Перейти к содержанию

English fallback

This translation is missing; the canonical English reference follows.

Web request contracts

Experimental structural endpoints, request templates and injection locations. These contracts resolve neither credentials nor execution authority.

fuzzy1337.requests

Experimental structural web requests without values, execution, or scope authority.

InjectionLocation

Bases: StrEnum

Select one typed input coordinate without providing an injection payload.

Source code in fuzzy1337/requests.py
41
42
43
44
45
46
47
48
49
50
51
class InjectionLocation(StrEnum):
    """Select one typed input coordinate without providing an injection payload."""

    QUERY = "query"
    BODY = "body"
    JSON = "json"
    COOKIE = "cookie"
    HEADER = "header"
    PATH = "path"
    GRAPHQL = "graphql"
    MULTIPART = "multipart"

BodyKind

Bases: StrEnum

Describe the runtime body encoding while storing no body values or bytes.

Source code in fuzzy1337/requests.py
54
55
56
57
58
59
60
61
62
class BodyKind(StrEnum):
    """Describe the runtime body encoding while storing no body values or bytes."""

    NONE = "none"
    FORM = "form"
    TEXT = "text"
    JSON = "json"
    GRAPHQL = "graphql"
    MULTIPART = "multipart"

BindingSource

Bases: StrEnum

Distinguish caller input names from separately owned session input names.

Source code in fuzzy1337/requests.py
65
66
67
68
69
class BindingSource(StrEnum):
    """Distinguish caller input names from separately owned session input names."""

    INPUT = "input"
    SESSION = "session"

ValueBinding dataclass

Name a runtime value source rather than persisting its content.

Source code in fuzzy1337/requests.py
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
@dataclass(frozen=True, slots=True)
class ValueBinding:
    """Name a runtime value source rather than persisting its content."""

    name: str
    source: BindingSource = BindingSource.INPUT

    def __post_init__(self) -> None:
        """Require a bounded non-secret identifier and an explicit source enum."""

        RequireIdentifier(self.name, "binding name")

        if len(self.name) > 64 or not isinstance(self.source, BindingSource):
            raise ValueError("binding requires a bounded name and BindingSource")

    def ToDict(self) -> dict[str, object]:
        """Return symbolic fields without resolving a value.

        Returns:
            Exact schema fields for an unresolved named input.
        """

        return {"name": self.name, "source": self.source.value}

    @classmethod
    def FromDict(cls, value: object) -> ValueBinding:
        """Decode an exact symbolic binding and reject literal-value extension fields.

        Args:
            value: Decoded binding object.

        Returns:
            Validated binding without side effects.

        Raises:
            ValueError: Fields, source, or identifier are invalid.
        """

        record = WorkspaceFields(value, {"name", "source"}, "value binding")
        source = RequireWorkspaceText(record["source"], "binding source")

        if source not in tuple(item.value for item in BindingSource):
            raise ValueError("binding source must be input or session")

        return cls(
            RequireWorkspaceText(record["name"], "binding name"),
            BindingSource(source),
        )

__post_init__() -> None

Require a bounded non-secret identifier and an explicit source enum.

Source code in fuzzy1337/requests.py
114
115
116
117
118
119
120
def __post_init__(self) -> None:
    """Require a bounded non-secret identifier and an explicit source enum."""

    RequireIdentifier(self.name, "binding name")

    if len(self.name) > 64 or not isinstance(self.source, BindingSource):
        raise ValueError("binding requires a bounded name and BindingSource")

ToDict() -> dict[str, object]

Return symbolic fields without resolving a value.

Returns:

Type Description
dict[str, object]

Exact schema fields for an unresolved named input.

Source code in fuzzy1337/requests.py
122
123
124
125
126
127
128
129
def ToDict(self) -> dict[str, object]:
    """Return symbolic fields without resolving a value.

    Returns:
        Exact schema fields for an unresolved named input.
    """

    return {"name": self.name, "source": self.source.value}

FromDict(value: object) -> ValueBinding classmethod

Decode an exact symbolic binding and reject literal-value extension fields.

Parameters:

Name Type Description Default
value object

Decoded binding object.

required

Returns:

Type Description
ValueBinding

Validated binding without side effects.

Raises:

Type Description
ValueError

Fields, source, or identifier are invalid.

Source code in fuzzy1337/requests.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
@classmethod
def FromDict(cls, value: object) -> ValueBinding:
    """Decode an exact symbolic binding and reject literal-value extension fields.

    Args:
        value: Decoded binding object.

    Returns:
        Validated binding without side effects.

    Raises:
        ValueError: Fields, source, or identifier are invalid.
    """

    record = WorkspaceFields(value, {"name", "source"}, "value binding")
    source = RequireWorkspaceText(record["source"], "binding source")

    if source not in tuple(item.value for item in BindingSource):
        raise ValueError("binding source must be input or session")

    return cls(
        RequireWorkspaceText(record["name"], "binding name"),
        BindingSource(source),
    )

SessionReference dataclass

Reference a separately owned session using non-secret workspace-local identifiers.

Source code in fuzzy1337/requests.py
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
@dataclass(frozen=True, slots=True)
class SessionReference:
    """Reference a separately owned session using non-secret workspace-local identifiers."""

    workspace_id: str
    session_id: str

    def __post_init__(self) -> None:
        """Require bounded identifiers without reading credentials or session state."""

        for field_name in ("workspace_id", "session_id"):
            value = getattr(self, field_name)
            RequireIdentifier(value, field_name)

            if len(value) > 64:
                raise ValueError("session identifiers must not exceed 64 characters")

    def Reference(self) -> str:
        """Expose a workspace-bound reference that does not prove session availability.

        Returns:
            Deterministic session digest independent of credentials.
        """

        return RequestDigest("session", self.ToDict())

    def ToDict(self) -> dict[str, object]:
        """Render the owned identifiers without credential material.

        Returns:
            Workspace and session identifier fields.
        """

        return {"workspace_id": self.workspace_id, "session_id": self.session_id}

    @classmethod
    def FromDict(cls, value: object) -> SessionReference:
        """Decode a reference rather than a captured authenticated session.

        Args:
            value: Exact workspace/session identifier object.

        Returns:
            Validated unresolved session reference.

        Raises:
            ValueError: A field is unknown, absent, or not an identifier.
        """

        record = WorkspaceFields(value, {"workspace_id", "session_id"}, "session reference")

        return cls(
            RequireWorkspaceText(record["workspace_id"], "workspace_id"),
            RequireWorkspaceText(record["session_id"], "session_id"),
        )

__post_init__() -> None

Require bounded identifiers without reading credentials or session state.

Source code in fuzzy1337/requests.py
164
165
166
167
168
169
170
171
172
def __post_init__(self) -> None:
    """Require bounded identifiers without reading credentials or session state."""

    for field_name in ("workspace_id", "session_id"):
        value = getattr(self, field_name)
        RequireIdentifier(value, field_name)

        if len(value) > 64:
            raise ValueError("session identifiers must not exceed 64 characters")

Reference() -> str

Expose a workspace-bound reference that does not prove session availability.

Returns:

Type Description
str

Deterministic session digest independent of credentials.

Source code in fuzzy1337/requests.py
174
175
176
177
178
179
180
181
def Reference(self) -> str:
    """Expose a workspace-bound reference that does not prove session availability.

    Returns:
        Deterministic session digest independent of credentials.
    """

    return RequestDigest("session", self.ToDict())

ToDict() -> dict[str, object]

Render the owned identifiers without credential material.

Returns:

Type Description
dict[str, object]

Workspace and session identifier fields.

Source code in fuzzy1337/requests.py
183
184
185
186
187
188
189
190
def ToDict(self) -> dict[str, object]:
    """Render the owned identifiers without credential material.

    Returns:
        Workspace and session identifier fields.
    """

    return {"workspace_id": self.workspace_id, "session_id": self.session_id}

FromDict(value: object) -> SessionReference classmethod

Decode a reference rather than a captured authenticated session.

Parameters:

Name Type Description Default
value object

Exact workspace/session identifier object.

required

Returns:

Type Description
SessionReference

Validated unresolved session reference.

Raises:

Type Description
ValueError

A field is unknown, absent, or not an identifier.

Source code in fuzzy1337/requests.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
@classmethod
def FromDict(cls, value: object) -> SessionReference:
    """Decode a reference rather than a captured authenticated session.

    Args:
        value: Exact workspace/session identifier object.

    Returns:
        Validated unresolved session reference.

    Raises:
        ValueError: A field is unknown, absent, or not an identifier.
    """

    record = WorkspaceFields(value, {"workspace_id", "session_id"}, "session reference")

    return cls(
        RequireWorkspaceText(record["workspace_id"], "workspace_id"),
        RequireWorkspaceText(record["session_id"], "session_id"),
    )

Endpoint dataclass

Describe a structural HTTP endpoint in the existing Security Object Model namespace.

Source code in fuzzy1337/requests.py
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
@dataclass(frozen=True, slots=True)
class Endpoint:
    """Describe a structural HTTP endpoint in the existing Security Object Model namespace."""

    workspace_id: str
    origin: str
    path_template: str
    method: str = "GET"

    def __post_init__(self) -> None:
        """Canonicalize an offline origin/method and reject inline values or ambiguous paths."""

        RequireIdentifier(self.workspace_id, "workspace_id")
        canonical_url = NormalizeTarget(TargetKind.URL, self.origin)
        parsed = urlsplit(canonical_url)

        if parsed.path != "/" or parsed.query or "?" in self.origin:
            raise ValueError("endpoint origin must contain only an HTTP(S) authority")

        RequireWorkspaceText(self.path_template, "path_template")
        parts = self.path_template.split("/")[1:]

        if (
            len(self.path_template) > 1024 or not self.path_template.startswith("/")
            or len(parts) > 64
            or any(
                part in {".", ".."} or (part and not _PATH_SEGMENT_PATTERN.fullmatch(part))
                for part in parts
            )
            or "//" in self.path_template
        ):
            raise ValueError("path_template requires structural segments or named path variables")

        variables = self.PathVariables()

        if len(variables) != len(set(variables)):
            raise ValueError("path variables must have unique names")

        method = RequireWorkspaceText(self.method, "method").upper()

        if not _METHOD_PATTERN.fullmatch(method):
            raise ValueError("method must be a bounded HTTP method token")

        object.__setattr__(self, "origin", f"{parsed.scheme}://{parsed.netloc}")
        object.__setattr__(self, "method", method)

    def PathVariables(self) -> tuple[str, ...]:
        """Return declared structural path names without substituting runtime data.

        Returns:
            Ordered path variable names.
        """

        return tuple(re.findall(r"\{([A-Za-z_][A-Za-z0-9_]*)\}", self.path_template))

    def Identity(self) -> ObjectIdentity:
        """Reuse the SOM Endpoint identity rather than inventing another object store.

        Returns:
            Workspace-bound Endpoint natural key over canonical method/origin/path fields.
        """

        key = CanonicalModelJson({
            "origin": self.origin, "path_template": self.path_template, "method": self.method,
        }).decode("utf-8")

        return ObjectIdentity(self.workspace_id, ObjectKind.ENDPOINT, key)

    def ToDict(self) -> dict[str, object]:
        """Render canonical endpoint fields with their recomputable existing model reference.

        Returns:
            Endpoint fields and object reference, without request values.
        """

        return {
            "workspace_id": self.workspace_id, "origin": self.origin,
            "path_template": self.path_template, "method": self.method,
            "object_reference": self.Identity().Reference(),
        }

    @classmethod
    def FromDict(cls, value: object) -> Endpoint:
        """Decode stored canonical endpoint spelling and reject forged references.

        Args:
            value: Exact decoded endpoint object.

        Returns:
            Validated endpoint; alias spelling is accepted only by the constructor.

        Raises:
            ValueError: Fields, spelling or reference differ from the canonical endpoint.
        """

        record = WorkspaceFields(value, {
            "workspace_id", "origin", "path_template", "method", "object_reference",
        }, "endpoint")
        endpoint = cls(*(
            RequireWorkspaceText(record[key], key)
            for key in ("workspace_id", "origin", "path_template", "method")
        ))

        if record != endpoint.ToDict():
            raise ValueError("stored endpoint fields and reference must be canonical")

        return endpoint

__post_init__() -> None

Canonicalize an offline origin/method and reject inline values or ambiguous paths.

Source code in fuzzy1337/requests.py
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
def __post_init__(self) -> None:
    """Canonicalize an offline origin/method and reject inline values or ambiguous paths."""

    RequireIdentifier(self.workspace_id, "workspace_id")
    canonical_url = NormalizeTarget(TargetKind.URL, self.origin)
    parsed = urlsplit(canonical_url)

    if parsed.path != "/" or parsed.query or "?" in self.origin:
        raise ValueError("endpoint origin must contain only an HTTP(S) authority")

    RequireWorkspaceText(self.path_template, "path_template")
    parts = self.path_template.split("/")[1:]

    if (
        len(self.path_template) > 1024 or not self.path_template.startswith("/")
        or len(parts) > 64
        or any(
            part in {".", ".."} or (part and not _PATH_SEGMENT_PATTERN.fullmatch(part))
            for part in parts
        )
        or "//" in self.path_template
    ):
        raise ValueError("path_template requires structural segments or named path variables")

    variables = self.PathVariables()

    if len(variables) != len(set(variables)):
        raise ValueError("path variables must have unique names")

    method = RequireWorkspaceText(self.method, "method").upper()

    if not _METHOD_PATTERN.fullmatch(method):
        raise ValueError("method must be a bounded HTTP method token")

    object.__setattr__(self, "origin", f"{parsed.scheme}://{parsed.netloc}")
    object.__setattr__(self, "method", method)

PathVariables() -> tuple[str, ...]

Return declared structural path names without substituting runtime data.

Returns:

Type Description
tuple[str, ...]

Ordered path variable names.

Source code in fuzzy1337/requests.py
260
261
262
263
264
265
266
267
def PathVariables(self) -> tuple[str, ...]:
    """Return declared structural path names without substituting runtime data.

    Returns:
        Ordered path variable names.
    """

    return tuple(re.findall(r"\{([A-Za-z_][A-Za-z0-9_]*)\}", self.path_template))

Identity() -> ObjectIdentity

Reuse the SOM Endpoint identity rather than inventing another object store.

Returns:

Type Description
ObjectIdentity

Workspace-bound Endpoint natural key over canonical method/origin/path fields.

Source code in fuzzy1337/requests.py
269
270
271
272
273
274
275
276
277
278
279
280
def Identity(self) -> ObjectIdentity:
    """Reuse the SOM Endpoint identity rather than inventing another object store.

    Returns:
        Workspace-bound Endpoint natural key over canonical method/origin/path fields.
    """

    key = CanonicalModelJson({
        "origin": self.origin, "path_template": self.path_template, "method": self.method,
    }).decode("utf-8")

    return ObjectIdentity(self.workspace_id, ObjectKind.ENDPOINT, key)

ToDict() -> dict[str, object]

Render canonical endpoint fields with their recomputable existing model reference.

Returns:

Type Description
dict[str, object]

Endpoint fields and object reference, without request values.

Source code in fuzzy1337/requests.py
282
283
284
285
286
287
288
289
290
291
292
293
def ToDict(self) -> dict[str, object]:
    """Render canonical endpoint fields with their recomputable existing model reference.

    Returns:
        Endpoint fields and object reference, without request values.
    """

    return {
        "workspace_id": self.workspace_id, "origin": self.origin,
        "path_template": self.path_template, "method": self.method,
        "object_reference": self.Identity().Reference(),
    }

FromDict(value: object) -> Endpoint classmethod

Decode stored canonical endpoint spelling and reject forged references.

Parameters:

Name Type Description Default
value object

Exact decoded endpoint object.

required

Returns:

Type Description
Endpoint

Validated endpoint; alias spelling is accepted only by the constructor.

Raises:

Type Description
ValueError

Fields, spelling or reference differ from the canonical endpoint.

Source code in fuzzy1337/requests.py
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
@classmethod
def FromDict(cls, value: object) -> Endpoint:
    """Decode stored canonical endpoint spelling and reject forged references.

    Args:
        value: Exact decoded endpoint object.

    Returns:
        Validated endpoint; alias spelling is accepted only by the constructor.

    Raises:
        ValueError: Fields, spelling or reference differ from the canonical endpoint.
    """

    record = WorkspaceFields(value, {
        "workspace_id", "origin", "path_template", "method", "object_reference",
    }, "endpoint")
    endpoint = cls(*(
        RequireWorkspaceText(record[key], key)
        for key in ("workspace_id", "origin", "path_template", "method")
    ))

    if record != endpoint.ToDict():
        raise ValueError("stored endpoint fields and reference must be canonical")

    return endpoint

InjectionPoint dataclass

Address one typed value slot without storing its value or a mutation payload.

Source code in fuzzy1337/requests.py
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
@dataclass(frozen=True, slots=True)
class InjectionPoint:
    """Address one typed value slot without storing its value or a mutation payload."""

    location: InjectionLocation
    selector: str
    binding: ValueBinding
    occurrence: int = 0

    def __post_init__(self) -> None:
        """Validate location syntax and freeze header names before template-level checks."""

        if not isinstance(self.location, InjectionLocation) or not isinstance(
            self.binding, ValueBinding,
        ):
            raise ValueError("injection requires InjectionLocation and ValueBinding")

        occurrence = RequireWorkspaceInteger(self.occurrence, "occurrence")

        if occurrence > 1023 or not isinstance(self.selector, str):
            raise ValueError("injection requires a string selector and bounded occurrence")

        if self.location in {InjectionLocation.JSON, InjectionLocation.GRAPHQL}:
            RequirePointer(self.selector)

            if self.location is InjectionLocation.GRAPHQL and not re.fullmatch(
                r"/variables/[_A-Za-z][_0-9A-Za-z]{0,63}(?:/.*)?", self.selector,
            ):
                raise ValueError("GraphQL selector must address a variable")

        elif self.location is not InjectionLocation.BODY or self.selector != "":
            if not _NAME_PATTERN.fullmatch(self.selector):
                raise ValueError("selector must be a bounded structural input name")

        if self.location in {
            InjectionLocation.JSON, InjectionLocation.GRAPHQL, InjectionLocation.PATH,
        } or (self.location is InjectionLocation.BODY and self.selector == ""):
            if occurrence != 0:
                raise ValueError("this injection location has no repeated field occurrence")

        if self.location is InjectionLocation.HEADER:
            object.__setattr__(self, "selector", self.selector.lower())

    def Coordinate(self) -> tuple[str, str, int]:
        """Identify an injection position independently of its value binding.

        Returns:
            Location, selector and occurrence in canonical order.
        """

        return self.location.value, self.selector, self.occurrence

    def Reference(self, request_reference: str) -> str:
        """Bind an injection identity to one recomputable request template reference.

        Args:
            request_reference: Validated request digest from the owning template.

        Returns:
            Domain-separated injection reference.

        Raises:
            ValueError: The owner reference is malformed.
        """

        if not isinstance(request_reference, str) or not _REFERENCE_PATTERN.fullmatch(
            request_reference,
        ):
            raise ValueError("injection owner must be a request reference")

        return RequestDigest("injection", {
            "request_reference": request_reference, "coordinate": self.Coordinate(),
        })

    def ToDict(self) -> dict[str, object]:
        """Render a structural coordinate and symbolic binding.

        Returns:
            Exact location, selector, binding and occurrence fields.
        """

        return {
            "location": self.location.value, "selector": self.selector,
            "binding": self.binding.ToDict(), "occurrence": self.occurrence,
        }

    @classmethod
    def FromDict(cls, value: object) -> InjectionPoint:
        """Decode an exact injection descriptor without accepting captured values.

        Args:
            value: Decoded injection descriptor object.

        Returns:
            Validated immutable injection point.

        Raises:
            ValueError: Fields, coordinate, binding or stored spelling are invalid.
        """

        record = WorkspaceFields(value, {
            "location", "selector", "binding", "occurrence",
        }, "injection point")

        if not isinstance(record["selector"], str):
            raise ValueError("selector must be a string")

        location = RequireWorkspaceText(record["location"], "location")

        if location not in tuple(item.value for item in InjectionLocation):
            raise ValueError("location must select a supported injection coordinate")

        point = cls(
            InjectionLocation(location),
            record["selector"], ValueBinding.FromDict(record["binding"]),
            RequireWorkspaceInteger(record["occurrence"], "occurrence"),
        )

        if record != point.ToDict():
            raise ValueError("stored injection coordinate must be canonical")

        return point

__post_init__() -> None

Validate location syntax and freeze header names before template-level checks.

Source code in fuzzy1337/requests.py
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
def __post_init__(self) -> None:
    """Validate location syntax and freeze header names before template-level checks."""

    if not isinstance(self.location, InjectionLocation) or not isinstance(
        self.binding, ValueBinding,
    ):
        raise ValueError("injection requires InjectionLocation and ValueBinding")

    occurrence = RequireWorkspaceInteger(self.occurrence, "occurrence")

    if occurrence > 1023 or not isinstance(self.selector, str):
        raise ValueError("injection requires a string selector and bounded occurrence")

    if self.location in {InjectionLocation.JSON, InjectionLocation.GRAPHQL}:
        RequirePointer(self.selector)

        if self.location is InjectionLocation.GRAPHQL and not re.fullmatch(
            r"/variables/[_A-Za-z][_0-9A-Za-z]{0,63}(?:/.*)?", self.selector,
        ):
            raise ValueError("GraphQL selector must address a variable")

    elif self.location is not InjectionLocation.BODY or self.selector != "":
        if not _NAME_PATTERN.fullmatch(self.selector):
            raise ValueError("selector must be a bounded structural input name")

    if self.location in {
        InjectionLocation.JSON, InjectionLocation.GRAPHQL, InjectionLocation.PATH,
    } or (self.location is InjectionLocation.BODY and self.selector == ""):
        if occurrence != 0:
            raise ValueError("this injection location has no repeated field occurrence")

    if self.location is InjectionLocation.HEADER:
        object.__setattr__(self, "selector", self.selector.lower())

Coordinate() -> tuple[str, str, int]

Identify an injection position independently of its value binding.

Returns:

Type Description
tuple[str, str, int]

Location, selector and occurrence in canonical order.

Source code in fuzzy1337/requests.py
366
367
368
369
370
371
372
373
def Coordinate(self) -> tuple[str, str, int]:
    """Identify an injection position independently of its value binding.

    Returns:
        Location, selector and occurrence in canonical order.
    """

    return self.location.value, self.selector, self.occurrence

Reference(request_reference: str) -> str

Bind an injection identity to one recomputable request template reference.

Parameters:

Name Type Description Default
request_reference str

Validated request digest from the owning template.

required

Returns:

Type Description
str

Domain-separated injection reference.

Raises:

Type Description
ValueError

The owner reference is malformed.

Source code in fuzzy1337/requests.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def Reference(self, request_reference: str) -> str:
    """Bind an injection identity to one recomputable request template reference.

    Args:
        request_reference: Validated request digest from the owning template.

    Returns:
        Domain-separated injection reference.

    Raises:
        ValueError: The owner reference is malformed.
    """

    if not isinstance(request_reference, str) or not _REFERENCE_PATTERN.fullmatch(
        request_reference,
    ):
        raise ValueError("injection owner must be a request reference")

    return RequestDigest("injection", {
        "request_reference": request_reference, "coordinate": self.Coordinate(),
    })

ToDict() -> dict[str, object]

Render a structural coordinate and symbolic binding.

Returns:

Type Description
dict[str, object]

Exact location, selector, binding and occurrence fields.

Source code in fuzzy1337/requests.py
397
398
399
400
401
402
403
404
405
406
407
def ToDict(self) -> dict[str, object]:
    """Render a structural coordinate and symbolic binding.

    Returns:
        Exact location, selector, binding and occurrence fields.
    """

    return {
        "location": self.location.value, "selector": self.selector,
        "binding": self.binding.ToDict(), "occurrence": self.occurrence,
    }

FromDict(value: object) -> InjectionPoint classmethod

Decode an exact injection descriptor without accepting captured values.

Parameters:

Name Type Description Default
value object

Decoded injection descriptor object.

required

Returns:

Type Description
InjectionPoint

Validated immutable injection point.

Raises:

Type Description
ValueError

Fields, coordinate, binding or stored spelling are invalid.

Source code in fuzzy1337/requests.py
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
@classmethod
def FromDict(cls, value: object) -> InjectionPoint:
    """Decode an exact injection descriptor without accepting captured values.

    Args:
        value: Decoded injection descriptor object.

    Returns:
        Validated immutable injection point.

    Raises:
        ValueError: Fields, coordinate, binding or stored spelling are invalid.
    """

    record = WorkspaceFields(value, {
        "location", "selector", "binding", "occurrence",
    }, "injection point")

    if not isinstance(record["selector"], str):
        raise ValueError("selector must be a string")

    location = RequireWorkspaceText(record["location"], "location")

    if location not in tuple(item.value for item in InjectionLocation):
        raise ValueError("location must select a supported injection coordinate")

    point = cls(
        InjectionLocation(location),
        record["selector"], ValueBinding.FromDict(record["binding"]),
        RequireWorkspaceInteger(record["occurrence"], "occurrence"),
    )

    if record != point.ToDict():
        raise ValueError("stored injection coordinate must be canonical")

    return point

RequestTemplate dataclass

Group structural inputs, encoding and a session reference without resolving values.

Source code in fuzzy1337/requests.py
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
@dataclass(frozen=True, slots=True)
class RequestTemplate:
    """Group structural inputs, encoding and a session reference without resolving values."""

    endpoint: Endpoint
    injection_points: tuple[InjectionPoint, ...] = ()
    body_kind: BodyKind = BodyKind.NONE
    session_reference: SessionReference | None = None
    graphql_operation: str | None = None

    def __post_init__(self) -> None:
        """Require coherent locations, ownership and unique deterministic coordinates."""

        if not isinstance(self.endpoint, Endpoint) or not isinstance(self.body_kind, BodyKind):
            raise ValueError("template requires Endpoint and BodyKind")

        if not isinstance(self.injection_points, (tuple, list)) or len(
            self.injection_points,
        ) > MAX_INJECTION_POINTS:
            raise ValueError("injection_points must be a bounded sequence")

        if self.session_reference is not None and (
            not isinstance(self.session_reference, SessionReference)
            or self.session_reference.workspace_id != self.endpoint.workspace_id
        ):
            raise ValueError("session reference must belong to the endpoint workspace")

        if self.graphql_operation is not None and (
            self.body_kind is not BodyKind.GRAPHQL
            or not isinstance(self.graphql_operation, str)
            or not re.fullmatch(r"[_A-Za-z][_0-9A-Za-z]{0,63}", self.graphql_operation)
        ):
            raise ValueError("graphql_operation requires a GraphQL body and operation name")

        points: dict[tuple[str, str, int], InjectionPoint] = {}

        for point in self.injection_points:
            if not isinstance(point, InjectionPoint):
                raise ValueError("injection_points must contain InjectionPoint values")

            if point.Coordinate() in points:
                raise ValueError("injection coordinates must be unique")

            self.ValidatePoint(point)
            points[point.Coordinate()] = point

        object.__setattr__(self, "injection_points", tuple(points[key] for key in sorted(points)))

        if len(CanonicalModelJson(self.ToDict())) > MAX_REQUEST_BYTES:
            raise ValueError("request template exceeds its serialized size bound")

    def ValidatePoint(self, point: InjectionPoint) -> None:
        """Check encoding, path ownership and session-reference relationships.

        Args:
            point: Typed input descriptor from this template.

        Raises:
            ValueError: A descriptor cannot be represented by this template's structure.
        """

        expected = {
            InjectionLocation.BODY: BodyKind.TEXT if point.selector == "" else BodyKind.FORM,
            InjectionLocation.JSON: BodyKind.JSON,
            InjectionLocation.GRAPHQL: BodyKind.GRAPHQL,
            InjectionLocation.MULTIPART: BodyKind.MULTIPART,
        }.get(point.location)

        if expected is not None and self.body_kind is not expected:
            raise ValueError("injection location is incompatible with body_kind")

        if point.location is InjectionLocation.PATH and (
            point.selector not in self.endpoint.PathVariables()
        ):
            raise ValueError("path selector must reference a declared path variable")

        if point.binding.source is BindingSource.SESSION and self.session_reference is None:
            raise ValueError("session bindings require a session reference")

    def Fields(self) -> dict[str, object]:
        """Render identity fields without recursively including their digest.

        Returns:
            Strict schema-versioned structural fields, with deterministic point order.
        """

        return {
            "schema_version": REQUEST_SCHEMA_VERSION, "endpoint": self.endpoint.ToDict(),
            "body_kind": self.body_kind.value,
            "session_reference": (
                None if self.session_reference is None else self.session_reference.ToDict()
            ),
            "graphql_operation": self.graphql_operation,
            "injection_points": [point.ToDict() for point in self.injection_points],
        }

    def Reference(self) -> str:
        """Return a digest of the complete unresolved structural template.

        Returns:
            Canonical request reference, including session and symbolic binding identity.
        """

        return RequestDigest("request", self.Fields())

    def ToDict(self) -> dict[str, object]:
        """Render a complete schema-versioned template with a verifiable reference.

        Returns:
            Canonical serializable request template object.
        """

        return {**self.Fields(), "request_reference": self.Reference()}

    def ToJson(self) -> str:
        """Serialize a deterministic portable template without accessing runtime values.

        Returns:
            Strict UTF-8 JSON text with no trailing newline.
        """

        return CanonicalModelJson(self.ToDict()).decode("utf-8")

    @classmethod
    def FromDict(cls, value: object) -> RequestTemplate:
        """Decode exact schema fields and recompute identity instead of trusting stored digests.

        Args:
            value: Decoded canonical schema-versioned object.

        Returns:
            Validated template ready for a separate authorized runtime consumer.

        Raises:
            ValueError: Size, version, fields, canonical spelling or relationships are invalid.
        """

        record = WorkspaceFields(value, {
            "schema_version", "endpoint", "body_kind", "session_reference",
            "graphql_operation", "injection_points", "request_reference",
        }, "request template")

        if RequireWorkspaceInteger(record["schema_version"], "schema_version") != (
            REQUEST_SCHEMA_VERSION
        ):
            raise ValueError("unsupported request schema version")

        if len(CanonicalModelJson(record)) > MAX_REQUEST_BYTES:
            raise ValueError("request template exceeds its serialized size bound")

        if not isinstance(record["injection_points"], list):
            raise ValueError("stored injection_points must be an array")

        operation = record["graphql_operation"]

        if operation is not None and not isinstance(operation, str):
            raise ValueError("graphql_operation must be a name or null")

        body_kind = RequireWorkspaceText(record["body_kind"], "body_kind")

        if body_kind not in tuple(item.value for item in BodyKind):
            raise ValueError("body_kind must select a supported encoding")

        template = cls(
            Endpoint.FromDict(record["endpoint"]),
            tuple(InjectionPoint.FromDict(point) for point in record["injection_points"]),
            BodyKind(body_kind),
            None if record["session_reference"] is None else SessionReference.FromDict(
                record["session_reference"],
            ),
            operation,
        )

        if record != template.ToDict():
            raise ValueError("stored template and request reference must be canonical")

        return template

    @classmethod
    def FromJson(cls, value: str) -> RequestTemplate:
        """Parse bounded strict JSON without duplicate-key or non-finite-value ambiguity.

        Args:
            value: Serialized structural template, never a captured raw HTTP request.

        Returns:
            Validated immutable request template.

        Raises:
            ValueError: Input is oversized, malformed, noncanonical or outside schema version 1.
        """

        if not isinstance(value, str):
            raise ValueError("request JSON must be text")

        try:
            if len(value.encode("utf-8")) > MAX_REQUEST_BYTES:
                raise ValueError("request JSON exceeds its size bound")

            record = json.loads(
                value, object_pairs_hook=UniqueWorkspaceObject,
                parse_constant=RejectWorkspaceConstant,
            )

        except (UnicodeError, RecursionError) as error:
            raise ValueError("request JSON must be bounded valid UTF-8") from error

        return cls.FromDict(record)

__post_init__() -> None

Require coherent locations, ownership and unique deterministic coordinates.

Source code in fuzzy1337/requests.py
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
def __post_init__(self) -> None:
    """Require coherent locations, ownership and unique deterministic coordinates."""

    if not isinstance(self.endpoint, Endpoint) or not isinstance(self.body_kind, BodyKind):
        raise ValueError("template requires Endpoint and BodyKind")

    if not isinstance(self.injection_points, (tuple, list)) or len(
        self.injection_points,
    ) > MAX_INJECTION_POINTS:
        raise ValueError("injection_points must be a bounded sequence")

    if self.session_reference is not None and (
        not isinstance(self.session_reference, SessionReference)
        or self.session_reference.workspace_id != self.endpoint.workspace_id
    ):
        raise ValueError("session reference must belong to the endpoint workspace")

    if self.graphql_operation is not None and (
        self.body_kind is not BodyKind.GRAPHQL
        or not isinstance(self.graphql_operation, str)
        or not re.fullmatch(r"[_A-Za-z][_0-9A-Za-z]{0,63}", self.graphql_operation)
    ):
        raise ValueError("graphql_operation requires a GraphQL body and operation name")

    points: dict[tuple[str, str, int], InjectionPoint] = {}

    for point in self.injection_points:
        if not isinstance(point, InjectionPoint):
            raise ValueError("injection_points must contain InjectionPoint values")

        if point.Coordinate() in points:
            raise ValueError("injection coordinates must be unique")

        self.ValidatePoint(point)
        points[point.Coordinate()] = point

    object.__setattr__(self, "injection_points", tuple(points[key] for key in sorted(points)))

    if len(CanonicalModelJson(self.ToDict())) > MAX_REQUEST_BYTES:
        raise ValueError("request template exceeds its serialized size bound")

ValidatePoint(point: InjectionPoint) -> None

Check encoding, path ownership and session-reference relationships.

Parameters:

Name Type Description Default
point InjectionPoint

Typed input descriptor from this template.

required

Raises:

Type Description
ValueError

A descriptor cannot be represented by this template's structure.

Source code in fuzzy1337/requests.py
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
def ValidatePoint(self, point: InjectionPoint) -> None:
    """Check encoding, path ownership and session-reference relationships.

    Args:
        point: Typed input descriptor from this template.

    Raises:
        ValueError: A descriptor cannot be represented by this template's structure.
    """

    expected = {
        InjectionLocation.BODY: BodyKind.TEXT if point.selector == "" else BodyKind.FORM,
        InjectionLocation.JSON: BodyKind.JSON,
        InjectionLocation.GRAPHQL: BodyKind.GRAPHQL,
        InjectionLocation.MULTIPART: BodyKind.MULTIPART,
    }.get(point.location)

    if expected is not None and self.body_kind is not expected:
        raise ValueError("injection location is incompatible with body_kind")

    if point.location is InjectionLocation.PATH and (
        point.selector not in self.endpoint.PathVariables()
    ):
        raise ValueError("path selector must reference a declared path variable")

    if point.binding.source is BindingSource.SESSION and self.session_reference is None:
        raise ValueError("session bindings require a session reference")

Fields() -> dict[str, object]

Render identity fields without recursively including their digest.

Returns:

Type Description
dict[str, object]

Strict schema-versioned structural fields, with deterministic point order.

Source code in fuzzy1337/requests.py
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def Fields(self) -> dict[str, object]:
    """Render identity fields without recursively including their digest.

    Returns:
        Strict schema-versioned structural fields, with deterministic point order.
    """

    return {
        "schema_version": REQUEST_SCHEMA_VERSION, "endpoint": self.endpoint.ToDict(),
        "body_kind": self.body_kind.value,
        "session_reference": (
            None if self.session_reference is None else self.session_reference.ToDict()
        ),
        "graphql_operation": self.graphql_operation,
        "injection_points": [point.ToDict() for point in self.injection_points],
    }

Reference() -> str

Return a digest of the complete unresolved structural template.

Returns:

Type Description
str

Canonical request reference, including session and symbolic binding identity.

Source code in fuzzy1337/requests.py
543
544
545
546
547
548
549
550
def Reference(self) -> str:
    """Return a digest of the complete unresolved structural template.

    Returns:
        Canonical request reference, including session and symbolic binding identity.
    """

    return RequestDigest("request", self.Fields())

ToDict() -> dict[str, object]

Render a complete schema-versioned template with a verifiable reference.

Returns:

Type Description
dict[str, object]

Canonical serializable request template object.

Source code in fuzzy1337/requests.py
552
553
554
555
556
557
558
559
def ToDict(self) -> dict[str, object]:
    """Render a complete schema-versioned template with a verifiable reference.

    Returns:
        Canonical serializable request template object.
    """

    return {**self.Fields(), "request_reference": self.Reference()}

ToJson() -> str

Serialize a deterministic portable template without accessing runtime values.

Returns:

Type Description
str

Strict UTF-8 JSON text with no trailing newline.

Source code in fuzzy1337/requests.py
561
562
563
564
565
566
567
568
def ToJson(self) -> str:
    """Serialize a deterministic portable template without accessing runtime values.

    Returns:
        Strict UTF-8 JSON text with no trailing newline.
    """

    return CanonicalModelJson(self.ToDict()).decode("utf-8")

FromDict(value: object) -> RequestTemplate classmethod

Decode exact schema fields and recompute identity instead of trusting stored digests.

Parameters:

Name Type Description Default
value object

Decoded canonical schema-versioned object.

required

Returns:

Type Description
RequestTemplate

Validated template ready for a separate authorized runtime consumer.

Raises:

Type Description
ValueError

Size, version, fields, canonical spelling or relationships are invalid.

Source code in fuzzy1337/requests.py
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
@classmethod
def FromDict(cls, value: object) -> RequestTemplate:
    """Decode exact schema fields and recompute identity instead of trusting stored digests.

    Args:
        value: Decoded canonical schema-versioned object.

    Returns:
        Validated template ready for a separate authorized runtime consumer.

    Raises:
        ValueError: Size, version, fields, canonical spelling or relationships are invalid.
    """

    record = WorkspaceFields(value, {
        "schema_version", "endpoint", "body_kind", "session_reference",
        "graphql_operation", "injection_points", "request_reference",
    }, "request template")

    if RequireWorkspaceInteger(record["schema_version"], "schema_version") != (
        REQUEST_SCHEMA_VERSION
    ):
        raise ValueError("unsupported request schema version")

    if len(CanonicalModelJson(record)) > MAX_REQUEST_BYTES:
        raise ValueError("request template exceeds its serialized size bound")

    if not isinstance(record["injection_points"], list):
        raise ValueError("stored injection_points must be an array")

    operation = record["graphql_operation"]

    if operation is not None and not isinstance(operation, str):
        raise ValueError("graphql_operation must be a name or null")

    body_kind = RequireWorkspaceText(record["body_kind"], "body_kind")

    if body_kind not in tuple(item.value for item in BodyKind):
        raise ValueError("body_kind must select a supported encoding")

    template = cls(
        Endpoint.FromDict(record["endpoint"]),
        tuple(InjectionPoint.FromDict(point) for point in record["injection_points"]),
        BodyKind(body_kind),
        None if record["session_reference"] is None else SessionReference.FromDict(
            record["session_reference"],
        ),
        operation,
    )

    if record != template.ToDict():
        raise ValueError("stored template and request reference must be canonical")

    return template

FromJson(value: str) -> RequestTemplate classmethod

Parse bounded strict JSON without duplicate-key or non-finite-value ambiguity.

Parameters:

Name Type Description Default
value str

Serialized structural template, never a captured raw HTTP request.

required

Returns:

Type Description
RequestTemplate

Validated immutable request template.

Raises:

Type Description
ValueError

Input is oversized, malformed, noncanonical or outside schema version 1.

Source code in fuzzy1337/requests.py
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
@classmethod
def FromJson(cls, value: str) -> RequestTemplate:
    """Parse bounded strict JSON without duplicate-key or non-finite-value ambiguity.

    Args:
        value: Serialized structural template, never a captured raw HTTP request.

    Returns:
        Validated immutable request template.

    Raises:
        ValueError: Input is oversized, malformed, noncanonical or outside schema version 1.
    """

    if not isinstance(value, str):
        raise ValueError("request JSON must be text")

    try:
        if len(value.encode("utf-8")) > MAX_REQUEST_BYTES:
            raise ValueError("request JSON exceeds its size bound")

        record = json.loads(
            value, object_pairs_hook=UniqueWorkspaceObject,
            parse_constant=RejectWorkspaceConstant,
        )

    except (UnicodeError, RecursionError) as error:
        raise ValueError("request JSON must be bounded valid UTF-8") from error

    return cls.FromDict(record)

RequestDigest(namespace: str, value: object) -> str

Derive a domain-separated structural identity without consulting runtime values.

Parameters:

Name Type Description Default
namespace str

Request, injection, or session reference namespace.

required
value object

Validated immutable structural identity fields.

required

Returns:

Type Description
str

Namespace and lowercase SHA-256 digest over canonical JSON.

Source code in fuzzy1337/requests.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def RequestDigest(namespace: str, value: object) -> str:
    """Derive a domain-separated structural identity without consulting runtime values.

    Args:
        namespace: Request, injection, or session reference namespace.
        value: Validated immutable structural identity fields.

    Returns:
        Namespace and lowercase SHA-256 digest over canonical JSON.
    """

    digest = hashlib.sha256(CanonicalModelJson({"namespace": namespace, "identity": value}))

    return f"{namespace}:{digest.hexdigest()}"

RequirePointer(value: str) -> None

Validate a bounded RFC 6901 pointer without resolving or decoding a body.

Parameters:

Name Type Description Default
value str

Root pointer or slash-prefixed pointer containing only valid tilde escapes.

required

Raises:

Type Description
ValueError

The pointer is malformed, oversized, or contains controls.

Source code in fuzzy1337/requests.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def RequirePointer(value: str) -> None:
    """Validate a bounded RFC 6901 pointer without resolving or decoding a body.

    Args:
        value: Root pointer or slash-prefixed pointer containing only valid tilde escapes.

    Raises:
        ValueError: The pointer is malformed, oversized, or contains controls.
    """

    if (
        not isinstance(value, str) or len(value) > 256
        or (value != "" and not value.startswith("/"))
        or re.search(r"~(?![01])", value)
        or any(ord(char) < 32 or ord(char) == 127 for char in value)
    ):
        raise ValueError("selector must be a bounded RFC 6901 pointer")

ProjectRequests(templates: tuple[RequestTemplate, ...], *, provenance: tuple[ModelProvenance, ...]) -> SecurityObject

Project one endpoint's complete request collection into the existing model.

Parameters:

Name Type Description Default
templates tuple[RequestTemplate, ...]

Nonempty complete collection for one endpoint; replaces this attribute.

required
provenance tuple[ModelProvenance, ...]

Nonempty existing model attribution for the structural observation.

required

Returns:

Type Description
SecurityObject

Endpoint patch containing only the owned request_templates attribute.

Raises:

Type Description
ValueError

Collection types, ownership, duplicates or model attribute bounds are invalid.

Source code in fuzzy1337/requests.py
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
def ProjectRequests(
    templates: tuple[RequestTemplate, ...], *, provenance: tuple[ModelProvenance, ...],
) -> SecurityObject:
    """Project one endpoint's complete request collection into the existing model.

    Args:
        templates: Nonempty complete collection for one endpoint; replaces this attribute.
        provenance: Nonempty existing model attribution for the structural observation.

    Returns:
        Endpoint patch containing only the owned request_templates attribute.

    Raises:
        ValueError: Collection types, ownership, duplicates or model attribute bounds are invalid.
    """

    if not isinstance(templates, (tuple, list)) or not templates:
        raise ValueError("request projection requires a nonempty template sequence")

    endpoint: Endpoint | None = None
    records: dict[str, dict[str, object]] = {}

    for template in templates:
        if not isinstance(template, RequestTemplate):
            raise ValueError("request projection requires RequestTemplate values")

        if endpoint is not None and template.endpoint != endpoint:
            raise ValueError("request projection must belong to one endpoint")

        endpoint = template.endpoint
        reference = template.Reference()

        if reference in records:
            raise ValueError("request projection must not contain duplicate templates")

        records[reference] = template.ToDict()

    assert endpoint is not None, "A nonempty typed collection must contain an endpoint"

    return SecurityObject(endpoint.Identity(), {
        "request_templates": [records[key] for key in sorted(records)],
    }, provenance)

RequestsFromObject(value: SecurityObject) -> tuple[RequestTemplate, ...]

Reopen validated structural requests from the existing model's immutable attributes.

Parameters:

Name Type Description Default
value SecurityObject

Endpoint object from a real model snapshot; no scope authority is inferred.

required

Returns:

Type Description
tuple[RequestTemplate, ...]

Ordered complete template collection, or empty when no projection is present.

Raises:

Type Description
ValueError

Object kind, projection schema, order, identity or duplicates are invalid.

Source code in fuzzy1337/requests.py
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
def RequestsFromObject(value: SecurityObject) -> tuple[RequestTemplate, ...]:
    """Reopen validated structural requests from the existing model's immutable attributes.

    Args:
        value: Endpoint object from a real model snapshot; no scope authority is inferred.

    Returns:
        Ordered complete template collection, or empty when no projection is present.

    Raises:
        ValueError: Object kind, projection schema, order, identity or duplicates are invalid.
    """

    if not isinstance(value, SecurityObject) or value.identity.kind is not ObjectKind.ENDPOINT:
        raise ValueError("request consumer requires a SOM Endpoint object")

    if "request_templates" not in value.attributes:
        return ()

    records = JsonValue(value.attributes["request_templates"])

    if not isinstance(records, list):
        raise ValueError("request_templates projection must be an array")

    templates = tuple(RequestTemplate.FromDict(record) for record in records)
    references = [template.Reference() for template in templates]

    if references != sorted(set(references)) or any(
        template.endpoint.Identity() != value.identity for template in templates
    ):
        raise ValueError("request projection has duplicate, unordered, or foreign identities")

    return templates