1password-agent-broker-sdk 0.4.0__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,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: 1password-agent-broker-sdk
3
+ Version: 0.4.0
4
+ Summary: Typed mTLS client for independently deployed 1Password Agent Broker services
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Author: Astrivant
8
+ Requires-Python: >=3.12,!=3.14.1,<4
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Programming Language :: Python :: 3.15
14
+ Requires-Dist: attrs (>=26.1,<27)
15
+ Requires-Dist: cattrs (>=26.2.1,<27)
16
+ Requires-Dist: jsonschema (>=4.26,<5)
17
+ Project-URL: Documentation, https://github.com/astrivant/1password-agent-broker/blob/main/packages/sdk/README.md
18
+ Project-URL: Repository, https://github.com/astrivant/1password-agent-broker
19
+ Description-Content-Type: text/markdown
20
+
21
+ # 1Password Agent Broker SDK
22
+
23
+ A typed, bounded mTLS client for the separately deployed
24
+ [1Password Agent Broker](https://github.com/astrivant/1password-agent-broker).
25
+ Service clients install this distribution to request key operations without
26
+ installing the broker server, its 1Password integration or its database adapters.
27
+
28
+ <!-- toc -->
29
+
30
+ - [Install](#install)
31
+ - [Inputs and authority](#inputs-and-authority)
32
+ - [Compatibility and failures](#compatibility-and-failures)
33
+ - [Development and publication](#development-and-publication)
34
+
35
+ <!-- /toc -->
36
+
37
+ ## Install
38
+
39
+ Requires Python 3.12 or newer, excluding 3.14.1. After the SDK release is published:
40
+
41
+ ```bash
42
+ python -m pip install 1password-agent-broker-sdk
43
+ ```
44
+
45
+ Import `CryptoClient`, `Binding` and `Request` from `agent_broker_sdk`. Construct
46
+ `CryptoClient(url, ca, cert, key)` using operator-provided paths, then pass a typed
47
+ `Request` to `invoke`. The returned bytes may contain a transient data key: keep
48
+ them inside the trusted service and out of logs, agent context and persistent
49
+ storage. See the [key service contract](https://github.com/astrivant/1password-agent-broker/blob/main/docs/key-service.md) for request
50
+ fields and operator setup.
51
+
52
+ ## Inputs and authority
53
+
54
+ | Input | Meaning |
55
+ | --- | --- |
56
+ | `url` | Fixed HTTPS broker origin; no path, credentials, query or fragment |
57
+ | `ca` | Path to the trusted broker certificate authority |
58
+ | `cert`, `key` | Paths to the workload's scoped TLS certificate and private key |
59
+ | `Request` | Opaque grant, task, authority, policy and key identifiers, immutable record binding and operation payload |
60
+
61
+ The client holds no 1Password service token or custodial private key. The broker
62
+ checks current policy for each operation. SDK validation checks wire shape; it
63
+ does not grant permission. A small dependency set does not limit the authority
64
+ of an overprivileged certificate.
65
+
66
+ ## Compatibility and failures
67
+
68
+ The SDK owns protocol-version-one models and schemas. The server imports these
69
+ same contracts. Its original `agent_broker.crypto.client.CryptoClient` import
70
+ remains available with the original runtime exception boundary.
71
+
72
+ The SDK requires TLS 1.3, verifies server identity, presents a client certificate,
73
+ limits messages to 4 KiB and decoded results to 1 KiB, and uses a 30-second socket
74
+ timeout. It raises a fixed `BrokerError` without reflecting payloads or policy.
75
+ Calls have no implicit retry; callers retain the exact request UUID and payload
76
+ when explicitly recovering a request. No admin, provider or policy-edit API is
77
+ included.
78
+
79
+ ## Development and publication
80
+
81
+ The repository's root lockfile owns the SDK test environment. Both distributions
82
+ use the same release version and immutable source tag. CI tests the SDK's isolated
83
+ wheel and real mTLS transport before publishing signed archives and both PyPI
84
+ packages. The SDK has no server dependency; the server depends on its exact SDK
85
+ version. Local Poetry development resolves that dependency from this directory,
86
+ while wheel metadata names the versioned registry distribution.
87
+
@@ -0,0 +1,66 @@
1
+ # 1Password Agent Broker SDK
2
+
3
+ A typed, bounded mTLS client for the separately deployed
4
+ [1Password Agent Broker](https://github.com/astrivant/1password-agent-broker).
5
+ Service clients install this distribution to request key operations without
6
+ installing the broker server, its 1Password integration or its database adapters.
7
+
8
+ <!-- toc -->
9
+
10
+ - [Install](#install)
11
+ - [Inputs and authority](#inputs-and-authority)
12
+ - [Compatibility and failures](#compatibility-and-failures)
13
+ - [Development and publication](#development-and-publication)
14
+
15
+ <!-- /toc -->
16
+
17
+ ## Install
18
+
19
+ Requires Python 3.12 or newer, excluding 3.14.1. After the SDK release is published:
20
+
21
+ ```bash
22
+ python -m pip install 1password-agent-broker-sdk
23
+ ```
24
+
25
+ Import `CryptoClient`, `Binding` and `Request` from `agent_broker_sdk`. Construct
26
+ `CryptoClient(url, ca, cert, key)` using operator-provided paths, then pass a typed
27
+ `Request` to `invoke`. The returned bytes may contain a transient data key: keep
28
+ them inside the trusted service and out of logs, agent context and persistent
29
+ storage. See the [key service contract](https://github.com/astrivant/1password-agent-broker/blob/main/docs/key-service.md) for request
30
+ fields and operator setup.
31
+
32
+ ## Inputs and authority
33
+
34
+ | Input | Meaning |
35
+ | --- | --- |
36
+ | `url` | Fixed HTTPS broker origin; no path, credentials, query or fragment |
37
+ | `ca` | Path to the trusted broker certificate authority |
38
+ | `cert`, `key` | Paths to the workload's scoped TLS certificate and private key |
39
+ | `Request` | Opaque grant, task, authority, policy and key identifiers, immutable record binding and operation payload |
40
+
41
+ The client holds no 1Password service token or custodial private key. The broker
42
+ checks current policy for each operation. SDK validation checks wire shape; it
43
+ does not grant permission. A small dependency set does not limit the authority
44
+ of an overprivileged certificate.
45
+
46
+ ## Compatibility and failures
47
+
48
+ The SDK owns protocol-version-one models and schemas. The server imports these
49
+ same contracts. Its original `agent_broker.crypto.client.CryptoClient` import
50
+ remains available with the original runtime exception boundary.
51
+
52
+ The SDK requires TLS 1.3, verifies server identity, presents a client certificate,
53
+ limits messages to 4 KiB and decoded results to 1 KiB, and uses a 30-second socket
54
+ timeout. It raises a fixed `BrokerError` without reflecting payloads or policy.
55
+ Calls have no implicit retry; callers retain the exact request UUID and payload
56
+ when explicitly recovering a request. No admin, provider or policy-edit API is
57
+ included.
58
+
59
+ ## Development and publication
60
+
61
+ The repository's root lockfile owns the SDK test environment. Both distributions
62
+ use the same release version and immutable source tag. CI tests the SDK's isolated
63
+ wheel and real mTLS transport before publishing signed archives and both PyPI
64
+ packages. The SDK has no server dependency; the server depends on its exact SDK
65
+ version. Local Poetry development resolves that dependency from this directory,
66
+ while wheel metadata names the versioned registry distribution.
@@ -0,0 +1,11 @@
1
+ """
2
+ Connect typed service clients to an independently deployed credential broker over mutual TLS.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from agent_broker_sdk.client import CryptoClient
8
+ from agent_broker_sdk.exceptions import BrokerError
9
+ from agent_broker_sdk.models import Binding, Request, Response
10
+
11
+ __all__ = ["Binding", "BrokerError", "CryptoClient", "Request", "Response"]
@@ -0,0 +1,97 @@
1
+ """
2
+ Send service-only key requests over authenticated TLS without provider or server dependencies.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import ssl
9
+ from http.client import HTTPException, HTTPSConnection
10
+ from typing import TYPE_CHECKING
11
+ from urllib.parse import urlsplit
12
+
13
+ from agent_broker_sdk import contracts
14
+ from agent_broker_sdk.exceptions import BrokerError
15
+
16
+ if TYPE_CHECKING:
17
+ from pathlib import Path
18
+
19
+ from agent_broker_sdk.models import Request
20
+
21
+ __all__ = ["CryptoClient"]
22
+
23
+
24
+ class CryptoClient:
25
+ """
26
+ Own transport configuration while the deployed broker owns authorization and key custody.
27
+ """
28
+
29
+ def __init__(self, url: str, ca: Path, cert: Path, key: Path) -> None:
30
+ """
31
+ Load a trusted HTTPS origin and the workload's scoped client certificate.
32
+
33
+ Args:
34
+ url (str): Broker HTTPS origin without credentials, query or fragment.
35
+ ca (Path): Trusted broker certificate authority.
36
+ cert (Path): Workload certificate approved by the broker operator.
37
+ key (Path): Workload TLS key; never a provider credential or custodial key.
38
+
39
+ Raises:
40
+ BrokerError: Origin or certificate configuration is invalid, without reflecting input.
41
+ """
42
+ try:
43
+ parsed = urlsplit(url)
44
+ if (
45
+ parsed.scheme != "https"
46
+ or not parsed.hostname
47
+ or parsed.path not in ("", "/")
48
+ or parsed.username is not None
49
+ or parsed.password is not None
50
+ or "?" in url
51
+ or "#" in url
52
+ or parsed.port == 0
53
+ or not url.isascii()
54
+ or any(ord(character) < 33 or ord(character) == 127 for character in url)
55
+ ):
56
+ raise BrokerError("Invalid broker origin")
57
+ self.host = parsed.hostname
58
+ self.port = parsed.port or 443
59
+ self.context = ssl.create_default_context(cafile=ca)
60
+ self.context.minimum_version = ssl.TLSVersion.TLSv1_3
61
+ self.context.load_cert_chain(cert, key)
62
+ except (OSError, ValueError):
63
+ raise BrokerError("Invalid broker transport configuration") from None
64
+
65
+ def invoke(self, request: Request) -> bytes:
66
+ """
67
+ Send one bounded operation without implicit retries or payload logging.
68
+
69
+ Args:
70
+ request (Request): Exact scoped request, including its retry identity.
71
+
72
+ Returns:
73
+ bytes: Authorized result; transient data keys must remain outside logs and agent context.
74
+
75
+ Raises:
76
+ BrokerError: Validation, admission, authorization or transport failed. No plaintext fallback.
77
+ """
78
+ connection = HTTPSConnection(self.host, self.port, context=self.context, timeout=30)
79
+ try:
80
+ body = contracts.encode(contracts.data(contracts.parse_request(contracts.data(request))))
81
+ if len(body) > 4096:
82
+ raise BrokerError("Invalid broker request")
83
+ connection.request("POST", "/crypto", body=body, headers={"Content-Type": "application/json"})
84
+ response = connection.getresponse()
85
+
86
+ # One extra byte distinguishes an oversized body from a complete bounded response.
87
+ payload = response.read(4097)
88
+ if response.status != 200 or len(payload) > 4096:
89
+ raise BrokerError("Invalid broker response")
90
+ result = contracts.parse_response(json.loads(payload))
91
+ if result.code != "ok":
92
+ raise BrokerError("Broker operation unavailable")
93
+ return contracts.decode(result.payload, 1024)
94
+ except (OSError, HTTPException, ValueError, BrokerError):
95
+ raise BrokerError("Broker operation unavailable") from None
96
+ finally:
97
+ connection.close()
@@ -0,0 +1,178 @@
1
+ """
2
+ Validate versioned service wire data without importing the broker runtime.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import base64
8
+ import json
9
+ from importlib.resources import files
10
+ from typing import TypeVar
11
+ from uuid import UUID
12
+
13
+ from cattrs import Converter
14
+ from cattrs.errors import BaseValidationError
15
+ from jsonschema import ValidationError, validate
16
+
17
+ from agent_broker_sdk.exceptions import BrokerError
18
+ from agent_broker_sdk.models import Binding, Request, Response
19
+
20
+ __all__ = ["aad", "data", "decode", "encode", "parse_request", "parse_response", "schema"]
21
+ CONVERTER = Converter(forbid_extra_keys=True)
22
+ T = TypeVar("T")
23
+
24
+
25
+ def encode(value: object) -> bytes:
26
+ """
27
+ Encode deterministic JSON for wire requests and immutable context bindings.
28
+
29
+ Args:
30
+ value (object): JSON-compatible input.
31
+
32
+ Returns:
33
+ bytes: Canonical UTF-8 serialization.
34
+ """
35
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
36
+
37
+
38
+ def data(value: Binding | Request | Response) -> dict[str, object]:
39
+ """
40
+ Convert one shared model into a JSON-compatible object.
41
+
42
+ Args:
43
+ value (Binding | Request | Response): Supported wire model.
44
+
45
+ Returns:
46
+ dict[str, object]: Unstructured representation; payloads remain sensitive.
47
+ """
48
+ result: dict[str, object] = CONVERTER.unstructure(value)
49
+ return result
50
+
51
+
52
+ def schema(name: str) -> dict[str, object]:
53
+ """
54
+ Load a shared, closed wire schema from the installed SDK.
55
+
56
+ Args:
57
+ name (str): Request or response schema stem.
58
+
59
+ Returns:
60
+ dict[str, object]: Maintained schema, without network access.
61
+
62
+ Raises:
63
+ BrokerError: The schema name is unsupported.
64
+ """
65
+ if name not in ("crypto-request", "crypto-response"):
66
+ raise BrokerError("Unsupported broker contract")
67
+ result: dict[str, object] = json.loads(files("agent_broker_sdk").joinpath(f"resources/{name}.schema.json").read_text())
68
+ return result
69
+
70
+
71
+ # Retain syntax supported by the project's pinned docstring checker.
72
+ def _structure(value: object, model: type[T], name: str) -> T: # noqa: UP047
73
+ """
74
+ Validate before conversion while suppressing reflected untrusted values.
75
+
76
+ Args:
77
+ value (object): Untrusted decoded JSON.
78
+ model (type[T]): Expected shared model.
79
+ name (str): Packaged schema stem.
80
+
81
+ Returns:
82
+ T: Validated typed model.
83
+
84
+ Raises:
85
+ BrokerError: Input violates the closed wire contract.
86
+ """
87
+ try:
88
+ validate(value, schema(name))
89
+ return CONVERTER.structure(value, model)
90
+ except (ValidationError, BaseValidationError, TypeError, ValueError):
91
+ raise BrokerError("Invalid broker contract") from None
92
+
93
+
94
+ def aad(binding: Binding) -> bytes:
95
+ """
96
+ Bind cryptography to immutable context independently of current access policy.
97
+
98
+ Args:
99
+ binding (Binding): Independently validated expected record context.
100
+
101
+ Returns:
102
+ bytes: Domain-separated canonical JSON, unchanged from protocol version one.
103
+ """
104
+ return b"agent-broker-record-v1\x00" + encode(data(binding))
105
+
106
+
107
+ def decode(value: str, maximum: int) -> bytes:
108
+ """
109
+ Reject oversized or noncanonical base64 without reflecting payloads.
110
+
111
+ Args:
112
+ value (str): Untrusted encoded bytes.
113
+ maximum (int): Maximum decoded size.
114
+
115
+ Returns:
116
+ bytes: Bounded decoded payload.
117
+
118
+ Raises:
119
+ BrokerError: Encoding or size is invalid.
120
+ """
121
+ try:
122
+ if len(value) > ((maximum + 2) // 3) * 4:
123
+ raise BrokerError("Invalid broker payload")
124
+ result = base64.b64decode(value, validate=True)
125
+ if len(result) > maximum or base64.b64encode(result).decode() != value:
126
+ raise BrokerError("Invalid broker payload")
127
+ return result
128
+ except (ValueError, UnicodeError):
129
+ raise BrokerError("Invalid broker payload") from None
130
+
131
+
132
+ def parse_request(value: object) -> Request:
133
+ """
134
+ Enforce closed fields and canonical identifiers without evaluating authorization.
135
+
136
+ Args:
137
+ value (object): Untrusted decoded request.
138
+
139
+ Returns:
140
+ Request: Valid wire request; permission remains a server decision.
141
+
142
+ Raises:
143
+ BrokerError: A field or opaque identifier is invalid.
144
+ """
145
+ request = _structure(value, Request, "crypto-request")
146
+ identifiers = (
147
+ request.request_id,
148
+ request.grant,
149
+ request.key,
150
+ request.task,
151
+ request.authority,
152
+ request.policy,
153
+ request.binding.tenant,
154
+ request.binding.identity,
155
+ request.binding.record,
156
+ )
157
+ try:
158
+ if any(str(UUID(value)) != value for value in identifiers):
159
+ raise BrokerError("Invalid broker scope")
160
+ except ValueError:
161
+ raise BrokerError("Invalid broker scope") from None
162
+ return request
163
+
164
+
165
+ def parse_response(value: object) -> Response:
166
+ """
167
+ Validate a bounded response before exposing any returned key bytes.
168
+
169
+ Args:
170
+ value (object): Untrusted decoded response.
171
+
172
+ Returns:
173
+ Response: Closed result contract.
174
+
175
+ Raises:
176
+ BrokerError: A response field is invalid.
177
+ """
178
+ return _structure(value, Response, "crypto-response")
@@ -0,0 +1,13 @@
1
+ """
2
+ Expose bounded client failures independently of the broker runtime.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ __all__ = ["BrokerError"]
8
+
9
+
10
+ class BrokerError(RuntimeError):
11
+ """
12
+ Report a fixed transport or contract error without reflecting sensitive payloads.
13
+ """
@@ -0,0 +1,80 @@
1
+ """
2
+ Own the shared version-one service wire models without importing the server or provider SDK.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Literal
8
+
9
+ from attrs import field, frozen
10
+
11
+ __all__ = ["Binding", "CryptoAction", "Request", "Response"]
12
+ CryptoAction = Literal["wrap", "unwrap", "sign", "public"]
13
+
14
+
15
+ @frozen
16
+ class Binding:
17
+ """
18
+ Bind a cryptographic result to independently authorized opaque scope and immutable content identity.
19
+
20
+ Attributes:
21
+ tenant (str): Opaque tenant UUID.
22
+ identity (str): Opaque identity UUID.
23
+ record (str): Immutable record or representation UUID.
24
+ kind (int): Versioned record-kind code, without a private label.
25
+ schema (int): Logical record schema version.
26
+ codec (int): Deterministic payload codec version.
27
+ hash (int): Semantic hash-domain version.
28
+ envelope (int): Encryption envelope version.
29
+ """
30
+
31
+ tenant: str
32
+ identity: str
33
+ record: str
34
+ kind: int
35
+ schema: int = 1
36
+ codec: int = 1
37
+ hash: int = 1
38
+ envelope: int = 1
39
+
40
+
41
+ @frozen
42
+ class Request:
43
+ """
44
+ Request one bounded cryptographic operation without a 1Password reference or private key.
45
+
46
+ Attributes:
47
+ request_id (str): Fresh request UUID, retained for exact retries.
48
+ grant (str): Operator-issued grant UUID.
49
+ action (CryptoAction): Requested service operation.
50
+ key (str): Allowed key generation UUID.
51
+ binding (Binding): Immutable record context checked against current operator policy.
52
+ task (str): Current authorized task UUID, separate from permanent cryptographic context.
53
+ authority (str): Current authority fence UUID.
54
+ policy (str): Current access-policy revision UUID.
55
+ payload (str): Base64 data key, wrapped key or ciphertext digest; excluded from repr.
56
+ """
57
+
58
+ request_id: str
59
+ grant: str
60
+ action: CryptoAction
61
+ key: str
62
+ binding: Binding
63
+ task: str
64
+ authority: str
65
+ policy: str
66
+ payload: str = field(repr=False)
67
+
68
+
69
+ @frozen
70
+ class Response:
71
+ """
72
+ Carry a service response whose key material must never enter logs or agent context.
73
+
74
+ Attributes:
75
+ code (Literal["ok", "denied", "unavailable"]): Bounded result category.
76
+ payload (str): Base64 result; transient data keys are service-only and excluded from repr.
77
+ """
78
+
79
+ code: Literal["ok", "denied", "unavailable"]
80
+ payload: str = field(default="", repr=False)
@@ -0,0 +1,99 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "request_id": {
7
+ "type": "string",
8
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
9
+ },
10
+ "grant": {
11
+ "type": "string",
12
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
13
+ },
14
+ "action": {
15
+ "enum": [
16
+ "wrap",
17
+ "unwrap",
18
+ "sign",
19
+ "public"
20
+ ]
21
+ },
22
+ "key": {
23
+ "type": "string",
24
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
25
+ },
26
+ "binding": {
27
+ "type": "object",
28
+ "additionalProperties": false,
29
+ "properties": {
30
+ "tenant": {
31
+ "type": "string",
32
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
33
+ },
34
+ "identity": {
35
+ "type": "string",
36
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
37
+ },
38
+ "record": {
39
+ "type": "string",
40
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
41
+ },
42
+ "kind": {
43
+ "type": "integer",
44
+ "minimum": 1,
45
+ "maximum": 65535
46
+ },
47
+ "schema": {
48
+ "type": "integer",
49
+ "const": 1
50
+ },
51
+ "codec": {
52
+ "type": "integer",
53
+ "const": 1
54
+ },
55
+ "hash": {
56
+ "type": "integer",
57
+ "const": 1
58
+ },
59
+ "envelope": {
60
+ "type": "integer",
61
+ "const": 1
62
+ }
63
+ },
64
+ "required": [
65
+ "tenant",
66
+ "identity",
67
+ "record",
68
+ "kind"
69
+ ]
70
+ },
71
+ "payload": {
72
+ "type": "string",
73
+ "maxLength": 1400
74
+ },
75
+ "task": {
76
+ "type": "string",
77
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
78
+ },
79
+ "authority": {
80
+ "type": "string",
81
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
82
+ },
83
+ "policy": {
84
+ "type": "string",
85
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
86
+ }
87
+ },
88
+ "required": [
89
+ "request_id",
90
+ "grant",
91
+ "action",
92
+ "key",
93
+ "binding",
94
+ "payload",
95
+ "task",
96
+ "authority",
97
+ "policy"
98
+ ]
99
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "code": {
7
+ "enum": [
8
+ "ok",
9
+ "denied",
10
+ "unavailable"
11
+ ]
12
+ },
13
+ "payload": {
14
+ "type": "string",
15
+ "maxLength": 1400
16
+ }
17
+ },
18
+ "required": [
19
+ "code"
20
+ ]
21
+ }
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "1password-agent-broker-sdk"
3
+ version = "0.4.0"
4
+ description = "Typed mTLS client for independently deployed 1Password Agent Broker services"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12,!=3.14.1,<4"
7
+ license = "Apache-2.0"
8
+ authors = [{name = "Astrivant"}]
9
+ dependencies = ["attrs>=26.1,<27", "cattrs>=26.2.1,<27", "jsonschema>=4.26,<5"]
10
+
11
+ [project.urls]
12
+ Repository = "https://github.com/astrivant/1password-agent-broker"
13
+ Documentation = "https://github.com/astrivant/1password-agent-broker/blob/main/packages/sdk/README.md"
14
+
15
+ [build-system]
16
+ requires = ["poetry-core==2.5.0"]
17
+ build-backend = "poetry.core.masonry.api"
18
+
19
+ [tool.poetry]
20
+ packages = [{include = "agent_broker_sdk", from = "pkg"}]
21
+ include = [{path = "pkg/agent_broker_sdk/resources", format = ["sdist", "wheel"]}]
22
+
23
+ [tool.ruff]
24
+ extend = "../../pyproject.toml"