unaiverse.uai.validate¶
A block that arrives on the network is attacker-controlled JSON. Before the package draws it, describes it to a model or reads an answer against it, validate_block checks its structure against the contract and builds a normalised copy of it called the spec. Every other module works on specs and never on raw objects: parse_message validates each block it extracts, the builders of compose validate what they are about to emit and the reading side trusts the field definitions it finds in a validated form. The narrative guide is Interactive messages.
The validator never raises on bad input. A malformed object comes back with ok equal to False and a list of error codes. A hostile peer can therefore at most make a block degrade to its alt or to its raw text (see parse_message).
Callers import from unaiverse.uai. The package re-exports validate_block, normalize_label, is_iso_date, is_https_url, interactive_fields and field_label. The type predicates (is_str, is_int, is_num, is_bool, is_obj, non_empty) and the regular expressions (ID_RE, NAME_RE, ISO_DATE_RE, MIME_RE, LANG_RE) are helpers that the other modules of the package import from here. They are documented below for completeness.
| Object | Role |
|---|---|
validate_block |
Checks one parsed block and returns {"ok", "spec", "errors", "kind"}. |
interactive_fields |
The fields of a form spec without its section rows. |
field_label |
The label of a field or its name when it has none. |
normalize_label |
The normal form of a label used for uniqueness and for tolerant matching. |
is_iso_date, is_https_url |
The two checks on strings that the contract defines. |
is_str, is_int, is_num, is_bool, is_obj, non_empty |
Type predicates with the semantics of JavaScript. |
ID_RE, NAME_RE, ISO_DATE_RE, MIME_RE, LANG_RE |
The patterns of ids, field names, dates, MIME types and language tags. |
from unaiverse.uai import validate_block
result = validate_block({"v": 1, "type": "media", "src": "https://a.org/x.PNG",
"mime": "Image/PNG", "alt": "a", "extra": 1})
# {'ok': True, 'spec': {'v': 1, 'type': 'media', 'src': 'https://a.org/x.PNG', 'mime': 'image/png', 'alt': 'a'},
# 'errors': [], 'kind': 'content'}
validate_block
¶
Source code in unaiverse/uai/validate.py
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 | |
Validates one block object as returned by json.loads on the body of a uai fence.
| Argument | Type | Default | Meaning |
|---|---|---|---|
obj |
any | required | The parsed body. Anything that is not a dict fails with not_an_object. |
The return value is always a dict with four keys.
| Key | Type | Meaning |
|---|---|---|
ok |
bool |
True when the block is valid. |
spec |
dict or None |
The normalised copy of the block when ok is True and None when it is False. |
errors |
list[str] |
The error codes, empty when ok is True. |
kind |
"content", "reply" or None |
"reply" for a block with kind, "content" for a block with type and None when the object is not a dict or carries both or neither key. |
The checks run in a fixed order and most of them stop at the first failure. The envelope comes first. v must be an integer in the JavaScript sense (1 and 1.0 both pass, True does not) and must not exceed PROTOCOL_VERSION. The object must then carry exactly one of type and kind as a string. A reply block (kind) is checked for kind == "reply", to and values. A content block (type) is checked for its alt first, then for its type, then for the keys of that type.
Normalisation. A valid spec is a new dict and never the input object. Because unknown keys are dropped at every level, a chart configuration or a callback inside a data block is never read. The MIME type of a media block is lower-cased. A select field always carries max (default 1). A section row keeps only type and label. An x-* block keeps only v, type and alt. A reply keeps v, kind, to, a shallow copy of values and, when usable, alt and raw.
Reply blocks. to must match ID_RE and values must be a dict. The values themselves are not checked here because the validator does not know the form. check_reply and apply_canonical check them against it. An alt that is missing, blank, not a string or longer than MAX_ALT_CHARS is dropped without an error. The same holds for raw. The validator keeps the non-blank strings of a list and drops the key when none survives.
validate_block({"v": 1, "kind": "reply", "to": "f", "values": {"x": 1}, "alt": "", "raw": ["", "hi", 3]})
# {'ok': True, 'spec': {'v': 1, 'kind': 'reply', 'to': 'f', 'values': {'x': 1}, 'raw': ['hi']},
# 'errors': [], 'kind': 'reply'}
Field types. A field whose type is not one of FIELD_TYPES degrades to "text". The degraded field keeps name, label, required, help and a string default. Its ui and every key specific to a type (maxLength, format, placeholder, min, max, unit, options) are dropped. Any known type keeps a string ui untouched and drops a ui that is not a string.
validate_block({"v": 1, "type": "form", "id": "f", "name": "n", "alt": "a",
"fields": [{"name": "x", "type": "color", "ui": "wheel", "default": "red", "maxLength": 3}]})
# spec["fields"] == [{'name': 'x', 'type': 'text', 'default': 'red'}]
Error codes. Codes that concern a single field end with : and the name of the field. The list below is complete for the current version.
| Code | Block | Cause |
|---|---|---|
not_an_object |
any | The body is not a JSON object. |
v_missing |
any | v is absent or not an integer. |
v_unsupported |
any | v is greater than PROTOCOL_VERSION. |
type_and_kind |
any | Both type and kind are strings. |
type_or_kind_missing |
any | Neither type nor kind is a string. |
kind_unknown |
reply | kind is not "reply". |
to_invalid |
reply | to is not an id of 1 to 32 characters in [A-Za-z0-9_-]. |
values_invalid |
reply | values is not an object. |
alt_missing |
content | alt is absent, not a string or blank. |
alt_too_long |
content | alt exceeds 2000 characters. |
type_unknown |
content | type is neither a block type nor an x-* type. |
src_invalid, poster_invalid |
media | The URL is not https with a host. |
mime_invalid |
media | mime is blank or does not match MIME_RE. |
title_invalid |
media | title is not a string or exceeds 120 characters. |
chart_invalid |
data | chart is not one of bar, line and pie. |
series_invalid |
data | series is not a list of 1 to 10 items. |
series_item_invalid |
data | A series is not an object with a string label and a list of at most 500 points. |
point_invalid |
data | A point is not a pair [x, y] with x a string or a finite number and y a finite number. |
id_invalid |
form | id does not match ID_RE. |
name_invalid |
form | name is blank, not a string or longer than 120 characters. |
lang_invalid |
form | lang does not match LANG_RE. |
aiHint_invalid |
form | aiHint is not a string or exceeds 2000 characters. |
progress_invalid |
form | progress is not two integers with 1 <= step <= total. |
fields_invalid |
form | fields is not a list of 1 to 40 items. |
field_invalid |
form | An item of fields is not an object. |
section_invalid |
form | A section row has a blank label or one over 120 characters. |
no_interactive_field |
form | Every item is a section row. |
too_many_fields |
form | More than 20 interactive fields. |
name_duplicate:<name> |
form | Two fields share a name. |
field_name_invalid |
field | name does not match NAME_RE. This code carries no name because the name is the problem. |
label_invalid:<name>, help_invalid:<name>, placeholder_invalid:<name> |
field | Not a string or longer than 120 (label) or 240 (help, placeholder) characters. |
required_invalid:<name> |
field | required is not a boolean. |
maxLength_invalid:<name> |
field | maxLength is not an integer of at least 1. |
format_invalid:<name> |
field | format of a text field is not email, url or tel. |
min_invalid:<name>, max_invalid:<name> |
field | A bound of the wrong type (a number, an integer, an ISO date). For a select it is a max under 1 or a min outside 0..max. |
range_invalid:<name> |
field | min is greater than max. |
unit_invalid:<name> |
field | unit is blank or longer than 16 characters. |
default_invalid:<name> |
field | default is not a valid value of the type. |
options_invalid:<name> |
field | options is not a list of 1 to 50 items. |
option_invalid:<name> |
field | An option is not an object with a string value and a non-blank label of at most 120 characters. |
option_label_comma:<name> |
field | An option label contains a comma. A comma separates the items of a multiple answer. |
option_label_duplicate:<name> |
field | Two labels are equal after normalize_label. |
option_value_duplicate:<name> |
field | Two options share a value. |
option_help_invalid:<name>, option_media_invalid:<name> |
field | The help of an option is not a string of at most 240 characters. The media of an option is not an https URL. |
validate_block({"v": 1, "type": "form", "id": "f", "name": "n", "alt": "a",
"fields": [{"type": "section", "label": "Part 1"},
{"name": "age", "type": "integer", "min": 10, "max": 5}]})
# {'ok': False, 'spec': None, 'errors': ['range_invalid:age'], 'kind': 'content'}
validate_block({"type": "media", "kind": "reply"})
# {'ok': False, 'spec': None, 'errors': ['v_missing', 'type_and_kind'], 'kind': None}
The current version has a few gaps that a caller should know about.
vis checked only from above. A block with"v": 0or"v": -3is valid.- The contract allows one form per message. The validator sees one block at a time and cannot enforce it.
parse_messagereturns every valid form of a message. - A select may declare a
maxgreater than the number of its options. A multi-selectdefaultmay repeat a value and may hold more values thanmax. - The
labelof a series in adatablock has no length limit. - For
datefields the bounds are compared as strings. ISO dates compare correctly in this way.
interactive_fields
¶
Returns the interactive fields of a form spec in their order and skips the section rows. The argument spec is a validated form spec (dict). None, a spec without fields and any non-form spec give []. Every function of the package that walks the fields of a form goes through this one.
interactive_fields({"fields": [{"type": "section", "label": "P"}, {"name": "a", "type": "text"}]})
# [{'name': 'a', 'type': 'text'}]
field_label
¶
Returns the human label of a field (str). The argument f is one validated field. When the author gave no label the function returns the name (field_label({"name": "x"}) returns "x"). The generated instruction, the readable projection and the corrective prompts all name fields through this function.
normalize_label
¶
Source code in unaiverse/uai/validate.py
Returns the normal form of a label. The function strips leading and trailing whitespace, collapses every run of whitespace to one space and lower-cases the result with str.lower. None becomes "" and any other value is first converted with str. The validator uses it to reject two option labels that differ only in case or spacing. The reading side uses it to match keys and options written by a person or a model.
The rule deliberately does no accent folding and no casefold. Both would make Python accept or reject labels differently from the JavaScript implementation.
is_iso_date
¶
Source code in unaiverse/uai/validate.py
Returns True when s is a string of the form YYYY-MM-DD (ASCII digits) that names a day of the calendar. The day is checked against the real length of its month in that year. February 29 is therefore valid only in a leap year. The year must be at least 1. Anything that is not a string returns False.
is_iso_date("2024-02-29") # True
is_iso_date("2024-02-30") # False
is_iso_date("0000-01-01") # False
is_https_url
¶
Source code in unaiverse/uai/validate.py
Returns True when s is a string that parses as a URL with scheme https and a non-empty host. The scheme comparison is exact and lower case. The check exists to keep javascript:, data: and http: URLs out of src, poster and option media.
is_https_url("https://a.org/x.png") # True
is_https_url("https://") # False
is_https_url("javascript:alert(1)") # False
is_str
¶
Returns True when v is a str.
is_int
¶
Source code in unaiverse/uai/validate.py
Returns True when v is an integer in the sense of JavaScript Number.isInteger. Such a value is an int that is not a bool or a finite float with no fractional part. is_int(3.0) is True and is_int(True) is False. The validator uses it for v, maxLength, progress and the bounds of integer fields. A value such as 3.0 therefore passes as an integer and stays a float in the spec.
is_num
¶
Returns True when v is a finite int or float that is not a bool. NaN and the infinities return False.
is_bool
¶
Returns True when v is a bool.
is_obj
¶
Returns True when v is a dict.
non_empty
¶
Returns True when v is a string that still holds a character after strip(). non_empty(" ") is False.
The compiled pattern of a form id and of the to of a reply: 1 to 32 characters from [A-Za-z0-9_-]. The validator applies it with fullmatch. The character classes are written out because \d in Python also matches non-ASCII digits.
The compiled pattern of a field name: a letter or _ followed by at most 63 letters, digits or _. The contract limit of 64 characters comes from this pattern.
The compiled pattern [0-9]{4}-[0-9]{2}-[0-9]{2} that is_iso_date applies before checking the calendar.
The compiled pattern of a MIME type, type/subtype with letters, digits and . + * - on both sides, matched without regard to case. The validator lower-cases the MIME type it stores.
The compiled pattern of the lang of a form: two or three lower-case letters followed by any number of subtags of 2 to 8 letters or digits, each introduced by -. "it", "en-GB" and "pt-BR" match. "EN" and "english" do not. The wording then follows the primary subtag (see template_for).