meshflow-contracts 0.2.3__tar.gz

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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: meshflow-contracts
3
+ Version: 0.2.3
4
+ Summary: Shared MeshFlow platform contracts.
5
+ Keywords: meshflow,contracts,pydantic,schemas
6
+ Author: MeshFlow contributors
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Typing :: Typed
15
+ Requires-Dist: pydantic>=2.13.4,<3
16
+ Requires-Python: >=3.14
17
+ Project-URL: Repository, https://github.com/MeshFlow-os/meshflow-contracts
18
+ Project-URL: Issues, https://github.com/MeshFlow-os/meshflow-contracts/issues
19
+ Project-URL: Changelog, https://github.com/MeshFlow-os/meshflow-contracts/blob/main/CHANGELOG.md
20
+ Description-Content-Type: text/markdown
21
+
22
+ # MeshFlow Contracts
23
+
24
+ Shared Pydantic contracts used by Core, Gateway, and MeshFlow apps.
25
+
26
+ Rule of thumb: if a model is only used by one app, it does not belong here.
27
+
28
+ ## Installation
29
+
30
+ This package is preparing for public PyPI publication. After the release is
31
+ published, install the supported `0.2` line with `pip install "meshflow-contracts~=0.2.3"`.
32
+ Until then, consumers must not assume the distribution is available on PyPI.
33
+
34
+ Maintainers: use the package-specific [release and adoption runbook](RELEASING.md).
35
+ It describes release gates without implying that `0.2.3` is already published.
36
+
37
+ ## External ingress manifests
38
+
39
+ Apps may declare optional generic external ingress capabilities through
40
+ `AppManifest.external_ingress`. Each entry fixes the audience, private upstream
41
+ path, methods, content types, scopes, body limit, and rate policy that platform
42
+ services may snapshot and enforce. The contract describes policy only; it does
43
+ not route traffic or authorize grants.
44
+
45
+ Manifests that omit `external_ingress` remain valid and declare no external
46
+ ingress capabilities.
47
+
48
+ External ingress policy is intentionally conservative for Core/Gateway
49
+ snapshots: internal upstream paths must be canonical absolute app-internal
50
+ paths, capability ids are unique per manifest, methods are limited to `GET`,
51
+ `POST`, `PUT`, and `DELETE`, and numeric limits are strict integers. Contract
52
+ safety caps are 100 MiB per request body, 1,000 requests per window, and 3,600
53
+ seconds per rate window.
54
+
55
+ ## Integration request tokens
56
+
57
+ `IntegrationRequestClaims` defines the shared internal JWT payload Gateway sends
58
+ only to private app ingress after Core has validated an integration grant. The
59
+ contract adds `token_type="integration_request"` without changing existing
60
+ `app_request` or `lifecycle` token claims.
61
+
62
+ The claims model requires workspace, installation, app/audience, capability,
63
+ grant, subject user, request, `jti`, immutable scopes, and strict integer `iat`
64
+ / `exp` values. App id and audience must match, token lifetime is capped at
65
+ 3,600 seconds, undeclared claims are rejected, and validated copies re-run the
66
+ same invariants. JWT registered claims keep their JWT semantics: `iss` accepts a
67
+ case-sensitive non-empty StringOrURI, including HTTPS URIs and arbitrary
68
+ human-readable no-colon issuer strings, while `sub` and `jti` are case-sensitive
69
+ opaque URL-safe strings rather than MeshFlow identifiers. This package validates
70
+ claim shape only; cryptographic verification and equality to the configured
71
+ issuer remain runtime responsibilities alongside signing, minting, JWKS
72
+ validation, replay handling, routing, lifecycle status, error taxonomy, and grant
73
+ persistence.
74
+
75
+ ## 0.2.3 recovery rollout notes
76
+
77
+ The failed `v0.2.0`, `v0.2.1`, and `v0.2.2` tags are immutable unpublished history. They
78
+ must never be moved, reused, published, or turned into GitHub Releases. `0.2.3`
79
+ is the recovery candidate, and consumers must wait for its public package verification. Core
80
+ adopts the verified package before Gateway; the schema upgrade alone does not
81
+ enable runtime capabilities.
82
+
83
+ - Apps that omit `external_ingress` preserve `0.1.0` parse/serialize behavior;
84
+ omission grants no public ingress.
85
+ - Registration and runtime rollout depend on Core/Gateway adopting their own
86
+ snapshot, introspection, routing, and policy-enforcement behavior.
87
+ - Core/Gateway must ignore `external_ingress` until their own snapshot,
88
+ introspection, routing, and policy-enforcement work lands.
89
+ - Apps must ignore `integration_request` until they implement private external
90
+ ingress consumers; existing browser and lifecycle paths keep using
91
+ `app_request` and `lifecycle` semantics.
92
+ - No Core, Gateway, or app domain behavior is enabled solely by upgrading this
93
+ package.
94
+
95
+ Packaging metadata, licensing, source-level checks, strict artifact inspection, and
96
+ wheel/sdist smoke tests are enforced by release CI before consumer adoption.
97
+
98
+ ## License
99
+
100
+ Licensed under the Apache License 2.0. See [LICENSE](LICENSE).
101
+
102
+ Copyright 2026 MeshFlow contributors.
@@ -0,0 +1,81 @@
1
+ # MeshFlow Contracts
2
+
3
+ Shared Pydantic contracts used by Core, Gateway, and MeshFlow apps.
4
+
5
+ Rule of thumb: if a model is only used by one app, it does not belong here.
6
+
7
+ ## Installation
8
+
9
+ This package is preparing for public PyPI publication. After the release is
10
+ published, install the supported `0.2` line with `pip install "meshflow-contracts~=0.2.3"`.
11
+ Until then, consumers must not assume the distribution is available on PyPI.
12
+
13
+ Maintainers: use the package-specific [release and adoption runbook](RELEASING.md).
14
+ It describes release gates without implying that `0.2.3` is already published.
15
+
16
+ ## External ingress manifests
17
+
18
+ Apps may declare optional generic external ingress capabilities through
19
+ `AppManifest.external_ingress`. Each entry fixes the audience, private upstream
20
+ path, methods, content types, scopes, body limit, and rate policy that platform
21
+ services may snapshot and enforce. The contract describes policy only; it does
22
+ not route traffic or authorize grants.
23
+
24
+ Manifests that omit `external_ingress` remain valid and declare no external
25
+ ingress capabilities.
26
+
27
+ External ingress policy is intentionally conservative for Core/Gateway
28
+ snapshots: internal upstream paths must be canonical absolute app-internal
29
+ paths, capability ids are unique per manifest, methods are limited to `GET`,
30
+ `POST`, `PUT`, and `DELETE`, and numeric limits are strict integers. Contract
31
+ safety caps are 100 MiB per request body, 1,000 requests per window, and 3,600
32
+ seconds per rate window.
33
+
34
+ ## Integration request tokens
35
+
36
+ `IntegrationRequestClaims` defines the shared internal JWT payload Gateway sends
37
+ only to private app ingress after Core has validated an integration grant. The
38
+ contract adds `token_type="integration_request"` without changing existing
39
+ `app_request` or `lifecycle` token claims.
40
+
41
+ The claims model requires workspace, installation, app/audience, capability,
42
+ grant, subject user, request, `jti`, immutable scopes, and strict integer `iat`
43
+ / `exp` values. App id and audience must match, token lifetime is capped at
44
+ 3,600 seconds, undeclared claims are rejected, and validated copies re-run the
45
+ same invariants. JWT registered claims keep their JWT semantics: `iss` accepts a
46
+ case-sensitive non-empty StringOrURI, including HTTPS URIs and arbitrary
47
+ human-readable no-colon issuer strings, while `sub` and `jti` are case-sensitive
48
+ opaque URL-safe strings rather than MeshFlow identifiers. This package validates
49
+ claim shape only; cryptographic verification and equality to the configured
50
+ issuer remain runtime responsibilities alongside signing, minting, JWKS
51
+ validation, replay handling, routing, lifecycle status, error taxonomy, and grant
52
+ persistence.
53
+
54
+ ## 0.2.3 recovery rollout notes
55
+
56
+ The failed `v0.2.0`, `v0.2.1`, and `v0.2.2` tags are immutable unpublished history. They
57
+ must never be moved, reused, published, or turned into GitHub Releases. `0.2.3`
58
+ is the recovery candidate, and consumers must wait for its public package verification. Core
59
+ adopts the verified package before Gateway; the schema upgrade alone does not
60
+ enable runtime capabilities.
61
+
62
+ - Apps that omit `external_ingress` preserve `0.1.0` parse/serialize behavior;
63
+ omission grants no public ingress.
64
+ - Registration and runtime rollout depend on Core/Gateway adopting their own
65
+ snapshot, introspection, routing, and policy-enforcement behavior.
66
+ - Core/Gateway must ignore `external_ingress` until their own snapshot,
67
+ introspection, routing, and policy-enforcement work lands.
68
+ - Apps must ignore `integration_request` until they implement private external
69
+ ingress consumers; existing browser and lifecycle paths keep using
70
+ `app_request` and `lifecycle` semantics.
71
+ - No Core, Gateway, or app domain behavior is enabled solely by upgrading this
72
+ package.
73
+
74
+ Packaging metadata, licensing, source-level checks, strict artifact inspection, and
75
+ wheel/sdist smoke tests are enforced by release CI before consumer adoption.
76
+
77
+ ## License
78
+
79
+ Licensed under the Apache License 2.0. See [LICENSE](LICENSE).
80
+
81
+ Copyright 2026 MeshFlow contributors.
@@ -0,0 +1,9 @@
1
+ """Shared MeshFlow platform contracts."""
2
+
3
+ from meshflow_contracts.auth import IntegrationRequestClaims
4
+
5
+ __version__ = "0.2.3"
6
+
7
+ __all__ = [
8
+ "IntegrationRequestClaims",
9
+ ]
@@ -0,0 +1,108 @@
1
+ import re
2
+ from typing import Any, Literal, Mapping, Self
3
+
4
+ from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator, model_validator
5
+
6
+
7
+ WorkspaceRole = Literal["owner", "admin", "member"]
8
+ InstallationRole = Literal["admin", "member", "viewer"]
9
+ InternalTokenType = Literal["app_request", "lifecycle", "integration_request"]
10
+ IntegrationRequestTokenType = Literal["integration_request"]
11
+
12
+ IDENTIFIER_PATTERN = r"^[a-z0-9]+(?:[._:-][a-z0-9]+)*$"
13
+ JWT_STRING_OR_URI_PATTERN = r"^[^\x00-\x1f\x7f]+$"
14
+ JWT_OPAQUE_URL_SAFE_PATTERN = r"^[A-Za-z0-9._~:-]+$"
15
+ MAX_INTEGRATION_REQUEST_LIFETIME_SECONDS = 3_600
16
+ MAX_JWT_REGISTERED_CLAIM_LENGTH = 512
17
+
18
+
19
+ class AuthContext(BaseModel):
20
+ user_id: str
21
+ workspace_id: str
22
+ installation_id: str | None = None
23
+ workspace_role: WorkspaceRole
24
+ installation_role: InstallationRole | None = None
25
+ request_id: str
26
+
27
+
28
+ class InternalJWTClaims(BaseModel):
29
+ iss: str
30
+ aud: str
31
+ sub: str
32
+ user_id: str
33
+ workspace_id: str
34
+ installation_id: str | None = None
35
+ workspace_role: WorkspaceRole
36
+ installation_role: InstallationRole | None = None
37
+ request_id: str
38
+ token_type: InternalTokenType
39
+ iat: int
40
+ exp: int
41
+ purpose: str | None = Field(default=None)
42
+
43
+
44
+ class IntegrationRequestClaims(BaseModel):
45
+ model_config = ConfigDict(frozen=True, extra="forbid")
46
+
47
+ iss: str
48
+ aud: str = Field(pattern=IDENTIFIER_PATTERN)
49
+ sub: str
50
+ token_type: IntegrationRequestTokenType
51
+ workspace_id: str = Field(pattern=IDENTIFIER_PATTERN)
52
+ installation_id: str = Field(pattern=IDENTIFIER_PATTERN)
53
+ app_id: str = Field(pattern=IDENTIFIER_PATTERN)
54
+ capability_id: str = Field(pattern=IDENTIFIER_PATTERN)
55
+ integration_grant_id: str = Field(pattern=IDENTIFIER_PATTERN)
56
+ subject_user_id: str = Field(pattern=IDENTIFIER_PATTERN)
57
+ scopes: tuple[str, ...] = Field(min_length=1)
58
+ request_id: str = Field(pattern=IDENTIFIER_PATTERN)
59
+ jti: str
60
+ iat: int = Field(strict=True)
61
+ exp: int = Field(strict=True)
62
+
63
+ @field_validator("iss")
64
+ @classmethod
65
+ def validate_string_or_uri_claim(cls, value: str) -> str:
66
+ if len(value) > MAX_JWT_REGISTERED_CLAIM_LENGTH:
67
+ raise ValueError("claim is too long")
68
+ if re.fullmatch(JWT_STRING_OR_URI_PATTERN, value) is None:
69
+ raise ValueError("claim must be a non-empty StringOrURI without control characters")
70
+ return value
71
+
72
+ @field_validator("sub", "jti")
73
+ @classmethod
74
+ def validate_opaque_url_safe_claim(cls, value: str) -> str:
75
+ if len(value) > MAX_JWT_REGISTERED_CLAIM_LENGTH:
76
+ raise ValueError("claim is too long")
77
+ if re.fullmatch(JWT_OPAQUE_URL_SAFE_PATTERN, value) is None:
78
+ raise ValueError("claim must be a non-empty URL-safe opaque string")
79
+ return value
80
+
81
+ @field_validator("scopes")
82
+ @classmethod
83
+ def validate_scopes(cls, scopes: tuple[str, ...]) -> tuple[str, ...]:
84
+ if len(set(scopes)) != len(scopes):
85
+ raise ValueError("scopes must be unique")
86
+ if any(re.fullmatch(IDENTIFIER_PATTERN, scope) is None for scope in scopes):
87
+ raise ValueError("scopes must be identifiers")
88
+ return scopes
89
+
90
+ @field_serializer("scopes")
91
+ def serialize_scopes(self, value: tuple[str, ...]) -> list[str]:
92
+ return list(value)
93
+
94
+ @model_validator(mode="after")
95
+ def validate_cross_field_invariants(self) -> "IntegrationRequestClaims":
96
+ if self.aud != self.app_id:
97
+ raise ValueError("audience must match app id")
98
+ lifetime_seconds = self.exp - self.iat
99
+ if lifetime_seconds <= 0 or lifetime_seconds > MAX_INTEGRATION_REQUEST_LIFETIME_SECONDS:
100
+ raise ValueError("integration request lifetime must be positive and bounded")
101
+ return self
102
+
103
+ def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
104
+ copied = super().model_copy(deep=deep)
105
+ data = copied.model_dump(round_trip=True)
106
+ if update is not None:
107
+ data.update(update)
108
+ return type(self).model_validate(data)
@@ -0,0 +1,7 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class ErrorResponse(BaseModel):
5
+ code: str
6
+ message: str
7
+ request_id: str | None = None
@@ -0,0 +1,164 @@
1
+ import re
2
+ from typing import Any
3
+ from urllib.parse import urlsplit
4
+
5
+ from pydantic import (
6
+ BaseModel,
7
+ ConfigDict,
8
+ Field,
9
+ HttpUrl,
10
+ field_serializer,
11
+ field_validator,
12
+ model_validator,
13
+ )
14
+
15
+
16
+ IDENTIFIER_PATTERN = r"^[a-z0-9]+(?:[._:-][a-z0-9]+)*$"
17
+ INTERNAL_UPSTREAM_PATH_PATTERN = re.compile(r"^/[A-Za-z0-9._:-]+(?:/[A-Za-z0-9._:-]+)*$")
18
+ CONTENT_TYPE_PATTERN = re.compile(r"^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+*-]+$")
19
+ SAFE_EXTERNAL_INGRESS_METHODS = frozenset({"GET", "POST", "PUT", "DELETE"})
20
+ MAX_EXTERNAL_INGRESS_BODY_BYTES = 100 * 1024 * 1024
21
+ MAX_EXTERNAL_INGRESS_RATE_REQUESTS = 1_000
22
+ MAX_EXTERNAL_INGRESS_RATE_WINDOW_SECONDS = 3_600
23
+
24
+
25
+ class Publisher(BaseModel):
26
+ name: str
27
+
28
+
29
+ class ServiceDefinition(BaseModel):
30
+ base_url: HttpUrl | str
31
+ health_url: str
32
+ manifest_url: str
33
+ openapi_url: str
34
+
35
+
36
+ class NavigationEntry(BaseModel):
37
+ id: str
38
+ label: str
39
+ path: str
40
+ icon: str | None = None
41
+
42
+
43
+ class NavigationDefinition(BaseModel):
44
+ entries: list[NavigationEntry]
45
+
46
+
47
+ class PermissionDefinition(BaseModel):
48
+ id: str
49
+ description: str
50
+
51
+
52
+ class SettingsDefinition(BaseModel):
53
+ sections: list[dict[str, Any]] = Field(default_factory=list)
54
+
55
+
56
+ class ExternalIngressRatePolicy(BaseModel):
57
+ model_config = ConfigDict(frozen=True)
58
+
59
+ requests: int = Field(strict=True, gt=0, le=MAX_EXTERNAL_INGRESS_RATE_REQUESTS)
60
+ window_seconds: int = Field(
61
+ strict=True, gt=0, le=MAX_EXTERNAL_INGRESS_RATE_WINDOW_SECONDS
62
+ )
63
+
64
+
65
+ class ExternalIngressDefinition(BaseModel):
66
+ model_config = ConfigDict(frozen=True)
67
+
68
+ capability_id: str = Field(pattern=IDENTIFIER_PATTERN)
69
+ audience: str = Field(pattern=IDENTIFIER_PATTERN)
70
+ allowed_methods: tuple[str, ...] = Field(min_length=1)
71
+ allowed_content_types: tuple[str, ...] = Field(min_length=1)
72
+ internal_upstream_path: str
73
+ scopes: tuple[str, ...] = Field(min_length=1)
74
+ max_body_bytes: int = Field(strict=True, gt=0, le=MAX_EXTERNAL_INGRESS_BODY_BYTES)
75
+ rate_policy: ExternalIngressRatePolicy
76
+
77
+ @field_validator("allowed_methods")
78
+ @classmethod
79
+ def validate_allowed_methods(cls, methods: tuple[str, ...]) -> tuple[str, ...]:
80
+ if len(set(methods)) != len(methods):
81
+ raise ValueError("allowed methods must be unique")
82
+ if any(method not in SAFE_EXTERNAL_INGRESS_METHODS for method in methods):
83
+ raise ValueError("allowed methods must be safe uppercase HTTP methods")
84
+ return methods
85
+
86
+ @field_validator("allowed_content_types")
87
+ @classmethod
88
+ def validate_allowed_content_types(
89
+ cls, content_types: tuple[str, ...]
90
+ ) -> tuple[str, ...]:
91
+ if len(set(content_types)) != len(content_types):
92
+ raise ValueError("allowed content types must be unique")
93
+ if any(CONTENT_TYPE_PATTERN.fullmatch(value) is None for value in content_types):
94
+ raise ValueError("allowed content types must be media types")
95
+ return content_types
96
+
97
+ @field_validator("scopes")
98
+ @classmethod
99
+ def validate_scopes(cls, scopes: tuple[str, ...]) -> tuple[str, ...]:
100
+ if len(set(scopes)) != len(scopes):
101
+ raise ValueError("scopes must be unique")
102
+ if any(re.fullmatch(IDENTIFIER_PATTERN, scope) is None for scope in scopes):
103
+ raise ValueError("scopes must be identifiers")
104
+ return scopes
105
+
106
+ @field_serializer("allowed_methods", "allowed_content_types", "scopes")
107
+ def serialize_policy_tuple(self, value: tuple[str, ...]) -> list[str]:
108
+ return list(value)
109
+
110
+ @field_validator("internal_upstream_path")
111
+ @classmethod
112
+ def validate_internal_upstream_path(cls, path: str) -> str:
113
+ parsed = urlsplit(path)
114
+ segments = parsed.path.split("/")
115
+ if (
116
+ INTERNAL_UPSTREAM_PATH_PATTERN.fullmatch(path) is None
117
+ or path.startswith("//")
118
+ or path.endswith("/")
119
+ or parsed.scheme
120
+ or parsed.netloc
121
+ or parsed.query
122
+ or parsed.fragment
123
+ or "%" in path
124
+ or "\\" in path
125
+ or "" in segments[1:]
126
+ or ".." in segments
127
+ or "." in segments
128
+ ):
129
+ raise ValueError("internal upstream path must be a normalized absolute path")
130
+ return path
131
+
132
+
133
+ class AppManifest(BaseModel):
134
+ schema_version: str
135
+ app_id: str
136
+ slug: str
137
+ name: str
138
+ version: str
139
+ publisher: Publisher
140
+ service: ServiceDefinition
141
+ navigation: NavigationDefinition
142
+ description: str | None = None
143
+ permissions: list[PermissionDefinition] = Field(default_factory=list)
144
+ settings: SettingsDefinition = Field(default_factory=SettingsDefinition)
145
+ triggers: list[dict[str, Any]] = Field(default_factory=list)
146
+ actions: list[dict[str, Any]] = Field(default_factory=list)
147
+ jobs: list[dict[str, Any]] = Field(default_factory=list)
148
+ ai_tools: list[dict[str, Any]] = Field(default_factory=list)
149
+ external_ingress: tuple[ExternalIngressDefinition, ...] = Field(
150
+ default_factory=tuple, exclude_if=lambda value: value == ()
151
+ )
152
+
153
+ @field_serializer("external_ingress")
154
+ def serialize_external_ingress(
155
+ self, value: tuple[ExternalIngressDefinition, ...]
156
+ ) -> list[ExternalIngressDefinition]:
157
+ return list(value)
158
+
159
+ @model_validator(mode="after")
160
+ def validate_unique_external_ingress_capability_ids(self) -> "AppManifest":
161
+ capability_ids = [entry.capability_id for entry in self.external_ingress]
162
+ if len(set(capability_ids)) != len(capability_ids):
163
+ raise ValueError("external ingress capability ids must be unique")
164
+ return self
@@ -0,0 +1,6 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class RequestContext(BaseModel):
5
+ request_id: str
6
+ service: str
File without changes
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.11.28,<0.12"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "meshflow-contracts"
7
+ version = "0.2.3"
8
+ description = "Shared MeshFlow platform contracts."
9
+ readme = "README.md"
10
+ requires-python = ">=3.14"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [
14
+ { name = "MeshFlow contributors" },
15
+ ]
16
+ keywords = ["meshflow", "contracts", "pydantic", "schemas"]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Intended Audience :: Developers",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = [
26
+ "pydantic>=2.13.4,<3",
27
+ ]
28
+
29
+ [project.urls]
30
+ Repository = "https://github.com/MeshFlow-os/meshflow-contracts"
31
+ Issues = "https://github.com/MeshFlow-os/meshflow-contracts/issues"
32
+ Changelog = "https://github.com/MeshFlow-os/meshflow-contracts/blob/main/CHANGELOG.md"
33
+
34
+ [dependency-groups]
35
+ dev = [
36
+ "mypy>=1.19.1",
37
+ "pyyaml>=6.0.3",
38
+ "pytest>=9.0.2",
39
+ "ruff>=0.14.14",
40
+ "types-pyyaml>=6.0.12",
41
+ ]
42
+
43
+ [tool.ruff]
44
+ line-length = 100
45
+ target-version = "py314"
46
+
47
+ [tool.mypy]
48
+ python_version = "3.14"
49
+ strict = true
50
+ warn_unused_configs = true
51
+ plugins = ["pydantic.mypy"]
52
+
53
+ [tool.pytest.ini_options]
54
+ pythonpath = ["."]
55
+ markers = [
56
+ "integration: builds and smoke-installs real release distributions",
57
+ ]
58
+
59
+ [tool.uv]
60
+ required-version = "==0.11.28"
61
+
62
+ [tool.uv.build-backend]
63
+ module-root = ""
64
+ module-name = "meshflow_contracts"