Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/source/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions src/s2_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
AppendInput,
AppendRetryPolicy,
AwsPrivateNet,
AwsPrivateNetPolicy,
BasinConfig,
BasinInfo,
BasinMetricSet,
Expand All @@ -42,11 +43,14 @@
Label,
LocationInfo,
MetricUnit,
NetworkPolicy,
NetworkPolicyInfo,
Operation,
OperationGroupPermissions,
Page,
Permission,
PrefixMatch,
PublicNetCidrs,
ReadBatch,
ReadLimit,
Record,
Expand Down Expand Up @@ -122,6 +126,10 @@
"OperationGroupPermissions",
"AccessTokenScope",
"AccessTokenInfo",
"PublicNetCidrs",
"AwsPrivateNetPolicy",
"NetworkPolicy",
"NetworkPolicyInfo",
"MetricUnit",
"TimeseriesInterval",
"AccountMetricSet",
Expand Down
56 changes: 56 additions & 0 deletions src/s2_sdk/_mappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
AppendAck,
AppendInput,
AwsPrivateNet,
AwsPrivateNetPolicy,
BasinConfig,
BasinInfo,
Encryption,
Expand All @@ -22,10 +23,13 @@
Label,
LocationInfo,
MetricUnit,
NetworkPolicy,
NetworkPolicyInfo,
Operation,
OperationGroupPermissions,
Permission,
PrefixMatch,
PublicNetCidrs,
ReadBatch,
ReadLimit,
Record,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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")),
),
)


Expand Down
135 changes: 134 additions & 1 deletion src/s2_sdk/_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.

Expand All @@ -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 ``<slug>.<nonce>`` 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",
Expand Down Expand Up @@ -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 ``<slug>.<nonce>`` 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 ``<slug>.<nonce>`` reference.
"""
await self._retrier(
self._account_client.unary_request, "DELETE", _network_policy_path(id)
)

@fallible
async def account_metrics(
self,
Expand Down Expand Up @@ -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,
Expand Down
55 changes: 55 additions & 0 deletions src/s2_sdk/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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, ``<slug>.<nonce>``, 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, ``<slug>.<nonce>``, 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:
Expand Down
Loading
Loading