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
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2023-2024 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package confdb
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"github.com/snapcore/snapd/strutil"
)
type parser interface {
DatabagSchema
// expectsConstraints returns true if the parser must have a map definition
// with constraints or false, if it may have a simple name definition.
expectsConstraints() bool
// parseConstraints parses constraints for a type defined as a JSON object.
// Shouldn't be used with non-object/map type definitions.
parseConstraints(map[string]json.RawMessage) error
}
// ParseStorageSchema parses a JSON confdb schema and returns a Schema that can be
// used to validate storage.
func ParseStorageSchema(raw []byte) (*StorageSchema, error) {
var schemaDef map[string]json.RawMessage
err := json.Unmarshal(raw, &schemaDef)
if err != nil {
return nil, fmt.Errorf("cannot parse top level schema as map: %w", err)
}
if rawType, ok := schemaDef["type"]; ok {
var typ string
if err := json.Unmarshal(rawType, &typ); err != nil {
return nil, fmt.Errorf(`cannot parse top level schema's "type" entry: %w`, err)
}
if typ != "map" {
return nil, fmt.Errorf(`cannot parse top level schema: unexpected declared type %q, should be "map" or omitted`, typ)
}
}
if _, ok := schemaDef["schema"]; !ok {
return nil, fmt.Errorf(`cannot parse top level schema: must have a "schema" constraint`)
}
schema := new(StorageSchema)
if aliasesRaw, ok := schemaDef["aliases"]; ok {
var aliases map[string]json.RawMessage
if err := json.Unmarshal(aliasesRaw, &aliases); err != nil {
return nil, fmt.Errorf(`cannot parse aliases map: %w`, err)
}
// TODO: if we want to allow aliases to refer to others, this must be handled
// explicitly since the "aliases" map doesn't have any implicit order
schema.aliases = make(map[string]*userDefinedType, len(aliases))
for alias, typeDef := range aliases {
if !validAliasName.Match([]byte(alias)) {
return nil, fmt.Errorf(`cannot parse alias name %q: must match %s`, alias, validAliasName)
}
aliasSchema, err := schema.parse(typeDef)
if err != nil {
return nil, fmt.Errorf(`cannot parse alias %q: %w`, alias, err)
}
if aliasSchema.NestedEphemeral() {
return nil, fmt.Errorf(`cannot use "ephemeral" in user-defined type: %s`, alias)
}
schema.aliases[alias] = newUserDefinedType(aliasSchema)
}
}
schema.topLevel, err = schema.parse(raw)
if err != nil {
return nil, err
}
return schema, nil
}
// userDefinedType represents a user-defined type defined under "aliases".
type userDefinedType struct {
DatabagSchema
stringBased bool
}
func newUserDefinedType(s DatabagSchema) *userDefinedType {
_, ok := s.(*stringSchema)
return &userDefinedType{
DatabagSchema: s,
stringBased: ok,
}
}
func (v *userDefinedType) Ephemeral() bool {
// TODO: this isn't allowed for now
return false
}
// aliasReference represents a reference to a user-defined type in the schema.
type aliasReference struct {
alias *userDefinedType
ephemeral bool
}
// expectsConstraints return false because a reference to an alias doesn't
// necessarily require constraints.
func (*aliasReference) expectsConstraints() bool {
return false
}
// parseConstraints parses any constraints passed to the alias reference, if any
// exist.
func (v *aliasReference) parseConstraints(constraints map[string]json.RawMessage) (err error) {
v.ephemeral, err = parseEphemeral(constraints)
return err
}
// isStringBased returns true if this reference's base type is a string.
func (v *aliasReference) isStringBased() bool {
return v.alias.stringBased
}
// Validate validates the data according to the user-defined type referred to by
// this reference.
func (v *aliasReference) Validate(data []byte) error {
return v.alias.Validate(data)
}
// SchemaAt returns the alias reference itself if the path terminates at it. If
// not, it uses the user-defined type to resolve the path.
func (v *aliasReference) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
if len(path) == 0 {
return []DatabagSchema{v}, nil
}
return v.alias.SchemaAt(path)
}
// Type uses the user-defined alias to resolve the type.
func (v *aliasReference) Type() SchemaType {
return v.alias.Type()
}
func (v *aliasReference) Ephemeral() bool {
return v.ephemeral
}
func (s *aliasReference) NestedEphemeral() bool {
// TODO: aliases can't be marked as ephemeral for now (only their references)
// so there's no point in calling the alias' NestedEphemeral()
return s.Ephemeral()
}
// scalarSchema holds the data and behaviours common to all types.
type scalarSchema struct {
ephemeral bool
}
func (s scalarSchema) Ephemeral() bool {
return s.ephemeral
}
func (s scalarSchema) NestedEphemeral() bool {
return s.Ephemeral()
}
func (b *scalarSchema) parseConstraints(constraints map[string]json.RawMessage) (err error) {
b.ephemeral, err = parseEphemeral(constraints)
return err
}
func parseEphemeral(constraints map[string]json.RawMessage) (bool, error) {
if rawVal, ok := constraints["ephemeral"]; ok {
var eph bool
err := json.Unmarshal([]byte(rawVal), &eph)
if err != nil {
return false, err
}
return eph, nil
}
return false, nil
}
// StorageSchema represents a confdb storage schema and can be used to validate
// the storage.
type StorageSchema struct {
// topLevel is the schema for the top level map.
topLevel DatabagSchema
// aliases are schemas that can validate custom types defined by the user.
aliases map[string]*userDefinedType
}
// Validate validates the provided JSON object.
func (s *StorageSchema) Validate(raw []byte) error {
return s.topLevel.Validate(raw)
}
// SchemaAt returns the types that may be stored at the specified path.
func (s *StorageSchema) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
return s.topLevel.SchemaAt(path)
}
func (s *StorageSchema) Type() SchemaType {
return s.topLevel.Type()
}
func (s *StorageSchema) Ephemeral() bool {
return s.topLevel.Ephemeral()
}
func (s *StorageSchema) NestedEphemeral() bool {
return s.topLevel.NestedEphemeral()
}
func (s *StorageSchema) parse(raw json.RawMessage) (DatabagSchema, error) {
jsonType, err := parseTypeDefinition(raw)
if err != nil {
return nil, fmt.Errorf(`cannot parse type definition: %w`, err)
}
var typ string
var schemaDef map[string]json.RawMessage
switch typedVal := jsonType.(type) {
case string:
typ = typedVal
case []json.RawMessage:
alts, err := s.parseAlternatives(typedVal)
if err != nil {
return nil, fmt.Errorf(`cannot parse alternative types: %w`, err)
}
return alts, nil
case map[string]json.RawMessage:
schemaDef = typedVal
rawType, ok := schemaDef["type"]
if !ok {
typ = "map"
} else {
if err := json.Unmarshal(rawType, &typ); err != nil {
return nil, fmt.Errorf(`cannot parse "type" constraint in type definition: %w`, err)
}
}
default:
// cannot happen save for programmer error
return nil, fmt.Errorf(`cannot parse schema definition of JSON type %T`, jsonType)
}
schema, err := s.newTypeSchema(typ)
if err != nil {
return nil, err
}
// only parse the schema if it's a schema definition w/ constraints
if schemaDef != nil {
if err := schema.parseConstraints(schemaDef); err != nil {
return nil, err
}
} else if schema.expectsConstraints() {
return nil, fmt.Errorf(`cannot parse %q: must be schema definition with constraints`, typ)
}
return schema, nil
}
// parseTypeDefinition tries to parse the raw JSON as a list, a map or a string
// (the accepted ways to express types).
func parseTypeDefinition(raw json.RawMessage) (any, error) {
var typeErr *json.UnmarshalTypeError
var l []json.RawMessage
if err := json.Unmarshal(raw, &l); err == nil {
return l, nil
} else if !errors.As(err, &typeErr) {
return nil, err
}
var m map[string]json.RawMessage
if err := json.Unmarshal(raw, &m); err == nil {
return m, nil
} else if !errors.As(err, &typeErr) {
return nil, err
}
var s string
if err := json.Unmarshal(raw, &s); err == nil {
return s, nil
} else {
return nil, fmt.Errorf(`type must be expressed as map, string or list: %w`, err)
}
}
// parseAlternatives takes a list of alternative types, parses them and creates
// a schema that accepts values matching any alternative.
func (s *StorageSchema) parseAlternatives(alternatives []json.RawMessage) (*alternativesSchema, error) {
alt := &alternativesSchema{schemas: make([]DatabagSchema, 0, len(alternatives))}
for _, altRaw := range alternatives {
schema, err := s.parse(altRaw)
if err != nil {
return nil, err
}
alt.schemas = append(alt.schemas, schema)
}
if len(alt.schemas) == 0 {
return nil, fmt.Errorf(`alternative type list cannot be empty`)
}
flatAlts := flattenAlternatives(alt)
alt.schemas = flatAlts
return alt, nil
}
// flattenAlternatives takes the schemas that comprise the alternative schema
// and flattens them into a single list.
func flattenAlternatives(alt *alternativesSchema) []DatabagSchema {
var flat []DatabagSchema
for _, schema := range alt.schemas {
if altSchema, ok := schema.(*alternativesSchema); ok {
nestedAlts := flattenAlternatives(altSchema)
flat = append(flat, nestedAlts...)
} else {
flat = append(flat, schema)
}
}
return flat
}
func (s *StorageSchema) newTypeSchema(typ string) (parser, error) {
switch typ {
case "map":
return &mapSchema{topSchema: s}, nil
case "string":
return &stringSchema{}, nil
case "int":
return &intSchema{}, nil
case "any":
return &anySchema{}, nil
case "number":
return &numberSchema{}, nil
case "bool":
return &booleanSchema{}, nil
case "array":
return &arraySchema{topSchema: s}, nil
default:
if alias, ok := stripAlias(typ); ok {
return s.getAlias(alias)
}
return nil, fmt.Errorf("cannot parse unknown type %q", typ)
}
}
// stripAlias removes the ${...} used to refer to an alias and returns the alias
// name. If the string isn't wrapped in ${}, it returns an empty string and false.
func stripAlias(str string) (string, bool) {
if len(str) < 4 || !strings.HasPrefix(str, "${") || !strings.HasSuffix(str, "}") {
return "", false
}
return str[2 : len(str)-1], true
}
func (s *StorageSchema) getAlias(ref string) (*aliasReference, error) {
if alias, ok := s.aliases[ref]; ok {
return &aliasReference{alias: alias}, nil
}
return nil, fmt.Errorf("cannot find alias %q", ref)
}
type alternativesSchema struct {
// schemas holds schemas for the types allowed for the corresponding value.
schemas []DatabagSchema
}
// Validate that raw matches at least one of the schemas in the alternative list.
func (v *alternativesSchema) Validate(raw []byte) error {
var errs []error
for _, schema := range v.schemas {
err := schema.Validate(raw)
if err == nil {
return nil
}
errs = append(errs, err)
}
var sb strings.Builder
sb.WriteString("no matching schema:")
for i, err := range errs {
sb.WriteString("\n\t")
if i > 0 {
sb.WriteString("or ")
}
if verr, ok := err.(*ValidationError); ok {
err = verr.Err
if len(verr.Path) != 0 {
sb.WriteString("...\"")
for i, part := range verr.Path {
switch v := part.(type) {
case string:
if i > 0 {
sb.WriteRune('.')
}
sb.WriteString(v)
case int:
sb.WriteString(fmt.Sprintf("[%d]", v))
default:
// can only happen due to bug
sb.WriteString(".<n/a>")
}
}
sb.WriteString("\": ")
}
}
sb.WriteString(err.Error())
}
return validationErrorFrom(errors.New(sb.String()))
}
// SchemaAt returns the list of schemas at the end of the path or an error if
// the path cannot be followed.
func (v *alternativesSchema) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
if len(path) == 0 {
return v.schemas, nil
}
var types []DatabagSchema
var lastErr error
for _, alt := range v.schemas {
altTypes, err := alt.SchemaAt(path)
if err != nil {
// some schemas may permit the path
lastErr = err
continue
}
types = append(types, altTypes...)
}
// TODO: find better way to combine errors
if len(types) == 0 {
return nil, lastErr
}
return types, nil
}
func (v *alternativesSchema) Type() SchemaType {
return Alt
}
func (v *alternativesSchema) Ephemeral() bool { return false }
func (v *alternativesSchema) NestedEphemeral() bool {
for _, schema := range v.schemas {
if schema.NestedEphemeral() {
return true
}
}
return false
}
type mapSchema struct {
// topSchema is the schema for the top-level schema which contains the aliases.
topSchema *StorageSchema
// entrySchemas maps keys to their expected types. Alternatively, the schema
// can constrain key and/or value types.
entrySchemas map[string]DatabagSchema
// valueSchema validates that the map's values match a certain type.
valueSchema DatabagSchema
// keySchema validates that the map's key match a certain type.
keySchema DatabagSchema
// requiredCombs holds combinations of keys that an instance of the map is
// allowed to have.
requiredCombs [][]string
ephemeral bool
}
// Validate that raw is a valid map and meets the constraints set by the
// confdb storage schema.
func (v *mapSchema) Validate(raw []byte) error {
var mapValue map[string]json.RawMessage
if err := json.Unmarshal(raw, &mapValue); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return validationErrorf("expected map type but value was %s", typeErr.Value)
}
return validationErrorFrom(err)
}
if mapValue == nil {
return validationErrorf(`cannot accept null value for "map" type`)
}
if err := validMapKeys(mapValue); err != nil {
return validationErrorFrom(err)
}
if v.entrySchemas != nil {
for key := range mapValue {
if _, ok := v.entrySchemas[key]; !ok {
return validationErrorf(`map contains unexpected key %q`, key)
}
}
}
var missing bool
for _, required := range v.requiredCombs {
missing = false
for _, key := range required {
if _, ok := mapValue[key]; !ok {
missing = true
break
}
}
if !missing {
// matched possible combination of required keys so we can stop
break
}
}
if missing {
return validationErrorf(`cannot find required combinations of keys`)
}
if v.entrySchemas != nil {
for key, val := range mapValue {
if validator, ok := v.entrySchemas[key]; ok {
if err := validator.Validate(val); err != nil {
var valErr *ValidationError
if errors.As(err, &valErr) {
valErr.Path = append([]any{key}, valErr.Path...)
}
return err
}
}
}
// all required entries are present and validated
return nil
}
if v.keySchema != nil {
for k := range mapValue {
rawKey, err := json.Marshal(k)
if err != nil {
return fmt.Errorf("internal error: %w", err)
}
if err := v.keySchema.Validate(rawKey); err != nil {
var valErr *ValidationError
if errors.As(err, &valErr) {
valErr.Path = append([]any{k}, valErr.Path...)
}
return err
}
}
}
if v.valueSchema != nil {
for k, val := range mapValue {
if err := v.valueSchema.Validate(val); err != nil {
var valErr *ValidationError
if errors.As(err, &valErr) {
valErr.Path = append([]any{k}, valErr.Path...)
}
return err
}
}
}
return nil
}
func validMapKeys(v map[string]json.RawMessage) error {
for k := range v {
if !validSubkey.Match([]byte(k)) {
return fmt.Errorf(`key %q doesn't conform to required format: %s`, k, validSubkey.String())
}
}
return nil
}
// SchemaAt returns the Map schema if this is the last path element. If not, it
// calls SchemaAt for the next path element's schema if the path is valid.
func (v *mapSchema) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
if len(path) == 0 {
return []DatabagSchema{v}, nil
}
key := path[0]
if key.Type() != MapKeyType && key.Type() != KeyPlaceholderType {
return nil, schemaAtErrorf(path, `cannot use %q as key in map`, key)
}
if v.entrySchemas != nil {
if key.Type() == MapKeyType {
// the subkey is a literal map key so there has to be a corresponding entry
valSchema, ok := v.entrySchemas[key.Name()]
if !ok {
return nil, schemaAtErrorf(path, `cannot use %q as key in map`, key)
}
return valSchema.SchemaAt(path[1:])
}
// since the path has a placeholder, we don't require it to be accepted by
// all sub-schemas but it should be by at least one
var schemas []DatabagSchema
var lastErr error
for _, valSchema := range v.entrySchemas {
schema, err := valSchema.SchemaAt(path[1:])
if err != nil {
lastErr = err
continue
}
schemas = append(schemas, schema...)
}
if len(schemas) == 0 {
return nil, lastErr
}
return schemas, nil
}
// using key/value constraints instead
return v.valueSchema.SchemaAt(path[1:])
}
// Type returns the Map type.
func (v *mapSchema) Type() SchemaType {
return Map
}
func (v *mapSchema) Ephemeral() bool {
return v.ephemeral
}
func (v *mapSchema) NestedEphemeral() bool {
if v.Ephemeral() {
return true
}
for _, schema := range v.entrySchemas {
if schema.NestedEphemeral() {
return true
}
}
if v.keySchema != nil {
if v.keySchema.NestedEphemeral() {
return true
}
}
return v.valueSchema != nil && v.valueSchema.NestedEphemeral()
}
func (v *mapSchema) parseConstraints(constraints map[string]json.RawMessage) error {
ephemeral, err := parseEphemeral(constraints)
if err != nil {
return err
}
v.ephemeral = ephemeral
err = checkExclusiveMapConstraints(constraints)
if err != nil {
return fmt.Errorf(`cannot parse map: %w`, err)
}
// maps can be "schemas" with types for specific entries and optional "required" constraints
if rawEntries, ok := constraints["schema"]; ok {
var entries map[string]json.RawMessage
if err := json.Unmarshal(rawEntries, &entries); err != nil {
return fmt.Errorf(`cannot parse map's "schema" constraint: %v`, err)
}
if err := validMapKeys(entries); err != nil {
return fmt.Errorf(`cannot parse map: %w`, err)
}
v.entrySchemas = make(map[string]DatabagSchema, len(entries))
for key, value := range entries {
entrySchema, err := v.topSchema.parse(value)
if err != nil {
return err
}
v.entrySchemas[key] = entrySchema
}
// "required" can be a list of keys or many lists of alternative combinations
if rawRequired, ok := constraints["required"]; ok {
var requiredCombs [][]string
if err := json.Unmarshal(rawRequired, &requiredCombs); err != nil {
var typeErr *json.UnmarshalTypeError
if !errors.As(err, &typeErr) {
return fmt.Errorf(`cannot parse map's "required" constraint: %v`, err)
}
var required []string
if err := json.Unmarshal(rawRequired, &required); err != nil {
return fmt.Errorf(`cannot parse map's "required" constraint: %v`, err)
}
v.requiredCombs = [][]string{required}
} else {
v.requiredCombs = requiredCombs
}
for _, requiredComb := range v.requiredCombs {
for _, required := range requiredComb {
if _, ok := v.entrySchemas[required]; !ok {
return fmt.Errorf(`cannot parse map's "required" constraint: required key %q must have schema entry`, required)
}
}
}
}
return nil
}
// map can not specify "schemas" and constrain the type of keys and values instead
rawKeyDef, ok := constraints["keys"]
if ok {
if v.keySchema, err = v.parseMapKeyType(rawKeyDef); err != nil {
return fmt.Errorf(`cannot parse "keys" constraint: %w`, err)
}
}
rawValuesDef, ok := constraints["values"]
if ok {
v.valueSchema, err = v.topSchema.parse(rawValuesDef)
if err != nil {
return err
}
}
if v.entrySchemas == nil && v.keySchema == nil && v.valueSchema == nil {
return fmt.Errorf(`cannot parse map: must have "schema" or "keys"/"values" constraint`)
}
return nil
}
// checkExclusiveMapConstraints checks if the map contains mutually exclusive constraints.
func checkExclusiveMapConstraints(obj map[string]json.RawMessage) error {
has := func(k string) bool {
_, ok := obj[k]
return ok
}
if has("required") && !has("schema") {
return fmt.Errorf(`cannot use "required" without "schema" constraint`)
}
if has("schema") && has("keys") {
return fmt.Errorf(`cannot use "schema" and "keys" constraints simultaneously`)
}
if has("schema") && has("values") {
return fmt.Errorf(`cannot use "schema" and "values" constraints simultaneously`)
}
return nil
}
func (v *mapSchema) parseMapKeyType(raw json.RawMessage) (DatabagSchema, error) {
var typ string
if err := json.Unmarshal(raw, &typ); err != nil {
var typeErr *json.UnmarshalTypeError
if !errors.As(err, &typeErr) {
return nil, err
}
var schemaDef map[string]json.RawMessage
if err := json.Unmarshal(raw, &schemaDef); err != nil {
return nil, err
}
if rawType, ok := schemaDef["type"]; ok {
if err := json.Unmarshal(rawType, &typ); err != nil {
return nil, err
}
if typ != "string" {
return nil, fmt.Errorf(`must be based on string but type was %s`, typ)
}
}
schema := &stringSchema{}
if err := schema.parseConstraints(schemaDef); err != nil {
return nil, err
}
return schema, nil
}
if typ == "string" {
return &stringSchema{}, nil
}
if aliasName, ok := stripAlias(typ); ok {
alias, err := v.topSchema.getAlias(aliasName)
if err != nil {
return nil, err
}
if !alias.isStringBased() {
return nil, fmt.Errorf(`key type %q must be based on string`, aliasName)
}
return alias, nil
}
return nil, fmt.Errorf(`keys must be based on string but type was %s`, typ)
}
func (v *mapSchema) expectsConstraints() bool { return true }
type stringSchema struct {
scalarSchema
// pattern is a regex pattern that the string must match.
pattern *regexp.Regexp
// choices holds the possible values the string can take, if non-empty.
choices []string
}
// Validate that raw is a valid string and meets the schema's constraints.
func (v *stringSchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var value *string
if err := json.Unmarshal(raw, &value); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return fmt.Errorf("expected string type but value was %s", typeErr.Value)
}
return err
}
if value == nil {
return fmt.Errorf(`cannot accept null value for "string" type`)
}
if len(v.choices) != 0 && !strutil.ListContains(v.choices, *value) {
return fmt.Errorf(`string %q is not one of the allowed choices`, *value)
}
if v.pattern != nil && !v.pattern.Match([]byte(*value)) {
return fmt.Errorf(`expected string matching %s but value was %q`, v.pattern.String(), *value)
}
return nil
}
// SchemaAt returns the string schema if the path terminates at this schema and
// an error if not.
func (v *stringSchema) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
if len(path) != 0 {
return nil, schemaAtErrorf(path, `cannot follow path beyond "string" type`)
}
return []DatabagSchema{v}, nil
}
func (v *stringSchema) Type() SchemaType {
return String
}
func (v *stringSchema) parseConstraints(constraints map[string]json.RawMessage) error {
if err := v.scalarSchema.parseConstraints(constraints); err != nil {
return err
}
if rawChoices, ok := constraints["choices"]; ok {
var choices []string
if err := json.Unmarshal(rawChoices, &choices); err != nil {
return fmt.Errorf(`cannot parse "choices" constraint: %w`, err)
}
if len(choices) == 0 {
return fmt.Errorf(`cannot have a "choices" constraint with an empty list`)
}
v.choices = choices
}
if rawPattern, ok := constraints["pattern"]; ok {
if v.choices != nil {
return fmt.Errorf(`cannot use "choices" and "pattern" constraints in same schema`)
}
var patt string
err := json.Unmarshal(rawPattern, &patt)
if err != nil {
return fmt.Errorf(`cannot parse "pattern" constraint: %w`, err)
}
if v.pattern, err = regexp.Compile(patt); err != nil {
return fmt.Errorf(`cannot parse "pattern" constraint: %w`, err)
}
}
return nil
}
func (v *stringSchema) expectsConstraints() bool { return false }
type intSchema struct {
scalarSchema
min *int64
max *int64
choices []int64
}
// Validate that raw is a valid integer and meets the schema's constraints.
func (v *intSchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var num *int64
if err := json.Unmarshal(raw, &num); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return fmt.Errorf("expected int type but value was %s", typeErr.Value)
}
return err
}
if num == nil {
return fmt.Errorf(`cannot accept null value for "int" type`)
}
return validateNumber(*num, v.choices, v.min, v.max)
}
// SchemaAt returns the int schema if the path terminates here and an error if
// not.
func (v *intSchema) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
if len(path) != 0 {
return nil, schemaAtErrorf(path, `cannot follow path beyond "int" type`)
}
return []DatabagSchema{v}, nil
}
// Type returns the Int schema type.
func (v *intSchema) Type() SchemaType {
return Int
}
func (v *intSchema) parseConstraints(constraints map[string]json.RawMessage) error {
if err := v.scalarSchema.parseConstraints(constraints); err != nil {
return err
}
if rawChoices, ok := constraints["choices"]; ok {
var choices []int64
err := json.Unmarshal(rawChoices, &choices)
if err != nil {
return fmt.Errorf(`cannot parse "choices" constraint: %v`, err)
}
if len(choices) == 0 {
return fmt.Errorf(`cannot have "choices" constraint with empty list`)
}
v.choices = choices
}
if rawMin, ok := constraints["min"]; ok {
if v.choices != nil {
return fmt.Errorf(`cannot have "choices" and "min" constraints`)
}
var min int64
if err := json.Unmarshal(rawMin, &min); err != nil {
return fmt.Errorf(`cannot parse "min" constraint: %v`, err)
}
v.min = &min
}
if rawMax, ok := constraints["max"]; ok {
if v.choices != nil {
return fmt.Errorf(`cannot have "choices" and "max" constraints`)
}
var max int64
if err := json.Unmarshal(rawMax, &max); err != nil {
return fmt.Errorf(`cannot parse "max" constraint: %v`, err)
}
v.max = &max
}
if v.min != nil && v.max != nil && *v.min > *v.max {
return fmt.Errorf(`cannot have "min" constraint with value greater than "max"`)
}
return nil
}
func (v *intSchema) expectsConstraints() bool { return false }
type anySchema struct {
scalarSchema
}
func (v *anySchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var val any
if err := json.Unmarshal(raw, &val); err != nil {
return err
}
if val == nil {
return fmt.Errorf(`cannot accept null value for "any" type`)
}
return nil
}
func (v *anySchema) parseConstraints(constraints map[string]json.RawMessage) error {
return v.scalarSchema.parseConstraints(constraints)
}
// SchemaAt returns the "any" schema.
func (v *anySchema) SchemaAt([]Accessor) ([]DatabagSchema, error) {
return []DatabagSchema{v}, nil
}
// Type returns the Any schema type.
func (v *anySchema) Type() SchemaType {
return Any
}
func (v *anySchema) expectsConstraints() bool { return false }
type numberSchema struct {
scalarSchema
min *float64
max *float64
choices []float64
}
// Validate that raw is a valid number and meets the schema's constraints.
func (v *numberSchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var num *float64
if err := json.Unmarshal(raw, &num); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return fmt.Errorf("expected number type but value was %s", typeErr.Value)
}
return err
}
if num == nil {
return fmt.Errorf(`cannot accept null value for "number" type`)
}
return validateNumber(*num, v.choices, v.min, v.max)
}
// SchemaAt returns the number schema if the path terminates here and an error if
// not.
func (v *numberSchema) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
if len(path) != 0 {
return nil, schemaAtErrorf(path, `cannot follow path beyond "number" type`)
}
return []DatabagSchema{v}, nil
}
// Type returns the Number schema type.
func (v *numberSchema) Type() SchemaType {
return Number
}
func validateNumber[Num ~int64 | ~float64](num Num, choices []Num, min, max *Num) error {
if len(choices) != 0 {
var found bool
for _, choice := range choices {
if num == choice {
found = true
break
}
}
if !found {
return fmt.Errorf(`%v is not one of the allowed choices`, num)
}
}
// these comparisons are susceptible to floating-point errors but given that
// this won't be used for general storage it should be precise enough
if min != nil && num < *min {
return fmt.Errorf(`%v is less than the allowed minimum %v`, num, *min)
}
if max != nil && num > *max {
return fmt.Errorf(`%v is greater than the allowed maximum %v`, num, *max)
}
return nil
}
func (v *numberSchema) parseConstraints(constraints map[string]json.RawMessage) error {
if err := v.scalarSchema.parseConstraints(constraints); err != nil {
return err
}
if rawChoices, ok := constraints["choices"]; ok {
var choices []float64
err := json.Unmarshal(rawChoices, &choices)
if err != nil {
return fmt.Errorf(`cannot parse "choices" constraint: %v`, err)
}
if len(choices) == 0 {
return fmt.Errorf(`cannot have "choices" constraint with empty list`)
}
v.choices = choices
}
if rawMin, ok := constraints["min"]; ok {
if v.choices != nil {
return fmt.Errorf(`cannot have "choices" and "min" constraints`)
}
var min float64
if err := json.Unmarshal(rawMin, &min); err != nil {
return fmt.Errorf(`cannot parse "min" constraint: %v`, err)
}
v.min = &min
}
if rawMax, ok := constraints["max"]; ok {
if v.choices != nil {
return fmt.Errorf(`cannot have "choices" and "max" constraints`)
}
var max float64
if err := json.Unmarshal(rawMax, &max); err != nil {
return fmt.Errorf(`cannot parse "max" constraint: %v`, err)
}
v.max = &max
}
if v.min != nil && v.max != nil && *v.min > *v.max {
return fmt.Errorf(`cannot have "min" constraint with value greater than "max"`)
}
return nil
}
func (v *numberSchema) expectsConstraints() bool { return false }
type booleanSchema struct {
scalarSchema
}
func (v *booleanSchema) Validate(raw []byte) (err error) {
defer func() {
if err != nil {
err = validationErrorFrom(err)
}
}()
var val *bool
if err := json.Unmarshal(raw, &val); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return fmt.Errorf("expected bool type but value was %s", typeErr.Value)
}
return err
}
if val == nil {
return fmt.Errorf(`cannot accept null value for "bool" type`)
}
return nil
}
// SchemaAt returns the boolean schema if the path terminates here and an error
// if not.
func (v *booleanSchema) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
if len(path) != 0 {
return nil, schemaAtErrorf(path, `cannot follow path beyond "bool" type`)
}
return []DatabagSchema{v}, nil
}
// Type return the Bool type.
func (v *booleanSchema) Type() SchemaType {
return Bool
}
func (v *booleanSchema) parseConstraints(constraints map[string]json.RawMessage) error {
return v.scalarSchema.parseConstraints(constraints)
}
func (v *booleanSchema) expectsConstraints() bool { return false }
type arraySchema struct {
// topSchema is the schema for the top-level schema which contains the aliases.
topSchema *StorageSchema
// elementType represents the type of the array's elements and can be used to
// validate them.
elementType DatabagSchema
// unique is true if the array should not contain duplicates.
unique bool
ephemeral bool
}
func (v *arraySchema) Validate(raw []byte) error {
var array *[]json.RawMessage
if err := json.Unmarshal(raw, &array); err != nil {
typeErr := &json.UnmarshalTypeError{}
if errors.As(err, &typeErr) {
return validationErrorf("expected array type but value was %s", typeErr.Value)
}
return validationErrorFrom(err)
}
if array == nil {
return validationErrorf(`cannot accept null value for "array" type`)
}
for e, val := range *array {
if err := v.elementType.Validate([]byte(val)); err != nil {
var vErr *ValidationError
if errors.As(err, &vErr) {
vErr.Path = append([]any{e}, vErr.Path...)
}
return err
}
}
if v.unique {
valSet := make(map[string]struct{}, len(*array))
for _, val := range *array {
encodedVal := string(val)
if _, ok := valSet[encodedVal]; ok {
return validationErrorf(`cannot accept duplicate values for array with "unique" constraint`)
}
valSet[encodedVal] = struct{}{}
}
}
return nil
}
// SchemaAt returns the array schema the path is empty. Otherwise, it calls SchemaAt
// for the next path element's schema if the path is valid.
func (v *arraySchema) SchemaAt(path []Accessor) ([]DatabagSchema, error) {
if len(path) == 0 {
return []DatabagSchema{v}, nil
}
// key can be a number or a placeholder in square brackets ([1] or [{n}])
key := path[0]
if key.Type() != IndexPlaceholderType && key.Type() != ListIndexType {
return nil, schemaAtErrorf(path, `key %q cannot be used to index array`, key)
}
return v.elementType.SchemaAt(path[1:])
}
// Type returns the Array schema type.
func (v *arraySchema) Type() SchemaType {
return Array
}
func (v *arraySchema) Ephemeral() bool {
return v.ephemeral
}
func (v *arraySchema) NestedEphemeral() bool {
return v.Ephemeral() || v.elementType.NestedEphemeral()
}
func (v *arraySchema) parseConstraints(constraints map[string]json.RawMessage) error {
eph, err := parseEphemeral(constraints)
if err != nil {
return err
}
v.ephemeral = eph
rawValues, ok := constraints["values"]
if !ok {
return fmt.Errorf(`cannot parse "array": must have "values" constraint`)
}
typ, err := v.topSchema.parse(rawValues)
if err != nil {
return fmt.Errorf(`cannot parse "array" values type: %v`, err)
}
v.elementType = typ
if rawUnique, ok := constraints["unique"]; ok {
var unique bool
if err := json.Unmarshal(rawUnique, &unique); err != nil {
return fmt.Errorf(`cannot parse array's "unique" constraint: %v`, err)
}
v.unique = unique
}
return nil
}
func (v *arraySchema) expectsConstraints() bool { return true }
// TODO: keep a list of expected types (to support alternatives), an actual type/value
// and then optional unmet constraints for the expected types. Then this could be used
// to have more concise errors when there are many possible types
// https://github.com/snapcore/snapd/pull/13502#discussion_r1463658230
type ValidationError struct {
Path []any
Err error
}
func (v *ValidationError) Error() string {
var msg string
if len(v.Path) == 0 {
msg = "cannot accept top level element"
} else {
var sb strings.Builder
for i, part := range v.Path {
switch v := part.(type) {
case string:
if i > 0 {
sb.WriteRune('.')
}
sb.WriteString(v)
case int:
sb.WriteString(fmt.Sprintf("[%d]", v))
default:
// can only happen due to bug
sb.WriteString(".<n/a>")
}
}
msg = fmt.Sprintf("cannot accept element in %q", sb.String())
}
return fmt.Sprintf("%s: %v", msg, v.Err)
}
func validationErrorFrom(err error) error {
return &ValidationError{Err: err}
}
func validationErrorf(format string, v ...any) error {
return &ValidationError{Err: fmt.Errorf(format, v...)}
}
type schemaAtError struct {
left int
err error
}
func (e *schemaAtError) Error() string {
return e.err.Error()
}
func schemaAtErrorf(path []Accessor, format string, v ...any) error {
return &schemaAtError{
left: len(path),
err: fmt.Errorf(format, v...),
}
}
|