From 6a01340e04c6293a19d1c9f258666a5fb0fed48d Mon Sep 17 00:00:00 2001 From: Stephen Balogh Date: Wed, 18 Nov 2026 23:11:03 +0000 Subject: [PATCH 1/3] feat: network policies Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- docs/source/api-reference.md | 12 ++++ src/s2_sdk/__init__.py | 8 +++ src/s2_sdk/_mappers.py | 56 +++++++++++++++ src/s2_sdk/_ops.py | 135 ++++++++++++++++++++++++++++++++++- src/s2_sdk/_types.py | 51 +++++++++++++ tests/test_account_ops.py | 36 ++++++++++ tests/test_mappers.py | 18 ++++- 7 files changed, 314 insertions(+), 2 deletions(-) diff --git a/docs/source/api-reference.md b/docs/source/api-reference.md index 7c2cd33..5b833b5 100644 --- a/docs/source/api-reference.md +++ b/docs/source/api-reference.md @@ -144,6 +144,18 @@ .. autoclass:: AccessTokenInfo() :members: +.. autoclass:: PublicNetCidrs + :members: + +.. autoclass:: AwsPrivateNetPolicy + :members: + +.. autoclass:: NetworkPolicy(public_net: PublicNetCidrs | Unknown | None = None, private_net: AwsPrivateNetPolicy | Unknown | None = None) + :members: + +.. autoclass:: NetworkPolicyInfo() + :members: + .. autoenum:: MetricUnit .. autoenum:: TimeseriesInterval diff --git a/src/s2_sdk/__init__.py b/src/s2_sdk/__init__.py index af8fcee..f1ac039 100644 --- a/src/s2_sdk/__init__.py +++ b/src/s2_sdk/__init__.py @@ -24,6 +24,7 @@ AppendAck, AppendInput, AppendRetryPolicy, + AwsPrivateNetPolicy, BasinConfig, BasinInfo, BasinMetricSet, @@ -41,11 +42,14 @@ Label, LocationInfo, MetricUnit, + NetworkPolicy, + NetworkPolicyInfo, Operation, OperationGroupPermissions, Page, Permission, PrefixMatch, + PublicNetCidrs, ReadBatch, ReadLimit, Record, @@ -120,6 +124,10 @@ "OperationGroupPermissions", "AccessTokenScope", "AccessTokenInfo", + "PublicNetCidrs", + "AwsPrivateNetPolicy", + "NetworkPolicy", + "NetworkPolicyInfo", "MetricUnit", "TimeseriesInterval", "AccountMetricSet", diff --git a/src/s2_sdk/_mappers.py b/src/s2_sdk/_mappers.py index 5427382..050fc4e 100644 --- a/src/s2_sdk/_mappers.py +++ b/src/s2_sdk/_mappers.py @@ -10,6 +10,7 @@ Accumulation, AppendAck, AppendInput, + AwsPrivateNetPolicy, BasinConfig, BasinInfo, Encryption, @@ -21,10 +22,13 @@ Label, LocationInfo, MetricUnit, + NetworkPolicy, + NetworkPolicyInfo, Operation, OperationGroupPermissions, Permission, PrefixMatch, + PublicNetCidrs, ReadBatch, ReadLimit, Record, @@ -283,6 +287,7 @@ def access_token_info_to_json( scope: AccessTokenScope, auto_prefix_streams: bool, expires_at: datetime | None, + network_policy: str | None = None, ) -> dict[str, Any]: scope_json: dict[str, Any] = {} if scope.basins is not None: @@ -310,6 +315,8 @@ def access_token_info_to_json( } if expires_at is not None: result["expires_at"] = expires_at.isoformat() + if network_policy is not None: + result["network_policy"] = network_policy return result @@ -340,6 +347,55 @@ def access_token_info_from_json(data: dict[str, Any]) -> AccessTokenInfo: if data.get("expires_at") else None, auto_prefix_streams=data.get("auto_prefix_streams", False), + network_policy=data.get("network_policy"), + ) + + +def network_policy_to_json(policy: NetworkPolicy) -> dict[str, Any]: + result: dict[str, Any] = {} + match policy.public_net: + case PublicNetCidrs(cidrs=cidrs): + result["public_net"] = {"cidrs": cidrs} + case Unknown(kind=kind): + result["public_net"] = kind + match policy.private_net: + case AwsPrivateNetPolicy(vpce_ids=vpce_ids): + result["private_net"] = {"aws": {"vpce_ids": vpce_ids}} + case Unknown(kind=kind): + result["private_net"] = kind + return result + + +def _public_net_policy_from_json( + data: dict[str, Any] | None, +) -> PublicNetCidrs | Unknown | None: + if data is None: + return None + if (cidrs := data.get("cidrs")) is not None: + return PublicNetCidrs(cidrs=cidrs) + return _unknown_kind(data) + + +def _private_net_policy_from_json( + data: dict[str, Any] | None, +) -> AwsPrivateNetPolicy | Unknown | None: + if data is None: + return None + if (aws := data.get("aws")) is not None: + return AwsPrivateNetPolicy(vpce_ids=aws["vpce_ids"]) + return _unknown_kind(data) + + +def network_policy_info_from_json(data: dict[str, Any]) -> NetworkPolicyInfo: + policy = data["policy"] + return NetworkPolicyInfo( + id=data["id"], + slug=data["slug"], + created_at=datetime.fromisoformat(data["created_at"]), + policy=NetworkPolicy( + public_net=_public_net_policy_from_json(policy.get("public_net")), + private_net=_private_net_policy_from_json(policy.get("private_net")), + ), ) diff --git a/src/s2_sdk/_ops.py b/src/s2_sdk/_ops.py index 05903d5..24ee460 100644 --- a/src/s2_sdk/_ops.py +++ b/src/s2_sdk/_ops.py @@ -23,6 +23,8 @@ ensured_stream_info_from_json_and_headers, location_info_from_json, metric_set_from_json, + network_policy_info_from_json, + network_policy_to_json, read_batch_from_proto, read_limit_params, read_start_params, @@ -457,6 +459,7 @@ async def issue_access_token( scope: types.AccessTokenScope, expires_at: datetime | None = None, auto_prefix_streams: bool = False, + network_policy: str | None = None, ) -> str: """Issue an access token. @@ -466,12 +469,17 @@ async def issue_access_token( expires_at: Optional expiration time. auto_prefix_streams: Automatically prefix stream names during creation and strip the prefix during listing. + network_policy: Slug or full ``.`` reference of a network + policy to restrict the token by. A slug binds the token to the + policy that currently holds it. Returns: The access token string. """ validate_access_token_id(id) - json = access_token_info_to_json(id, scope, auto_prefix_streams, expires_at) + json = access_token_info_to_json( + id, scope, auto_prefix_streams, expires_at, network_policy + ) response = await self._retrier( self._account_client.unary_request, "POST", @@ -560,6 +568,127 @@ async def revoke_access_token(self, id: str) -> None: self._account_client.unary_request, "DELETE", _access_token_path(id) ) + @fallible + async def list_network_policies( + self, + *, + prefix: str = "", + start_after: str = "", + limit: int = 1000, + ) -> types.Page[types.NetworkPolicyInfo]: + """List a page of network policies. + + Args: + prefix: Filter to policies whose slug starts with this prefix. + start_after: List policies whose slug is lexicographically after this value. + limit: Maximum number of policies to return per page. Capped at 1000. + + Returns: + A page of :class:`NetworkPolicyInfo`. + + Tip: + See :meth:`list_all_network_policies` for automatic pagination. + """ + params: dict[str, Any] = {} + if prefix: + params["prefix"] = prefix + if start_after: + params["start_after"] = start_after + if limit != 1000: + params["limit"] = limit + + response = await self._retrier( + self._account_client.unary_request, + "GET", + "/v1/network-policies", + params=params, + ) + data = response.json() + return types.Page( + items=[ + network_policy_info_from_json(info) for info in data["network_policies"] + ], + has_more=data["has_more"], + ) + + @fallible + async def list_all_network_policies( + self, + *, + prefix: str = "", + start_after: str = "", + ) -> AsyncIterator[types.NetworkPolicyInfo]: + """List all network policies, paginating automatically. + + Args: + prefix: Filter to policies whose slug starts with this prefix. + start_after: List policies whose slug is lexicographically after this value. + + Yields: + :class:`NetworkPolicyInfo` for each policy. + """ + while True: + page = await self.list_network_policies( + prefix=prefix, start_after=start_after + ) + for info in page.items: + yield info + if not page.has_more or not page.items: + break + start_after = page.items[-1].slug + + @fallible + async def create_network_policy( + self, + slug: str, + *, + policy: types.NetworkPolicy, + ) -> types.NetworkPolicyInfo: + """Create a network policy. + + A network policy restricts where an access token may be used from. Bind one + when issuing a token with :meth:`issue_access_token`. + + Args: + slug: Slug, unique to the account. Up to 96 characters of letters, + digits, ``-`` and ``_``. + policy: The restriction. Policies are immutable; create a new one to + change it. + + Returns: + Information about the created policy. + """ + response = await self._retrier( + self._account_client.unary_request, + "POST", + "/v1/network-policies", + json={"slug": slug, "policy": network_policy_to_json(policy)}, + ) + return network_policy_info_from_json(response.json()) + + @fallible + async def get_network_policy(self, id: str) -> types.NetworkPolicyInfo: + """Get a network policy. + + Args: + id: Slug, or full ``.`` reference. + """ + response = await self._retrier( + self._account_client.unary_request, "GET", _network_policy_path(id) + ) + return network_policy_info_from_json(response.json()) + + @fallible + async def delete_network_policy(self, id: str) -> None: + """Delete a network policy. It must not be bound to any access token. + + Args: + id: Slug, or full ``.`` reference. + """ + await self._retrier( + self._account_client.unary_request, "DELETE", _network_policy_path(id) + ) + @fallible async def account_metrics( self, @@ -1296,6 +1425,10 @@ def _access_token_path(id: str) -> str: return f"/v1/access-tokens/{_encode_path_segment(id)}" +def _network_policy_path(id: str) -> str: + return f"/v1/network-policies/{_encode_path_segment(id)}" + + def _metrics_params( set_value: str, start: int | None, diff --git a/src/s2_sdk/_types.py b/src/s2_sdk/_types.py index e43a9b7..72ba471 100644 --- a/src/s2_sdk/_types.py +++ b/src/s2_sdk/_types.py @@ -686,6 +686,57 @@ class AccessTokenInfo: auto_prefix_streams: bool """Whether to automatically prefix stream names during creation and strip the prefix during listing.""" + network_policy: str | None = None + """Full reference, ``.``, of the network policy the token is restricted by, if any.""" + + +@dataclass(slots=True) +class PublicNetCidrs: + """Source addresses a token may be used from over the public path.""" + + cidrs: list[str] + """IP networks in CIDR notation, e.g. ``203.0.113.0/24``. Between 1 and 32.""" + + +@dataclass(slots=True) +class AwsPrivateNetPolicy: + """AWS VPC endpoints a token may be used through.""" + + vpce_ids: list[str] + """VPC endpoint IDs. Between 1 and 32.""" + + +@dataclass(slots=True) +class NetworkPolicy: + """Restriction a network policy applies to the access tokens bound to it. + + At least one of ``public_net`` and ``private_net`` must be set. A path without + one is closed. + """ + + public_net: PublicNetCidrs | Unknown | None = None + """Governs requests arriving over the public path.""" + + private_net: AwsPrivateNetPolicy | Unknown | None = None + """Governs requests arriving through a private network.""" + + +@dataclass(slots=True) +class NetworkPolicyInfo: + """Network policy information.""" + + id: str + """Full reference, ``.``, which access tokens are bound to.""" + + slug: str + """Slug chosen at creation.""" + + created_at: datetime + """Creation time.""" + + policy: NetworkPolicy + """The restriction.""" + @dataclass(slots=True) class Scalar: diff --git a/tests/test_account_ops.py b/tests/test_account_ops.py index 1574092..6b3f656 100644 --- a/tests/test_account_ops.py +++ b/tests/test_account_ops.py @@ -8,10 +8,12 @@ AccessTokenScope, BasinConfig, EnsureStatus, + NetworkPolicy, Operation, OperationGroupPermissions, Permission, PrefixMatch, + PublicNetCidrs, S2Basin, S2ServerError, StreamConfig, @@ -318,6 +320,40 @@ async def test_issue_access_token_with_auto_prefix(self, s2: S2, token_id: str): finally: await s2.revoke_access_token(token_id) + # s2-lite does not implement network policies; its CI run excludes this marker. + @pytest.mark.access_tokens + async def test_network_policy_restricts_access_token(self, s2: S2, token_id: str): + slug = f"policy-{token_id}" + policy = NetworkPolicy(public_net=PublicNetCidrs(["203.0.113.0/24"])) + created = await s2.create_network_policy(slug, policy=policy) + + try: + assert created.slug == slug + assert created.policy == policy + assert await s2.get_network_policy(slug) == created + assert [p async for p in s2.list_all_network_policies(prefix=slug)] == [ + created + ] + + token = await s2.issue_access_token( + id=token_id, + scope=AccessTokenScope(ops=[Operation.LIST_BASINS]), + network_policy=slug, + ) + try: + page = await s2.list_access_tokens(prefix=token_id) + assert page.items[0].network_policy == created.id + + # This client is outside the policy's documentation-only range. + async with S2(token, endpoints=s2._endpoints) as restricted: + with pytest.raises(S2ServerError) as exc_info: + await restricted.list_basins() + assert exc_info.value.status_code == 403 + finally: + await s2.revoke_access_token(token_id) + finally: + await s2.delete_network_policy(slug) + async def test_get_basin_config(self, s2: S2, basin: S2Basin): config = await s2.get_basin_config(basin.name) assert isinstance(config, BasinConfig) diff --git a/tests/test_mappers.py b/tests/test_mappers.py index 9ea556a..3b85527 100644 --- a/tests/test_mappers.py +++ b/tests/test_mappers.py @@ -1,5 +1,9 @@ from s2_sdk import Operation, Unknown -from s2_sdk._mappers import access_token_info_from_json, access_token_info_to_json +from s2_sdk._mappers import ( + access_token_info_from_json, + access_token_info_to_json, + network_policy_info_from_json, +) def test_unknown_values_survive_parsing(): @@ -18,3 +22,15 @@ def test_unknown_values_survive_parsing(): # An unknown operation is sent back by name; the service decides. body = access_token_info_to_json(info.id, info.scope, False, None) assert body["scope"]["ops"] == ["read", "some-future-op"] + policy = network_policy_info_from_json( + { + "id": "p.abc", + "slug": "p", + "created_at": "2026-01-01T00:00:00Z", + "policy": { + "public_net": {"some-future-kind": {}}, + "private_net": {"aws": {"vpce_ids": ["vpce-0123456789abcdef0"]}}, + }, + } + ).policy + assert policy.public_net == Unknown("some-future-kind") From 19589138df637cd2a0aa2ccd4a43560caad2467c Mon Sep 17 00:00:00 2001 From: Stephen Balogh Date: Wed, 18 Nov 2026 23:12:05 +0000 Subject: [PATCH 2/3] feat: network policy operations Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/s2_sdk/_types.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/s2_sdk/_types.py b/src/s2_sdk/_types.py index 72ba471..02941dc 100644 --- a/src/s2_sdk/_types.py +++ b/src/s2_sdk/_types.py @@ -452,6 +452,10 @@ class Operation(_OpenEnum): LIST_LOCATIONS = "list-locations" GET_DEFAULT_LOCATION = "get-default-location" SET_DEFAULT_LOCATION = "set-default-location" + LIST_NETWORK_POLICIES = "list-network-policies" + CREATE_NETWORK_POLICY = "create-network-policy" + GET_NETWORK_POLICY = "get-network-policy" + DELETE_NETWORK_POLICY = "delete-network-policy" class Permission(_DocEnum): From 44add511cefe37ca8fad9ee5e64244676d653fbe Mon Sep 17 00:00:00 2001 From: Stephen Balogh Date: Wed, 18 Nov 2026 23:13:47 +0000 Subject: [PATCH 3/3] test: do not compare created_at across create and get Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- s2-specs | 2 +- tests/test_account_ops.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/s2-specs b/s2-specs index 60dfbe3..0fb08b4 160000 --- a/s2-specs +++ b/s2-specs @@ -1 +1 @@ -Subproject commit 60dfbe312609572710a5c539a02a393e7ee37a2e +Subproject commit 0fb08b4f8f2c4a889d4a6c69b64a4d0a9be2233a diff --git a/tests/test_account_ops.py b/tests/test_account_ops.py index 6b3f656..0188e67 100644 --- a/tests/test_account_ops.py +++ b/tests/test_account_ops.py @@ -330,9 +330,10 @@ async def test_network_policy_restricts_access_token(self, s2: S2, token_id: str try: assert created.slug == slug assert created.policy == policy - assert await s2.get_network_policy(slug) == created + fetched = await s2.get_network_policy(slug) + assert (fetched.id, fetched.policy) == (created.id, policy) assert [p async for p in s2.list_all_network_policies(prefix=slug)] == [ - created + fetched ] token = await s2.issue_access_token(