diff --git a/docs/source/api-reference.md b/docs/source/api-reference.md index 8dd8781..8a48296 100644 --- a/docs/source/api-reference.md +++ b/docs/source/api-reference.md @@ -147,6 +147,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 0247f3d..d65769a 100644 --- a/src/s2_sdk/__init__.py +++ b/src/s2_sdk/__init__.py @@ -25,6 +25,7 @@ AppendInput, AppendRetryPolicy, AwsPrivateNet, + AwsPrivateNetPolicy, BasinConfig, BasinInfo, BasinMetricSet, @@ -42,11 +43,14 @@ Label, LocationInfo, MetricUnit, + NetworkPolicy, + NetworkPolicyInfo, Operation, OperationGroupPermissions, Page, Permission, PrefixMatch, + PublicNetCidrs, ReadBatch, ReadLimit, Record, @@ -122,6 +126,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 7a0b82d..4e48bbb 100644 --- a/src/s2_sdk/_mappers.py +++ b/src/s2_sdk/_mappers.py @@ -11,6 +11,7 @@ AppendAck, AppendInput, AwsPrivateNet, + AwsPrivateNetPolicy, BasinConfig, BasinInfo, Encryption, @@ -22,10 +23,13 @@ Label, LocationInfo, MetricUnit, + NetworkPolicy, + NetworkPolicyInfo, Operation, OperationGroupPermissions, Permission, PrefixMatch, + PublicNetCidrs, ReadBatch, ReadLimit, Record, @@ -295,6 +299,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: @@ -322,6 +327,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 @@ -352,6 +359,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 422f36a..5e46ae0 100644 --- a/src/s2_sdk/_types.py +++ b/src/s2_sdk/_types.py @@ -468,6 +468,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): @@ -702,6 +706,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..0188e67 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,41 @@ 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 + 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)] == [ + fetched + ] + + 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 cef454f..aaa48de 100644 --- a/tests/test_mappers.py +++ b/tests/test_mappers.py @@ -3,6 +3,7 @@ access_token_info_from_json, access_token_info_to_json, location_info_from_json, + network_policy_info_from_json, ) @@ -22,6 +23,18 @@ 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") location = location_info_from_json( { "name": "gcp:us-east4",