tba-primitives-identity 0.4.0.dev2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ """Entity key helpers shared by identity packages."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def tenant_key(tenant_id: str, entity_id: str) -> str:
7
+ """Return the stable in-memory key for a tenant-scoped entity."""
8
+
9
+ return f"{tenant_id}:{entity_id}"
10
+
11
+
12
+ def normalize_entity(entity_type: str, entity_id: str) -> str:
13
+ """Return the normalized entity reference used by relationship graphs."""
14
+
15
+ return f"{entity_type}:{entity_id}"
16
+
17
+
18
+ __all__ = ["normalize_entity", "tenant_key"]
@@ -0,0 +1,58 @@
1
+ """Custom JWT-related exceptions for tba_auth.
2
+
3
+ The tba_auth package relies on swarmauri token services and avoids direct
4
+ use of external libraries such as PyJWT. These lightweight exception classes
5
+ provide a small surface that mirrors the errors previously exposed by PyJWT
6
+ without requiring a dependency on that package.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+
12
+ class InvalidTokenError(Exception):
13
+ """Raised when a JWT cannot be decoded or fails validation."""
14
+
15
+
16
+ class RefreshTokenError(Exception):
17
+ """Base class for refresh token lifecycle errors."""
18
+
19
+
20
+ class InvalidRefreshTokenError(RefreshTokenError):
21
+ """Raised when a refresh token is unknown, expired, revoked, or inactive."""
22
+
23
+
24
+ class RefreshTokenReuseError(RefreshTokenError):
25
+ """Raised when refresh token reuse is detected."""
26
+
27
+
28
+ class InvalidKeyError(Exception):
29
+ """Raised when a suitable key for JWT processing cannot be found."""
30
+
31
+
32
+ class IdentityError(Exception):
33
+ """Base error for identity package primitives."""
34
+
35
+
36
+ class IdentityValidationError(IdentityError):
37
+ """Raised when an identity primitive or contract fails validation."""
38
+
39
+
40
+ class IdentityConfigurationError(IdentityError):
41
+ """Raised when package/runtime configuration is invalid."""
42
+
43
+
44
+ class IdentityAuthorizationError(IdentityError):
45
+ """Raised when a principal is not authorized for an operation."""
46
+
47
+
48
+ __all__ = [
49
+ "IdentityAuthorizationError",
50
+ "IdentityConfigurationError",
51
+ "IdentityError",
52
+ "IdentityValidationError",
53
+ "InvalidKeyError",
54
+ "InvalidRefreshTokenError",
55
+ "InvalidTokenError",
56
+ "RefreshTokenError",
57
+ "RefreshTokenReuseError",
58
+ ]
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any, Awaitable, Callable
5
+
6
+
7
+ def json_response(
8
+ status: int,
9
+ payload: dict[str, Any],
10
+ ) -> tuple[int, list[tuple[bytes, bytes]], bytes]:
11
+ body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
12
+ headers = [
13
+ (b"content-type", b"application/json"),
14
+ (b"content-length", str(len(body)).encode("ascii")),
15
+ ]
16
+ if status == 401:
17
+ headers.append((b"www-authenticate", b"Bearer"))
18
+ return status, headers, body
19
+
20
+
21
+ async def read_http_body(receive: Callable[[], Awaitable[dict[str, Any]]]) -> bytes:
22
+ chunks: list[bytes] = []
23
+ while True:
24
+ message = await receive()
25
+ if message.get("type") != "http.request":
26
+ continue
27
+ chunks.append(message.get("body", b""))
28
+ if not message.get("more_body", False):
29
+ break
30
+ return b"".join(chunks)
31
+
32
+
33
+ def replay_http_body(body: bytes) -> Callable[[], Awaitable[dict[str, Any]]]:
34
+ sent = False
35
+
36
+ async def receive() -> dict[str, Any]:
37
+ nonlocal sent
38
+ if sent:
39
+ return {"type": "http.request", "body": b"", "more_body": False}
40
+ sent = True
41
+ return {"type": "http.request", "body": body, "more_body": False}
42
+
43
+ return receive
44
+
45
+
46
+ def headers_from_scope(scope: dict[str, Any]) -> dict[str, str]:
47
+ return {
48
+ key.decode("latin-1").lower(): value.decode("latin-1")
49
+ for key, value in scope.get("headers", [])
50
+ }
51
+
52
+
53
+ __all__ = [
54
+ "headers_from_scope",
55
+ "json_response",
56
+ "read_http_body",
57
+ "replay_http_body",
58
+ ]
@@ -0,0 +1,175 @@
1
+ """JSON Canonicalization Scheme helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ import hashlib
9
+ from collections.abc import Iterable, Mapping, Sequence
10
+ from decimal import Decimal
11
+ from typing import Any
12
+
13
+ RFC8785_SPEC_URL = "https://www.rfc-editor.org/rfc/rfc8785"
14
+ MAX_SAFE_INTEGER = 2**53 - 1
15
+ _EXPONENT_RE = re.compile(r"e([+-])0+(\d+)$")
16
+
17
+
18
+ class JCSCanonicalizationError(ValueError):
19
+ """Raised when input cannot be represented as RFC 8785 JCS JSON."""
20
+
21
+
22
+ def canonicalize(value: Any) -> bytes:
23
+ """Return RFC 8785 JCS canonical JSON encoded as UTF-8 bytes."""
24
+
25
+ return _serialize(value).encode("utf-8")
26
+
27
+
28
+ def canonicalize_json(document: str | bytes | bytearray) -> bytes:
29
+ """Parse JSON text with duplicate-name rejection and return JCS bytes."""
30
+
31
+ if isinstance(document, (bytes, bytearray)):
32
+ document = bytes(document).decode("utf-8")
33
+ value = json.loads(document, object_pairs_hook=_reject_duplicate_pairs)
34
+ return canonicalize(value)
35
+
36
+
37
+ def _normalize_canonical_json_value(value: Any) -> Any:
38
+ if isinstance(value, Mapping):
39
+ return {
40
+ str(key): _normalize_canonical_json_value(item)
41
+ for key, item in sorted(value.items(), key=lambda item: str(item[0]))
42
+ }
43
+ if isinstance(value, tuple):
44
+ return [_normalize_canonical_json_value(item) for item in value]
45
+ if isinstance(value, list):
46
+ return [_normalize_canonical_json_value(item) for item in value]
47
+ if isinstance(value, set):
48
+ return [
49
+ _normalize_canonical_json_value(item)
50
+ for item in sorted(value, key=lambda item: repr(item))
51
+ ]
52
+ return value
53
+
54
+
55
+ def canonical_json(value: Any) -> str:
56
+ """Return deterministic JSON text for policy proof artifacts."""
57
+
58
+ return json.dumps(
59
+ _normalize_canonical_json_value(value),
60
+ sort_keys=True,
61
+ separators=(",", ":"),
62
+ ensure_ascii=True,
63
+ )
64
+
65
+
66
+ def canonical_json_bytes(value: Any) -> bytes:
67
+ """Return deterministic JSON encoded as UTF-8 bytes."""
68
+
69
+ return canonical_json(value).encode("utf-8")
70
+
71
+
72
+ def canonical_hash(value: Any) -> str:
73
+ """Return the SHA-256 hex digest of :func:`canonical_json` output."""
74
+
75
+ return hashlib.sha256(canonical_json_bytes(value)).hexdigest()
76
+
77
+
78
+ def _reject_duplicate_pairs(pairs: Iterable[tuple[str, Any]]) -> dict[str, Any]:
79
+ result: dict[str, Any] = {}
80
+ for key, value in pairs:
81
+ if key in result:
82
+ raise JCSCanonicalizationError(f"duplicate JSON object member: {key!r}")
83
+ result[key] = value
84
+ return result
85
+
86
+
87
+ def _serialize(value: Any) -> str:
88
+ if value is None:
89
+ return "null"
90
+ if value is True:
91
+ return "true"
92
+ if value is False:
93
+ return "false"
94
+ if isinstance(value, str):
95
+ _reject_lone_surrogates(value)
96
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
97
+ if isinstance(value, int):
98
+ _validate_integer(value)
99
+ return str(value)
100
+ if isinstance(value, float):
101
+ return _serialize_float(value)
102
+ if isinstance(value, Decimal):
103
+ raise JCSCanonicalizationError("Decimal values are not JCS JSON numbers")
104
+ if isinstance(value, Mapping):
105
+ return _serialize_object(value)
106
+ if _is_json_sequence(value):
107
+ return "[" + ",".join(_serialize(item) for item in value) + "]"
108
+ raise JCSCanonicalizationError(
109
+ f"unsupported JCS JSON value: {type(value).__name__}"
110
+ )
111
+
112
+
113
+ def _serialize_object(value: Mapping[Any, Any]) -> str:
114
+ items: list[tuple[str, Any]] = []
115
+ seen: set[str] = set()
116
+ for key, item in value.items():
117
+ if not isinstance(key, str):
118
+ raise JCSCanonicalizationError("JCS object member names must be strings")
119
+ if key in seen:
120
+ raise JCSCanonicalizationError(f"duplicate JSON object member: {key!r}")
121
+ _reject_lone_surrogates(key)
122
+ seen.add(key)
123
+ items.append((key, item))
124
+ fields = (
125
+ f"{_serialize(key)}:{_serialize(item)}"
126
+ for key, item in sorted(items, key=lambda pair: _utf16_sort_key(pair[0]))
127
+ )
128
+ return "{" + ",".join(fields) + "}"
129
+
130
+
131
+ def _is_json_sequence(value: Any) -> bool:
132
+ return isinstance(value, Sequence) and not isinstance(
133
+ value, (str, bytes, bytearray)
134
+ )
135
+
136
+
137
+ def _validate_integer(value: int) -> None:
138
+ if abs(value) > MAX_SAFE_INTEGER:
139
+ raise JCSCanonicalizationError(
140
+ "JCS integer values must be exactly representable by IEEE 754 doubles"
141
+ )
142
+
143
+
144
+ def _serialize_float(value: float) -> str:
145
+ if not math.isfinite(value):
146
+ raise JCSCanonicalizationError("NaN and Infinity are not valid JCS numbers")
147
+ if value == 0:
148
+ return "0"
149
+ if value.is_integer() and abs(value) <= MAX_SAFE_INTEGER:
150
+ return str(int(value))
151
+ encoded = json.dumps(value, allow_nan=False, separators=(",", ":"))
152
+ return _EXPONENT_RE.sub(r"e\1\2", encoded)
153
+
154
+
155
+ def _reject_lone_surrogates(value: str) -> None:
156
+ for char in value:
157
+ codepoint = ord(char)
158
+ if 0xD800 <= codepoint <= 0xDFFF:
159
+ raise JCSCanonicalizationError("lone surrogate values are not valid JCS")
160
+
161
+
162
+ def _utf16_sort_key(value: str) -> tuple[int, ...]:
163
+ return tuple(value.encode("utf-16-be"))
164
+
165
+
166
+ __all__ = [
167
+ "JCSCanonicalizationError",
168
+ "MAX_SAFE_INTEGER",
169
+ "RFC8785_SPEC_URL",
170
+ "canonical_hash",
171
+ "canonical_json",
172
+ "canonical_json_bytes",
173
+ "canonicalize",
174
+ "canonicalize_json",
175
+ ]
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ def jsonrpc_error(
7
+ request_id: Any,
8
+ code: int,
9
+ message: str,
10
+ data: Any | None = None,
11
+ ) -> dict[str, Any]:
12
+ error: dict[str, Any] = {"code": code, "message": message}
13
+ if data is not None:
14
+ error["data"] = data
15
+ return {"jsonrpc": "2.0", "id": request_id, "error": error}
16
+
17
+
18
+ __all__ = ["jsonrpc_error"]
@@ -0,0 +1,58 @@
1
+ """Small, strict media-type value objects."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True, slots=True)
7
+ class MediaType:
8
+ value: str
9
+
10
+ def __post_init__(self) -> None:
11
+ value = str(self.value).strip().lower()
12
+ if "/" not in value or any(char.isspace() for char in value):
13
+ raise ValueError("media type must be a type/subtype value")
14
+ object.__setattr__(self, "value", value)
15
+
16
+ def __str__(self) -> str:
17
+ return self.value
18
+
19
+
20
+ APPLICATION_DC_SD_JWT = MediaType("application/dc+sd-jwt")
21
+ APPLICATION_VC = MediaType("application/vc")
22
+ APPLICATION_VP = MediaType("application/vp")
23
+ APPLICATION_CWT = MediaType("application/cwt")
24
+ APPLICATION_EAT_JWT = MediaType("application/eat+jwt")
25
+ APPLICATION_EAT_CWT = MediaType("application/eat+cwt")
26
+ APPLICATION_JWT = MediaType("application/jwt")
27
+ APPLICATION_AT_JWT = MediaType("application/at+jwt")
28
+ APPLICATION_WIT_JWT = MediaType("application/wit+jwt")
29
+ APPLICATION_WPT_JWT = MediaType("application/wpt+jwt")
30
+ APPLICATION_VC_JWT = MediaType("application/vc+jwt")
31
+ APPLICATION_VP_JWT = MediaType("application/vp+jwt")
32
+ APPLICATION_VC_COSE = MediaType("application/vc+cose")
33
+ APPLICATION_VP_COSE = MediaType("application/vp+cose")
34
+ APPLICATION_COSE = MediaType("application/cose")
35
+ APPLICATION_DID_JSON = MediaType("application/did+json")
36
+ APPLICATION_DID_LD_JSON = MediaType("application/did+ld+json")
37
+
38
+
39
+ __all__ = [
40
+ "APPLICATION_CWT",
41
+ "APPLICATION_DC_SD_JWT",
42
+ "APPLICATION_EAT_CWT",
43
+ "APPLICATION_EAT_JWT",
44
+ "APPLICATION_JWT",
45
+ "APPLICATION_AT_JWT",
46
+ "APPLICATION_WIT_JWT",
47
+ "APPLICATION_WPT_JWT",
48
+ "APPLICATION_VC_JWT",
49
+ "APPLICATION_VP_JWT",
50
+ "APPLICATION_VC_COSE",
51
+ "APPLICATION_VP_COSE",
52
+ "APPLICATION_COSE",
53
+ "APPLICATION_DID_JSON",
54
+ "APPLICATION_DID_LD_JSON",
55
+ "APPLICATION_VC",
56
+ "APPLICATION_VP",
57
+ "MediaType",
58
+ ]
@@ -0,0 +1,28 @@
1
+ """Cryptographically secure nonce primitives."""
2
+
3
+ import hmac
4
+ import secrets
5
+
6
+ from .base64url import base64url_encode
7
+
8
+ MIN_NONCE_BYTES = 16
9
+
10
+
11
+ def generate_nonce(*, size: int = 32) -> str:
12
+ if size < MIN_NONCE_BYTES:
13
+ raise ValueError(f"nonce size must be at least {MIN_NONCE_BYTES} bytes")
14
+ return base64url_encode(secrets.token_bytes(size))
15
+
16
+
17
+ def validate_nonce(value: str, *, min_length: int = 22) -> str:
18
+ normalized = str(value).strip()
19
+ if len(normalized) < min_length:
20
+ raise ValueError("nonce is too short")
21
+ return normalized
22
+
23
+
24
+ def nonce_equal(left: str, right: str) -> bool:
25
+ return hmac.compare_digest(str(left), str(right))
26
+
27
+
28
+ __all__ = ["MIN_NONCE_BYTES", "generate_nonce", "nonce_equal", "validate_nonce"]
@@ -0,0 +1,81 @@
1
+ """Normalization helpers shared by identity packages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping
6
+ from typing import Any
7
+ from uuid import uuid4
8
+
9
+
10
+ def new_model_id() -> str:
11
+ """Return a dependency-light opaque identifier for concrete models."""
12
+
13
+ return str(uuid4())
14
+
15
+
16
+ def required_text(value: object, field_name: str) -> str:
17
+ """Normalize a required textual field."""
18
+
19
+ cleaned = str(value).strip()
20
+ if not cleaned:
21
+ raise ValueError(f"{field_name} is required")
22
+ return cleaned
23
+
24
+
25
+ def clean_tuple(values: Iterable[object] = ()) -> tuple[str, ...]:
26
+ """Return unique, non-empty textual values in stable order."""
27
+
28
+ return tuple(sorted({str(value).strip() for value in values if str(value).strip()}))
29
+
30
+
31
+ def clean_mapping(value: Mapping[str, Any], field_name: str) -> dict[str, Any]:
32
+ """Validate and copy a mapping owned by a concrete model."""
33
+
34
+ if not isinstance(value, Mapping):
35
+ raise ValueError(f"{field_name} must be a mapping")
36
+ return dict(value)
37
+
38
+
39
+ def pick_fields(record: Mapping[str, Any], fields: Iterable[str]) -> dict[str, Any]:
40
+ return {field: record[field] for field in fields if field in record}
41
+
42
+
43
+ def row_value(row: Any, key: str, default: Any = None) -> Any:
44
+ if isinstance(row, Mapping):
45
+ return row.get(key, default)
46
+ return getattr(row, key, default)
47
+
48
+
49
+ def row_active(row: Any) -> bool:
50
+ return str(row_value(row, "status", "active") or "active") == "active"
51
+
52
+
53
+ def str_tuple(values: Any, *, sort: bool = True) -> tuple[str, ...]:
54
+ if values is None or values == "" or values is False:
55
+ return ()
56
+ if isinstance(values, str):
57
+ items = (values,)
58
+ else:
59
+ items = tuple(str(value) for value in values if value not in {None, ""})
60
+ return tuple(sorted(set(items))) if sort else tuple(items)
61
+
62
+
63
+ def normal_tuple(values: Iterable[str] | None) -> tuple[str, ...]:
64
+ """Return a sorted tuple of non-empty stripped string values."""
65
+
66
+ return tuple(
67
+ sorted({str(value).strip() for value in values or () if str(value).strip()})
68
+ )
69
+
70
+
71
+ __all__ = [
72
+ "clean_mapping",
73
+ "clean_tuple",
74
+ "new_model_id",
75
+ "normal_tuple",
76
+ "pick_fields",
77
+ "required_text",
78
+ "row_active",
79
+ "row_value",
80
+ "str_tuple",
81
+ ]
@@ -0,0 +1,78 @@
1
+ """Reusable Tigrbl ORM authoring surface for identity storage packages.
2
+
3
+ This optional module centralizes stable imports without creating a storage-layer
4
+ package dependency. Importing the rest of :mod:`tba_primitives_identity` remains
5
+ dependency-light and does not import Tigrbl or SQLAlchemy.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from tigrbl import ForeignKeySpec, RestOltpTable
11
+ from tigrbl.orm.mixins import (
12
+ ActiveToggle,
13
+ Bootstrappable,
14
+ Created,
15
+ GUIDPk,
16
+ KeyDigest,
17
+ LastUsed,
18
+ Principal,
19
+ TenantBound,
20
+ TenantColumn,
21
+ Timestamped,
22
+ UserColumn,
23
+ ValidityWindow,
24
+ )
25
+ from tigrbl.orm.tables import Client as ClientBase
26
+ from tigrbl.orm.tables import Tenant as TenantBase
27
+ from tigrbl.orm.tables import User as UserBase
28
+ from tigrbl.shortcuts.column import ColumnSpec, F, IO, S, acol
29
+ from tigrbl.types import (
30
+ Boolean,
31
+ Integer,
32
+ JSON,
33
+ LargeBinary,
34
+ Mapped,
35
+ PgUUID,
36
+ String,
37
+ TZDateTime,
38
+ UUID,
39
+ relationship,
40
+ )
41
+
42
+ AUTHN_SCHEMA = "authn"
43
+
44
+ __all__ = [
45
+ "AUTHN_SCHEMA",
46
+ "ActiveToggle",
47
+ "Boolean",
48
+ "Bootstrappable",
49
+ "ClientBase",
50
+ "ColumnSpec",
51
+ "Created",
52
+ "F",
53
+ "ForeignKeySpec",
54
+ "GUIDPk",
55
+ "IO",
56
+ "Integer",
57
+ "JSON",
58
+ "KeyDigest",
59
+ "LargeBinary",
60
+ "LastUsed",
61
+ "Mapped",
62
+ "PgUUID",
63
+ "Principal",
64
+ "RestOltpTable",
65
+ "S",
66
+ "String",
67
+ "TZDateTime",
68
+ "TenantBase",
69
+ "TenantBound",
70
+ "TenantColumn",
71
+ "Timestamped",
72
+ "UUID",
73
+ "UserBase",
74
+ "UserColumn",
75
+ "ValidityWindow",
76
+ "acol",
77
+ "relationship",
78
+ ]
@@ -0,0 +1,79 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ _WINDOWS_ABSOLUTE_PATH = re.compile(r"\b[A-Za-z]:[\\/][^\s`'\"\]\)},]+")
8
+
9
+
10
+ def _as_posix(value: str) -> str:
11
+ return value.replace("\\", "/")
12
+
13
+
14
+ def safe_display_path(
15
+ path: Path | str, repo_root: Path, *, external_label: str = "<local-path>"
16
+ ) -> str:
17
+ """Return a stable repo-safe path for user-facing reports and committed artifacts."""
18
+
19
+ candidate = Path(path)
20
+ resolved_repo = repo_root.resolve()
21
+ try:
22
+ return candidate.resolve().relative_to(resolved_repo).as_posix()
23
+ except Exception:
24
+ pass
25
+
26
+ raw = _as_posix(str(path))
27
+ parts = [part for part in raw.split("/") if part]
28
+ for marker, label in (
29
+ (".pytest-tmp", "<repo>"),
30
+ ("dist", "<repo>"),
31
+ ("operator-state", "<operator-state>"),
32
+ ("operator-plane", "<operator-state>"),
33
+ ):
34
+ if marker in parts:
35
+ index = parts.index(marker)
36
+ return "/".join([label, *parts[index:]])
37
+ return f"{external_label}/{candidate.name or 'path'}"
38
+
39
+
40
+ def _redact_windows_path(match: re.Match[str]) -> str:
41
+ raw = _as_posix(match.group(0))
42
+ parts = [part for part in raw.split("/") if part]
43
+ for marker, label in (
44
+ (".pytest-tmp", "<repo>"),
45
+ ("dist", "<repo>"),
46
+ ("operator-state", "<operator-state>"),
47
+ ("operator-plane", "<operator-state>"),
48
+ ):
49
+ if marker in parts:
50
+ index = parts.index(marker)
51
+ return "/".join([label, *parts[index:]])
52
+ return "<local-path>"
53
+
54
+
55
+ def sanitize_local_paths(value: Any, repo_root: Path) -> Any:
56
+ """Recursively redact local absolute paths from generated repo artifacts."""
57
+
58
+ if isinstance(value, dict):
59
+ return {
60
+ key: sanitize_local_paths(item, repo_root) for key, item in value.items()
61
+ }
62
+ if isinstance(value, list):
63
+ return [sanitize_local_paths(item, repo_root) for item in value]
64
+ if isinstance(value, tuple):
65
+ return tuple(sanitize_local_paths(item, repo_root) for item in value)
66
+ if not isinstance(value, str):
67
+ return value
68
+
69
+ resolved_repo = repo_root.resolve()
70
+ candidates = {
71
+ str(resolved_repo),
72
+ _as_posix(str(resolved_repo)),
73
+ }
74
+ text = value
75
+ for candidate in sorted(candidates, key=len, reverse=True):
76
+ if candidate:
77
+ text = text.replace(candidate, "<repo>")
78
+ text = _as_posix(text)
79
+ return _WINDOWS_ABSOLUTE_PATH.sub(_redact_windows_path, text)
@@ -0,0 +1,17 @@
1
+ """Pattern matching helpers shared by identity packages."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def matches_dotted_pattern(pattern: str, value: str) -> bool:
7
+ """Match exact, wildcard, or dotted-prefix patterns."""
8
+
9
+ if pattern == "*" or pattern == value:
10
+ return True
11
+ if pattern.endswith(".*"):
12
+ prefix = pattern[:-2]
13
+ return value == prefix or value.startswith(f"{prefix}.")
14
+ return False
15
+
16
+
17
+ __all__ = ["matches_dotted_pattern"]