Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(api): call tenant UTM and network access group APIs through the generated client (#45144)
yyhd597152b2f27
diff --git a/api/dev/generate_billing_client.py b/api/dev/generate_billing_client.pyindex 6017cfe8835..427e3f434bd 100644--- a/api/dev/generate_billing_client.py+++ b/api/dev/generate_billing_client.py@@ -45,7 +45,7 @@ GENERATOR = "api/dev/generate_billing_client.py"logger = logging.getLogger("generate_billing_client")type Service = Literal["billing", "saas"]-type UpstreamName = Literal["BILLING", "BILLING_QUOTA", "SAAS"]+type UpstreamName = Literal["BILLING", "BILLING_QUOTA", "SAAS", "NETWORK_ACCESS"]type JsonObject = dict[str, Any]SERVICES: tuple[Service, ...] = ("billing", "saas")@@ -54,6 +54,7 @@ SCHEMA_PREFIXES: dict[Service, str] = {"billing": "dify.saas.api.billing.", "saaPATH_VERSION_PREFIX = "/v1"SNAPSHOT_COMMIT_KEY = "x-dify-saas-commit"HTTP_METHODS = ("get", "post", "put", "delete", "patch")+LINE_LENGTH = 120BASE_MODEL_ATTRIBUTES = frozenset(dir(BaseModel))@@ -93,6 +94,18 @@ ALLOWED_OPERATIONS: dict[Service, tuple[AllowedOperation, ...]] = {AllowedOperation("POST", "/v1/account/delete-feedback", "SAAS"),AllowedOperation("GET", "/v1/notifications/active", "SAAS"),AllowedOperation("POST", "/v1/notifications/{notificationId}/dismiss", "SAAS"),+ AllowedOperation("POST", "/v1/tenant_utms", "SAAS"),+ AllowedOperation("GET", "/v1/tenants/{tenantId}/network-access-groups", "NETWORK_ACCESS"),+ AllowedOperation("POST", "/v1/tenants/{tenantId}/network-access-groups", "NETWORK_ACCESS"),+ AllowedOperation("GET", "/v1/tenants/{tenantId}/network-access-groups/{groupId}", "NETWORK_ACCESS"),+ AllowedOperation("PUT", "/v1/tenants/{tenantId}/network-access-groups/{groupId}", "NETWORK_ACCESS"),+ AllowedOperation("DELETE", "/v1/tenants/{tenantId}/network-access-groups/{groupId}", "NETWORK_ACCESS"),+ AllowedOperation("GET", "/v1/tenants/{tenantId}/apps/{appId}/network-access-group", "NETWORK_ACCESS"),+ AllowedOperation("PUT", "/v1/tenants/{tenantId}/apps/{appId}/network-access-group", "NETWORK_ACCESS"),+ AllowedOperation("GET", "/v1/tenants/{tenantId}/apps/{appId}/network-access-group/status", "NETWORK_ACCESS"),+ AllowedOperation(+ "DELETE", "/v1/tenants/{tenantId}/apps/{appId}/network-access-group-binding", "NETWORK_ACCESS"+ ),),}@@ -287,6 +300,8 @@ def python_type(schema: JsonObject, context: str) -> str:return f"Literal[{', '.join(json.dumps(value) for value in schema['enum'])}]"if schema_type == "integer" or (schema_type == "string" and schema.get("format") in {"int64", "uint64"}):return "int"+ if schema_type == "string" and schema.get("format") == "date-time":+ return "datetime"if schema_type == "string":return "str"if schema_type == "number":@@ -383,9 +398,12 @@ def render_operation(service: Service, allowed: AllowedOperation, operation: Jsoraise GenerationError(f"{context}: argument names collide")signature = f"def {function_name}({'*, ' + ', '.join(arguments) if arguments else ''}) -> {response}:"+ docstring = f' """{allowed.method} {allowed.path} ({operation["operationId"]})."""'+ if len(docstring) > LINE_LENGTH:+ docstring = f' """{allowed.method} {allowed.path}\n\n {operation["operationId"]}\n """'return [signature,- f' """{allowed.method} {allowed.path} ({operation["operationId"]})."""',+ docstring," return request(",f" Upstream.{allowed.upstream},",f" {json.dumps(allowed.method)},",@@ -410,6 +428,7 @@ def render_module(service: Service, snapshot: JsonObject) -> str:f"# Code generated by {GENERATOR} from {service}.openapi.json. DO NOT EDIT.",f"# dify-saas commit: {snapshot[SNAPSHOT_COMMIT_KEY]}","",+ "from datetime import datetime","from typing import Literal","","from pydantic import Field",diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.pyindex 289f0f34ccf..f55df0150ae 100644--- a/api/extensions/ext_application_services.py+++ b/api/extensions/ext_application_services.py@@ -796,11 +796,7 @@ def build_application_services(notifications=BillingNotificationGateway(),),network_access_groups=NetworkAccessGroupService(- control_plane=NetworkAccessGroupGateway(- base_url=dify_config.NETWORK_ACCESS_API_URL,- fallback_base_url=BillingService.base_url,- secret_key=BillingService.secret_key,- ),+ control_plane=NetworkAccessGroupGateway(),apps=SQLAlchemyNetworkAccessGroupAppRepository(session_factory=database_client),memberships=workspace_repository,entitlement=BillingNetworkAccessGroupEntitlementGateway(),diff --git a/api/services/billing_client/billing.openapi.json b/api/services/billing_client/billing.openapi.jsonindex bbfbbb5f7e0..01e528e6101 100644--- a/api/services/billing_client/billing.openapi.json+++ b/api/services/billing_client/billing.openapi.json@@ -4,7 +4,7 @@"title": "","version": "0.0.1"},- "x-dify-saas-commit": "a0b548cf3020d490a8b7fad21dfbb66b72fa0ed6",+ "x-dify-saas-commit": "16c5186fecc57e802bf69673f58093bf0dcb77c2","paths": {"/v1/subscription/info": {"get": {diff --git a/api/services/billing_client/billing.py b/api/services/billing_client/billing.pyindex 57b7b783e7c..f910945c592 100644--- a/api/services/billing_client/billing.py+++ b/api/services/billing_client/billing.py@@ -1,6 +1,7 @@# Code generated by api/dev/generate_billing_client.py from billing.openapi.json. DO NOT EDIT.-# dify-saas commit: a0b548cf3020d490a8b7fad21dfbb66b72fa0ed6+# dify-saas commit: 16c5186fecc57e802bf69673f58093bf0dcb77c2+from datetime import datetimefrom typing import Literalfrom services.billing_client.transport import BillingModel, Upstream, request@@ -118,9 +119,9 @@ class SubscriptionCleanupWhitelist(BillingModel):id: strtenant_id: strcontact: str- expired_at: str- created_at: str- updated_at: str+ expired_at: datetime+ created_at: datetime+ updated_at: datetimeclass ListSubscriptionCleanupWhitelistReply(BillingModel):diff --git a/api/services/billing_client/saas.openapi.json b/api/services/billing_client/saas.openapi.jsonindex f3d43ac714c..1a1245f6799 100644--- a/api/services/billing_client/saas.openapi.json+++ b/api/services/billing_client/saas.openapi.json@@ -4,7 +4,7 @@"title": "","version": "0.0.1"},- "x-dify-saas-commit": "a0b548cf3020d490a8b7fad21dfbb66b72fa0ed6",+ "x-dify-saas-commit": "16c5186fecc57e802bf69673f58093bf0dcb77c2","paths": {"/v1/account": {"delete": {@@ -165,6 +165,428 @@}}}+ },+ "/v1/tenant_utms": {+ "post": {+ "tags": [+ "Utm"+ ],+ "operationId": "Utm_RecordTenantUtm",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TenantUtmRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TenantUtmReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/tenants/{tenantId}/network-access-groups": {+ "get": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "operationId": "SaasNetworkAccessPolicy_ListNetworkAccessGroups",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "actorAccountId",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ListNetworkAccessGroupsReply"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "operationId": "SaasNetworkAccessPolicy_CreateNetworkAccessGroup",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateNetworkAccessGroupRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NetworkAccessGroupReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/tenants/{tenantId}/network-access-groups/{groupId}": {+ "get": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "operationId": "SaasNetworkAccessPolicy_GetNetworkAccessGroup",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "groupId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "actorAccountId",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NetworkAccessGroupReply"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "operationId": "SaasNetworkAccessPolicy_UpdateNetworkAccessGroup",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "groupId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateNetworkAccessGroupRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/NetworkAccessGroupReply"+ }+ }+ }+ }+ }+ },+ "delete": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "operationId": "SaasNetworkAccessPolicy_DeleteNetworkAccessGroup",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "groupId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "expectedVersion",+ "in": "query",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "actorAccountId",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DeleteNetworkAccessGroupReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/tenants/{tenantId}/apps/{appId}/network-access-group": {+ "get": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "operationId": "SaasNetworkAccessPolicy_GetAppNetworkAccessGroup",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "appId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "actorAccountId",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetAppNetworkAccessGroupReply"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "operationId": "SaasNetworkAccessPolicy_PutAppNetworkAccessGroup",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "appId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PutAppNetworkAccessGroupRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PutAppNetworkAccessGroupReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/tenants/{tenantId}/apps/{appId}/network-access-group/status": {+ "get": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "description": "Entry status is available to normal members without exposing policy details.",+ "operationId": "SaasNetworkAccessPolicy_GetAppNetworkAccessGroupStatus",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "appId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "actorAccountId",+ "in": "query",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetAppNetworkAccessGroupStatusReply"+ }+ }+ }+ }+ }+ }+ },+ "/v1/tenants/{tenantId}/apps/{appId}/network-access-group-binding": {+ "delete": {+ "tags": [+ "SaasNetworkAccessPolicy"+ ],+ "description": "CleanupAppNetworkAccessGroupBinding is an internal App lifecycle hook.\n It deliberately has no actor field: callers are authenticated by the\n internal HTTP secret and this operation must not be exposed as a member\n or account deletion side effect.",+ "operationId": "SaasNetworkAccessPolicy_CleanupAppNetworkAccessGroupBinding",+ "parameters": [+ {+ "name": "tenantId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "appId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CleanupAppNetworkAccessGroupBindingReply"+ }+ }+ }+ }+ }+ }}},"components": {@@ -196,6 +618,59 @@"feedback"]},+ "AppNetworkAccessGroupBinding": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "tenantId": {+ "type": "string"+ },+ "appId": {+ "type": "string"+ },+ "groupId": {+ "nullable": true,+ "type": "string"+ },+ "version": {+ "type": "string",+ "format": "int64"+ },+ "updatedByAccountId": {+ "type": "string"+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ },+ "enabled": {+ "type": "boolean"+ },+ "accessPoints": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "id",+ "tenantId",+ "appId",+ "version",+ "updatedByAccountId",+ "createdAt",+ "updatedAt",+ "enabled",+ "accessPoints"+ ]+ },"CheckAccountInFreezeReply": {"type": "object","properties": {@@ -217,6 +692,52 @@"freezeType"]},+ "CleanupAppNetworkAccessGroupBindingReply": {+ "type": "object",+ "properties": {+ "deleted": {+ "type": "boolean"+ }+ },+ "required": [+ "deleted"+ ]+ },+ "CreateNetworkAccessGroupRequest": {+ "type": "object",+ "properties": {+ "tenantId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "mode": {+ "type": "string",+ "description": "Deprecated and ignored. Kept only for wire compatibility with clients\n built against the first reusable-group draft."+ },+ "allowedCidrs": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "actorAccountId": {+ "type": "string"+ }+ },+ "required": [+ "tenantId",+ "name",+ "description",+ "mode",+ "allowedCidrs",+ "actorAccountId"+ ]+ },"DeleteAccountReply": {"type": "object","properties": {@@ -228,6 +749,17 @@"message"]},+ "DeleteNetworkAccessGroupReply": {+ "type": "object",+ "properties": {+ "deleted": {+ "type": "boolean"+ }+ },+ "required": [+ "deleted"+ ]+ },"DismissNotificationReply": {"type": "object","properties": {@@ -274,6 +806,67 @@"notifications"]},+ "GetAppNetworkAccessGroupReply": {+ "type": "object",+ "properties": {+ "tenantId": {+ "type": "string"+ },+ "appId": {+ "type": "string"+ },+ "entitled": {+ "type": "boolean"+ },+ "binding": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AppNetworkAccessGroupBinding"+ }+ ],+ "nullable": true+ },+ "effectiveEnabled": {+ "type": "boolean",+ "description": "Effective runtime state; does not replace the saved binding.enabled value."+ }+ },+ "required": [+ "tenantId",+ "appId",+ "entitled",+ "binding",+ "effectiveEnabled"+ ]+ },+ "GetAppNetworkAccessGroupStatusReply": {+ "type": "object",+ "properties": {+ "entitled": {+ "type": "boolean"+ },+ "configured": {+ "type": "boolean"+ },+ "enabled": {+ "type": "boolean",+ "description": "Preserve the saved switch independently of plan entitlement."+ },+ "accessPoints": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "The Console BFF filters these scopes against the app's current capabilities."+ }+ },+ "required": [+ "entitled",+ "configured",+ "enabled",+ "accessPoints"+ ]+ },"LangContent": {"type": "object","properties": {@@ -303,6 +896,116 @@"titlePicUrl"]},+ "ListNetworkAccessGroupsReply": {+ "type": "object",+ "properties": {+ "tenantId": {+ "type": "string"+ },+ "entitled": {+ "type": "boolean"+ },+ "groups": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/NetworkAccessGroup"+ }+ }+ },+ "required": [+ "tenantId",+ "entitled",+ "groups"+ ]+ },+ "NetworkAccessGroup": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "tenantId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "mode": {+ "type": "string",+ "description": "Deprecated compatibility field. User-managed policies are always enforced;\n rollout shadow/off behavior belongs to Gateway configuration."+ },+ "allowedCidrs": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "version": {+ "type": "string",+ "format": "int64"+ },+ "updatedByAccountId": {+ "type": "string"+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ },+ "usedByCount": {+ "type": "string",+ "format": "int64"+ },+ "usedByAppIds": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "enforcingCount": {+ "type": "string",+ "description": "Number of saved references which are actively enforcing for an entitled\n tenant. Disabled bindings and bindings without access points remain in\n used_by_count but do not contribute here.",+ "format": "int64"+ }+ },+ "required": [+ "id",+ "tenantId",+ "name",+ "description",+ "mode",+ "allowedCidrs",+ "version",+ "updatedByAccountId",+ "createdAt",+ "updatedAt",+ "usedByCount",+ "usedByAppIds",+ "enforcingCount"+ ]+ },+ "NetworkAccessGroupReply": {+ "type": "object",+ "properties": {+ "group": {+ "allOf": [+ {+ "$ref": "#/components/schemas/NetworkAccessGroup"+ }+ ],+ "nullable": true+ }+ },+ "required": [+ "group"+ ]+ },"NotificationPayload": {"type": "object","properties": {@@ -334,6 +1037,153 @@"frequency","isGlobal"]+ },+ "PutAppNetworkAccessGroupReply": {+ "type": "object",+ "properties": {+ "binding": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AppNetworkAccessGroupBinding"+ }+ ],+ "nullable": true+ },+ "effectiveEnabled": {+ "type": "boolean",+ "description": "Effective runtime state; does not replace the saved binding.enabled value."+ }+ },+ "required": [+ "binding",+ "effectiveEnabled"+ ]+ },+ "PutAppNetworkAccessGroupRequest": {+ "type": "object",+ "properties": {+ "tenantId": {+ "type": "string"+ },+ "appId": {+ "type": "string"+ },+ "groupId": {+ "nullable": true,+ "type": "string"+ },+ "expectedVersion": {+ "type": "string",+ "format": "int64"+ },+ "actorAccountId": {+ "type": "string"+ },+ "enabled": {+ "nullable": true,+ "type": "boolean",+ "description": "Optional distinguishes an explicit disable from a legacy caller that\n predates per-app access-point settings."+ },+ "accessPoints": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "tenantId",+ "appId",+ "expectedVersion",+ "actorAccountId",+ "accessPoints"+ ]+ },+ "TenantUtmReply": {+ "type": "object",+ "properties": {+ "result": {+ "type": "string"+ }+ },+ "required": [+ "result"+ ]+ },+ "TenantUtmRequest": {+ "type": "object",+ "properties": {+ "tenantId": {+ "type": "string"+ },+ "utmSource": {+ "type": "string"+ },+ "utmMedium": {+ "type": "string"+ },+ "utmCampaign": {+ "type": "string"+ },+ "utmContent": {+ "type": "string"+ },+ "utmTerm": {+ "type": "string"+ }+ },+ "required": [+ "tenantId",+ "utmSource",+ "utmMedium",+ "utmCampaign",+ "utmContent",+ "utmTerm"+ ]+ },+ "UpdateNetworkAccessGroupRequest": {+ "type": "object",+ "properties": {+ "tenantId": {+ "type": "string"+ },+ "groupId": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "mode": {+ "type": "string",+ "description": "Deprecated and ignored. Kept only for wire compatibility."+ },+ "allowedCidrs": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "expectedVersion": {+ "type": "string",+ "format": "int64"+ },+ "actorAccountId": {+ "type": "string"+ }+ },+ "required": [+ "tenantId",+ "groupId",+ "name",+ "description",+ "mode",+ "allowedCidrs",+ "expectedVersion",+ "actorAccountId"+ ]}}}diff --git a/api/services/billing_client/saas.py b/api/services/billing_client/saas.pyindex 2a4ba1c58a2..20d716090dd 100644--- a/api/services/billing_client/saas.py+++ b/api/services/billing_client/saas.py@@ -1,6 +1,7 @@# Code generated by api/dev/generate_billing_client.py from saas.openapi.json. DO NOT EDIT.-# dify-saas commit: a0b548cf3020d490a8b7fad21dfbb66b72fa0ed6+# dify-saas commit: 16c5186fecc57e802bf69673f58093bf0dcb77c2+from datetime import datetimefrom typing import Literalfrom pydantic import Field@@ -17,15 +18,45 @@ class AddDeleteFeedbackRequest(BillingModel):feedback: str+class AppNetworkAccessGroupBinding(BillingModel):+ id: str+ tenant_id: str = Field(alias="tenantId")+ app_id: str = Field(alias="appId")+ group_id: str | None = Field(None, alias="groupId")+ version: int+ updated_by_account_id: str = Field(alias="updatedByAccountId")+ created_at: datetime = Field(alias="createdAt")+ updated_at: datetime = Field(alias="updatedAt")+ enabled: bool+ access_points: list[str] = Field(alias="accessPoints")++class CheckAccountInFreezeReply(BillingModel):data: boolfreeze_type: Literal["", "freeze", "email_domain_suspended"] = Field(alias="freezeType")+class CleanupAppNetworkAccessGroupBindingReply(BillingModel):+ deleted: bool+++class CreateNetworkAccessGroupRequest(BillingModel):+ tenant_id: str = Field(alias="tenantId")+ name: str+ description: str+ mode: str+ allowed_cidrs: list[str] = Field(alias="allowedCidrs")+ actor_account_id: str = Field(alias="actorAccountId")++class DeleteAccountReply(BillingModel):message: str+class DeleteNetworkAccessGroupReply(BillingModel):+ deleted: bool++class DismissNotificationReply(BillingModel):success: bool@@ -55,6 +86,86 @@ class GetAccountNotificationReply(BillingModel):notifications: list[NotificationPayload]+class GetAppNetworkAccessGroupReply(BillingModel):+ tenant_id: str = Field(alias="tenantId")+ app_id: str = Field(alias="appId")+ entitled: bool+ binding: AppNetworkAccessGroupBinding | None+ effective_enabled: bool = Field(alias="effectiveEnabled")+++class GetAppNetworkAccessGroupStatusReply(BillingModel):+ entitled: bool+ configured: bool+ enabled: bool+ access_points: list[str] = Field(alias="accessPoints")+++class NetworkAccessGroup(BillingModel):+ id: str+ tenant_id: str = Field(alias="tenantId")+ name: str+ description: str+ mode: str+ allowed_cidrs: list[str] = Field(alias="allowedCidrs")+ version: int+ updated_by_account_id: str = Field(alias="updatedByAccountId")+ created_at: datetime = Field(alias="createdAt")+ updated_at: datetime = Field(alias="updatedAt")+ used_by_count: int = Field(alias="usedByCount")+ used_by_app_ids: list[str] = Field(alias="usedByAppIds")+ enforcing_count: int = Field(alias="enforcingCount")+++class ListNetworkAccessGroupsReply(BillingModel):+ tenant_id: str = Field(alias="tenantId")+ entitled: bool+ groups: list[NetworkAccessGroup]+++class NetworkAccessGroupReply(BillingModel):+ group: NetworkAccessGroup | None+++class PutAppNetworkAccessGroupReply(BillingModel):+ binding: AppNetworkAccessGroupBinding | None+ effective_enabled: bool = Field(alias="effectiveEnabled")+++class PutAppNetworkAccessGroupRequest(BillingModel):+ tenant_id: str = Field(alias="tenantId")+ app_id: str = Field(alias="appId")+ group_id: str | None = Field(None, alias="groupId")+ expected_version: int = Field(alias="expectedVersion")+ actor_account_id: str = Field(alias="actorAccountId")+ enabled: bool | None = None+ access_points: list[str] = Field(alias="accessPoints")+++class TenantUtmReply(BillingModel):+ result: str+++class TenantUtmRequest(BillingModel):+ tenant_id: str = Field(alias="tenantId")+ utm_source: str = Field(alias="utmSource")+ utm_medium: str = Field(alias="utmMedium")+ utm_campaign: str = Field(alias="utmCampaign")+ utm_content: str = Field(alias="utmContent")+ utm_term: str = Field(alias="utmTerm")+++class UpdateNetworkAccessGroupRequest(BillingModel):+ tenant_id: str = Field(alias="tenantId")+ group_id: str = Field(alias="groupId")+ name: str+ description: str+ mode: str+ allowed_cidrs: list[str] = Field(alias="allowedCidrs")+ expected_version: int = Field(alias="expectedVersion")+ actor_account_id: str = Field(alias="actorAccountId")++def account_delete_account(*, account_id: str) -> DeleteAccountReply:"""DELETE /v1/account (Account_DeleteAccount)."""return request(@@ -120,3 +231,166 @@ def notification_dismiss_notification(params={},body=body,)+++def utm_record_tenant_utm(*, body: TenantUtmRequest) -> TenantUtmReply:+ """POST /v1/tenant_utms (Utm_RecordTenantUtm)."""+ return request(+ Upstream.SAAS,+ "POST",+ "/tenant_utms",+ response_model=TenantUtmReply,+ path_params={},+ params={},+ body=body,+ )+++def network_access_policy_list_network_access_groups(+ *, tenant_id: str, actor_account_id: str+) -> ListNetworkAccessGroupsReply:+ """GET /v1/tenants/{tenantId}/network-access-groups (SaasNetworkAccessPolicy_ListNetworkAccessGroups)."""+ return request(+ Upstream.NETWORK_ACCESS,+ "GET",+ "/tenants/{tenant_id}/network-access-groups",+ response_model=ListNetworkAccessGroupsReply,+ path_params={"tenant_id": tenant_id},+ params={"actorAccountId": actor_account_id},+ body=None,+ )+++def network_access_policy_create_network_access_group(+ *, tenant_id: str, body: CreateNetworkAccessGroupRequest+) -> NetworkAccessGroupReply:+ """POST /v1/tenants/{tenantId}/network-access-groups (SaasNetworkAccessPolicy_CreateNetworkAccessGroup)."""+ return request(+ Upstream.NETWORK_ACCESS,+ "POST",+ "/tenants/{tenant_id}/network-access-groups",+ response_model=NetworkAccessGroupReply,+ path_params={"tenant_id": tenant_id},+ params={},+ body=body,+ )+++def network_access_policy_get_network_access_group(+ *, tenant_id: str, group_id: str, actor_account_id: str+) -> NetworkAccessGroupReply:+ """GET /v1/tenants/{tenantId}/network-access-groups/{groupId} (SaasNetworkAccessPolicy_GetNetworkAccessGroup)."""+ return request(+ Upstream.NETWORK_ACCESS,+ "GET",+ "/tenants/{tenant_id}/network-access-groups/{group_id}",+ response_model=NetworkAccessGroupReply,+ path_params={"tenant_id": tenant_id, "group_id": group_id},+ params={"actorAccountId": actor_account_id},+ body=None,+ )+++def network_access_policy_update_network_access_group(+ *, tenant_id: str, group_id: str, body: UpdateNetworkAccessGroupRequest+) -> NetworkAccessGroupReply:+ """PUT /v1/tenants/{tenantId}/network-access-groups/{groupId} (SaasNetworkAccessPolicy_UpdateNetworkAccessGroup)."""+ return request(+ Upstream.NETWORK_ACCESS,+ "PUT",+ "/tenants/{tenant_id}/network-access-groups/{group_id}",+ response_model=NetworkAccessGroupReply,+ path_params={"tenant_id": tenant_id, "group_id": group_id},+ params={},+ body=body,+ )+++def network_access_policy_delete_network_access_group(+ *, tenant_id: str, group_id: str, expected_version: str, actor_account_id: str+) -> DeleteNetworkAccessGroupReply:+ """DELETE /v1/tenants/{tenantId}/network-access-groups/{groupId}++ SaasNetworkAccessPolicy_DeleteNetworkAccessGroup+ """+ return request(+ Upstream.NETWORK_ACCESS,+ "DELETE",+ "/tenants/{tenant_id}/network-access-groups/{group_id}",+ response_model=DeleteNetworkAccessGroupReply,+ path_params={"tenant_id": tenant_id, "group_id": group_id},+ params={"expectedVersion": expected_version, "actorAccountId": actor_account_id},+ body=None,+ )+++def network_access_policy_get_app_network_access_group(+ *, tenant_id: str, app_id: str, actor_account_id: str+) -> GetAppNetworkAccessGroupReply:+ """GET /v1/tenants/{tenantId}/apps/{appId}/network-access-group++ SaasNetworkAccessPolicy_GetAppNetworkAccessGroup+ """+ return request(+ Upstream.NETWORK_ACCESS,+ "GET",+ "/tenants/{tenant_id}/apps/{app_id}/network-access-group",+ response_model=GetAppNetworkAccessGroupReply,+ path_params={"tenant_id": tenant_id, "app_id": app_id},+ params={"actorAccountId": actor_account_id},+ body=None,+ )+++def network_access_policy_put_app_network_access_group(+ *, tenant_id: str, app_id: str, body: PutAppNetworkAccessGroupRequest+) -> PutAppNetworkAccessGroupReply:+ """PUT /v1/tenants/{tenantId}/apps/{appId}/network-access-group++ SaasNetworkAccessPolicy_PutAppNetworkAccessGroup+ """+ return request(+ Upstream.NETWORK_ACCESS,+ "PUT",+ "/tenants/{tenant_id}/apps/{app_id}/network-access-group",+ response_model=PutAppNetworkAccessGroupReply,+ path_params={"tenant_id": tenant_id, "app_id": app_id},+ params={},+ body=body,+ )+++def network_access_policy_get_app_network_access_group_status(+ *, tenant_id: str, app_id: str, actor_account_id: str+) -> GetAppNetworkAccessGroupStatusReply:+ """GET /v1/tenants/{tenantId}/apps/{appId}/network-access-group/status++ SaasNetworkAccessPolicy_GetAppNetworkAccessGroupStatus+ """+ return request(+ Upstream.NETWORK_ACCESS,+ "GET",+ "/tenants/{tenant_id}/apps/{app_id}/network-access-group/status",+ response_model=GetAppNetworkAccessGroupStatusReply,+ path_params={"tenant_id": tenant_id, "app_id": app_id},+ params={"actorAccountId": actor_account_id},+ body=None,+ )+++def network_access_policy_cleanup_app_network_access_group_binding(+ *, tenant_id: str, app_id: str+) -> CleanupAppNetworkAccessGroupBindingReply:+ """DELETE /v1/tenants/{tenantId}/apps/{appId}/network-access-group-binding++ SaasNetworkAccessPolicy_CleanupAppNetworkAccessGroupBinding+ """+ return request(+ Upstream.NETWORK_ACCESS,+ "DELETE",+ "/tenants/{tenant_id}/apps/{app_id}/network-access-group-binding",+ response_model=CleanupAppNetworkAccessGroupBindingReply,+ path_params={"tenant_id": tenant_id, "app_id": app_id},+ params={},+ body=None,+ )diff --git a/api/services/billing_client/transport.py b/api/services/billing_client/transport.pyindex f7c08c930d3..4cc485cf7f7 100644--- a/api/services/billing_client/transport.py+++ b/api/services/billing_client/transport.py@@ -3,7 +3,8 @@Reuses the pooled client, auth header, and connection retry of `services.billing_service`.Network failures, timeouts, throttling, and 5xx raise `BillingUpstreamUnavailableError`;any other non-200 status or an enforced response that fails model validation raises-`BillingUpstreamInvalidResponseError`.+`BillingUpstreamInvalidResponseError`. For a non-200 status, the error carries the status+code and the parsed Kratos error body, so callers can branch on its `reason`.Response validation is observed before it is enforced. For a path not in`ENFORCED_RESPONSE_PATHS`, a body that fails validation is logged with `logger.exception`@@ -28,8 +29,13 @@ import httpxfrom pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationErrorfrom tenacity import retry, retry_if_exception_type, stop_before_delay, wait_fixed+from configs import dify_configfrom core.helper.http_client_pooling import get_pooled_http_client-from services.errors.billing import BillingUpstreamInvalidResponseError, BillingUpstreamUnavailableError+from services.errors.billing import (+ BillingUpstreamInvalidResponseError,+ BillingUpstreamUnavailableError,+ UpstreamErrorBody,+)logger = logging.getLogger(__name__)@@ -49,6 +55,12 @@ ENFORCED_RESPONSE_PATHS: frozenset[str] = frozenset("/quota/release","/quota/balance","/quota/consume-capped",+ # Network access replies already required validation and gate access control.+ "/tenants/{tenant_id}/network-access-groups",+ "/tenants/{tenant_id}/network-access-groups/{group_id}",+ "/tenants/{tenant_id}/apps/{app_id}/network-access-group",+ "/tenants/{tenant_id}/apps/{app_id}/network-access-group/status",+ "/tenants/{tenant_id}/apps/{app_id}/network-access-group-binding",})@@ -70,6 +82,7 @@ class Upstream(StrEnum):BILLING = "billing"BILLING_QUOTA = "billing_quota"SAAS = "saas"+ NETWORK_ACCESS = "network_access"class BillingModel(BaseModel):@@ -82,6 +95,8 @@ def _base_url(upstream: Upstream) -> str:billing_url = os.environ.get("BILLING_API_URL", "BILLING_API_URL")if upstream == Upstream.BILLING_QUOTA:return os.environ.get("BILLING_QUOTA_API_URL") or billing_url+ if upstream == Upstream.NETWORK_ACCESS:+ return (dify_config.NETWORK_ACCESS_API_URL.strip() or billing_url).rstrip("/")return billing_url@@ -119,9 +134,10 @@ def request[ResponseT: BillingModel](if response.status_code != httpx.codes.OK:message = f"{method} {path} returned {response.status_code}"- if response.status_code in _UNAVAILABLE_STATUSES or response.status_code >= 500:- raise BillingUpstreamUnavailableError(message)- raise BillingUpstreamInvalidResponseError(message)+ status_code, error_body = response.status_code, _error_body(response)+ if status_code in _UNAVAILABLE_STATUSES or status_code >= 500:+ raise BillingUpstreamUnavailableError(message, status_code=status_code, body=error_body)+ raise BillingUpstreamInvalidResponseError(message, status_code=status_code, body=error_body)invalid_body = f"{method} {path} returned an invalid body"try:@@ -137,6 +153,13 @@ def request[ResponseT: BillingModel](return _salvage_model(response_model, payload)+def _error_body(response: httpx.Response) -> UpstreamErrorBody | None:+ try:+ return UpstreamErrorBody.model_validate_json(response.content)+ except ValidationError:+ return None++def _salvage_model[ModelT: BillingModel](model: type[ModelT], payload: Mapping[str, Any]) -> ModelT:values: dict[str, Any] = {}for name, field in model.model_fields.items():diff --git a/api/services/billing_service.py b/api/services/billing_service.pyindex 4a515834950..7ee9286e24f 100644--- a/api/services/billing_service.py+++ b/api/services/billing_service.py@@ -1,5 +1,4 @@import logging-import osfrom collections.abc import Mapping, Sequencefrom typing import Literalfrom warnings import deprecated@@ -22,9 +21,6 @@ def _quota_meta(meta: Mapping[str, object] | None) -> dict[str, str]:class BillingService:- base_url = os.environ.get("BILLING_API_URL", "BILLING_API_URL")- secret_key = os.environ.get("BILLING_API_SECRET_KEY", "BILLING_API_SECRET_KEY")-# Redis key prefix for tenant plan cache_PLAN_CACHE_KEY_PREFIX = "tenant_plan:"# Cache TTL: 10 minutesdiff --git a/api/services/errors/billing.py b/api/services/errors/billing.pyindex cbbd96fa803..f1e214407cf 100644--- a/api/services/errors/billing.py+++ b/api/services/errors/billing.py@@ -1,3 +1,8 @@+from typing import Annotated, Any++from pydantic import BaseModel, ConfigDict, ValidationError, ValidatorFunctionWrapHandler, WrapValidator++class BillingError(Exception):pass@@ -6,9 +11,42 @@ class ComplianceRateLimitExceededError(BillingError):pass-class BillingUpstreamInvalidResponseError(BillingError):+def _none_on_error(value: object, handler: ValidatorFunctionWrapHandler) -> Any:+ try:+ return handler(value)+ except ValidationError:+ return None+++type _Lenient[T] = Annotated[T | None, WrapValidator(_none_on_error)]+++class UpstreamErrorBody(BaseModel):+ """Kratos error body of a non-200 reply. A field of an unexpected type reads as None instead of failing the rest."""++ model_config = ConfigDict(extra="ignore", frozen=True)++ code: _Lenient[int] = None+ reason: _Lenient[str] = None+ message: _Lenient[str] = None+ metadata: _Lenient[dict[str, str]] = None+++class BillingUpstreamError(BillingError):+ """A billing or saas call failed.++ `status_code` and `body` are set when the upstream answered with a non-200 status.+ """++ def __init__(self, *args: object, status_code: int | None = None, body: UpstreamErrorBody | None = None) -> None:+ super().__init__(*args)+ self.status_code = status_code+ self.body = body+++class BillingUpstreamInvalidResponseError(BillingUpstreamError):pass-class BillingUpstreamUnavailableError(BillingError):+class BillingUpstreamUnavailableError(BillingUpstreamError):passdiff --git a/api/services/network_access_group_gateway.py b/api/services/network_access_group_gateway.pyindex 00338f6fa9d..be2c63ba4b2 100644--- a/api/services/network_access_group_gateway.py+++ b/api/services/network_access_group_gateway.py@@ -1,26 +1,13 @@-"""HTTP and Billing adapters used by the network access group service."""+"""Saas and Billing adapters used by the network access group service."""-import json-import re-from collections.abc import Mapping-from datetime import datetime-from typing import Annotated, Any, ClassVar, Literal, override+from collections.abc import Generator+from contextlib import contextmanager+from typing import overrideimport httpx-from pydantic import (- BaseModel,- BeforeValidator,- ConfigDict,- Field,- StrictBool,- StrictStr,- ValidationError,- model_validator,-)-from tenacity import retry, retry_if_exception_type, stop_before_delay, wait_fixed-from core.helper.http_client_pooling import get_pooled_http_clientfrom enums import CloudPlan+from services.billing_client import saasfrom services.billing_service import BillingServicefrom services.entities.network_access_group_entities import (NetworkAccessAppConfig,@@ -30,7 +17,7 @@ from services.entities.network_access_group_entities import (NetworkAccessGroup,NetworkAccessGroupList,)-from services.errors.billing import BillingError+from services.errors.billing import BillingError, BillingUpstreamError, BillingUpstreamUnavailableErrorfrom services.network_access_group_service import (NetworkAccessGroupControlPlane,NetworkAccessGroupEntitlement,@@ -40,196 +27,81 @@ from services.network_access_group_service import ()-def _int64(value: object) -> int:- if type(value) is int:- return value- if isinstance(value, str) and re.fullmatch(r"[+-]?[0-9]+", value):- return int(value)- raise ValueError("Expected a ProtoJSON integer or decimal string")---_Count = Annotated[int, BeforeValidator(_int64), Field(ge=0, le=2**63 - 1)]-_Version = Annotated[int, BeforeValidator(_int64), Field(ge=1, le=2**63 - 1)]-_Identifier = Annotated[StrictStr, Field(min_length=1)]---class _WireModel(BaseModel):- model_config = ConfigDict(frozen=True, extra="ignore")- aliases: ClassVar[Mapping[str, tuple[str, ...]]] = {}-- @model_validator(mode="before")- @classmethod- def canonical_names(cls, value: object) -> object:- if not isinstance(value, dict):- return value- data = dict(value)- for name, aliases in cls.aliases.items():- supplied = [data[key] for key in (name, *aliases) if key in data]- if not supplied:- continue- if any(type(item) is not type(supplied[0]) or item != supplied[0] for item in supplied[1:]):- raise ValueError(f"Conflicting aliases for {name}")- data[name] = supplied[0]- for alias in aliases:- data.pop(alias, None)- return data---class _GroupWire(_WireModel):- aliases = {- "tenant_id": ("tenantId",),- "allowed_cidrs": ("allowedCidrs",),- "used_by_count": ("usedByCount",),- "enforcing_count": ("enforcingCount",),- "app_ids": ("appIds", "used_by_app_ids", "usedByAppIds"),- "updated_by_account_id": ("updatedByAccountId",),- "created_at": ("createdAt",),- "updated_at": ("updatedAt",),- }- id: _Identifier- tenant_id: _Identifier- name: StrictStr- description: StrictStr = ""- allowed_cidrs: Annotated[tuple[StrictStr, ...], Field(min_length=1, max_length=100)]- version: _Version- used_by_count: _Count | None = None- enforcing_count: _Count = 0- app_ids: tuple[_Identifier, ...] = ()- updated_by_account_id: StrictStr | None = None- created_at: datetime- updated_at: datetime-- def record(self) -> NetworkAccessGroup:- return NetworkAccessGroup(- id=self.id,- tenant_id=self.tenant_id,- name=self.name,- description=self.description,- allowed_cidrs=self.allowed_cidrs,- version=self.version,- used_by_count=len(self.app_ids) if self.used_by_count is None else self.used_by_count,- enforcing_count=self.enforcing_count,- app_ids=self.app_ids,- updated_by_account_id=self.updated_by_account_id,- created_at=self.created_at,- updated_at=self.updated_at,- )---class _BindingWire(_WireModel):- aliases = {- "tenant_id": ("tenantId",),- "app_id": ("appId",),- "group_id": ("groupId", "policy_id", "policyId"),- "access_points": ("accessPoints",),- "updated_by_account_id": ("updatedByAccountId",),- "created_at": ("createdAt",),- "updated_at": ("updatedAt",),- }- id: _Identifier- tenant_id: _Identifier- app_id: _Identifier- enabled: StrictBool = False- group_id: StrictStr | None = None- access_points: tuple[StrictStr, ...] = ()- version: _Version- updated_by_account_id: StrictStr | None = None- created_at: datetime- updated_at: datetime-- def record(self) -> NetworkAccessBinding:- return NetworkAccessBinding(- id=self.id,- tenant_id=self.tenant_id,- app_id=self.app_id,- enabled=self.enabled,- group_id=self.group_id or None,- access_points=self.access_points,- version=self.version,- updated_by_account_id=self.updated_by_account_id,- created_at=self.created_at,- updated_at=self.updated_at,- )---class _GroupResultWire(_WireModel):- group: _GroupWire---class _ListWire(_WireModel):- aliases = {"tenant_id": ("tenantId",)}- tenant_id: _Identifier- entitled: StrictBool = False- groups: tuple[_GroupWire, ...] = ()---class _AppConfigWire(_WireModel):- aliases = {"tenant_id": ("tenantId",), "app_id": ("appId",), "effective_enabled": ("effectiveEnabled",)}- tenant_id: _Identifier- app_id: _Identifier- entitled: StrictBool = False- effective_enabled: StrictBool = False- binding: _BindingWire | None = None---class _BindingUpdateWire(_WireModel):- aliases = {"effective_enabled": ("effectiveEnabled",)}- binding: _BindingWire- effective_enabled: StrictBool = False+@contextmanager+def _upstream_errors() -> Generator[None]:+ """Map saas failures to the service's errors, keeping the upstream status and Kratos reason."""+ try:+ yield+ except BillingUpstreamError as exc:+ if exc.status_code is not None:+ reason = exc.body.reason if exc.body is not None else None+ raise NetworkAccessGroupUpstreamError(exc.status_code, reason) from exc+ if isinstance(exc, BillingUpstreamUnavailableError):+ raise NetworkAccessGroupUpstreamError(httpx.codes.SERVICE_UNAVAILABLE) from exc+ raise NetworkAccessGroupInvalidResponseError from exc-class _AppStatusWire(_WireModel):- aliases = {"access_points": ("accessPoints",)}- entitled: StrictBool = False- configured: StrictBool = False- enabled: StrictBool = False- access_points: tuple[StrictStr, ...] = ()+_MAX_INT64 = 2**63 - 1-class _DeletedWire(_WireModel):- deleted: StrictBool = False+def _require(valid: bool) -> None:+ """Reject replies that match the schema but break invariants the service relies on."""+ if not valid:+ raise NetworkAccessGroupInvalidResponseError-def _decode[T: _WireModel](model: type[T], value: dict[str, Any]) -> T:- try:- return model.model_validate(value)- except ValidationError as exc:- raise NetworkAccessGroupInvalidResponseError from exc+def _group(wire: saas.NetworkAccessGroup | None) -> NetworkAccessGroup:+ if wire is None:+ raise NetworkAccessGroupInvalidResponseError+ _require(+ bool(wire.id and wire.tenant_id)+ and 1 <= len(wire.allowed_cidrs) <= 100+ and 1 <= wire.version <= _MAX_INT64+ and 0 <= wire.used_by_count <= _MAX_INT64+ and 0 <= wire.enforcing_count <= _MAX_INT64+ and all(wire.used_by_app_ids)+ )+ return NetworkAccessGroup(+ id=wire.id,+ tenant_id=wire.tenant_id,+ name=wire.name,+ description=wire.description,+ allowed_cidrs=tuple(wire.allowed_cidrs),+ version=wire.version,+ used_by_count=wire.used_by_count,+ enforcing_count=wire.enforcing_count,+ app_ids=tuple(wire.used_by_app_ids),+ updated_by_account_id=wire.updated_by_account_id,+ created_at=wire.created_at,+ updated_at=wire.updated_at,+ )-_http_client: httpx.Client = get_pooled_http_client(- "network-access-group:default",- lambda: httpx.Client(- timeout=httpx.Timeout(30.0, connect=5.0),- limits=httpx.Limits(max_keepalive_connections=50, max_connections=100),- ),-)+def _binding(wire: saas.AppNetworkAccessGroupBinding) -> NetworkAccessBinding:+ _require(bool(wire.id and wire.tenant_id and wire.app_id) and 1 <= wire.version <= _MAX_INT64)+ return NetworkAccessBinding(+ id=wire.id,+ tenant_id=wire.tenant_id,+ app_id=wire.app_id,+ enabled=wire.enabled,+ group_id=wire.group_id or None,+ access_points=tuple(wire.access_points),+ version=wire.version,+ updated_by_account_id=wire.updated_by_account_id,+ created_at=wire.created_at,+ updated_at=wire.updated_at,+ )class NetworkAccessGroupGateway(NetworkAccessGroupControlPlane):- def __init__(- self,- *,- base_url: str,- fallback_base_url: str,- secret_key: str,- http_client: httpx.Client = _http_client,- ) -> None:- self._base_url = base_url.strip() or fallback_base_url- self._secret_key = secret_key- self._http_client = http_client-@overridedef list_groups(self, workspace_id: str, actor_account_id: str) -> NetworkAccessGroupList:- wire = _decode(- _ListWire,- self._send_request(- "GET",- f"/tenants/{workspace_id}/network-access-groups",- params={"actor_account_id": actor_account_id},- ),- )- return NetworkAccessGroupList(wire.tenant_id, wire.entitled, tuple(group.record() for group in wire.groups))+ with _upstream_errors():+ reply = saas.network_access_policy_list_network_access_groups(+ tenant_id=workspace_id, actor_account_id=actor_account_id+ )+ _require(bool(reply.tenant_id))+ return NetworkAccessGroupList(reply.tenant_id, reply.entitled, tuple(_group(group) for group in reply.groups))@overridedef create_group(@@ -241,30 +113,27 @@ class NetworkAccessGroupGateway(NetworkAccessGroupControlPlane):allowed_cidrs: list[str],actor_account_id: str,) -> NetworkAccessGroup:- return _decode(- _GroupResultWire,- self._send_request(- "POST",- f"/tenants/{workspace_id}/network-access-groups",- payload_json={- "name": name,- "description": description,- "allowed_cidrs": allowed_cidrs,- "actor_account_id": actor_account_id,- },- ),- ).group.record()+ with _upstream_errors():+ reply = saas.network_access_policy_create_network_access_group(+ tenant_id=workspace_id,+ body=saas.CreateNetworkAccessGroupRequest(+ tenant_id=workspace_id,+ name=name,+ description=description,+ mode="",+ allowed_cidrs=allowed_cidrs,+ actor_account_id=actor_account_id,+ ),+ )+ return _group(reply.group)@overridedef get_group(self, workspace_id: str, group_id: str, actor_account_id: str) -> NetworkAccessGroup:- return _decode(- _GroupResultWire,- self._send_request(- "GET",- f"/tenants/{workspace_id}/network-access-groups/{group_id}",- params={"actor_account_id": actor_account_id},- ),- ).group.record()+ with _upstream_errors():+ reply = saas.network_access_policy_get_network_access_group(+ tenant_id=workspace_id, group_id=group_id, actor_account_id=actor_account_id+ )+ return _group(reply.group)@overridedef update_group(@@ -278,20 +147,22 @@ class NetworkAccessGroupGateway(NetworkAccessGroupControlPlane):expected_version: int,actor_account_id: str,) -> NetworkAccessGroup:- return _decode(- _GroupResultWire,- self._send_request(- "PUT",- f"/tenants/{workspace_id}/network-access-groups/{group_id}",- payload_json={- "name": name,- "description": description,- "allowed_cidrs": allowed_cidrs,- "expected_version": expected_version,- "actor_account_id": actor_account_id,- },- ),- ).group.record()+ with _upstream_errors():+ reply = saas.network_access_policy_update_network_access_group(+ tenant_id=workspace_id,+ group_id=group_id,+ body=saas.UpdateNetworkAccessGroupRequest(+ tenant_id=workspace_id,+ group_id=group_id,+ name=name,+ description=description,+ mode="",+ allowed_cidrs=allowed_cidrs,+ expected_version=expected_version,+ actor_account_id=actor_account_id,+ ),+ )+ return _group(reply.group)@overridedef delete_group(@@ -302,47 +173,39 @@ class NetworkAccessGroupGateway(NetworkAccessGroupControlPlane):expected_version: int,actor_account_id: str,) -> bool:- return _decode(- _DeletedWire,- self._send_request(- "DELETE",- f"/tenants/{workspace_id}/network-access-groups/{group_id}",- params={- "expected_version": expected_version,- "actor_account_id": actor_account_id,- },- ),- ).deleted+ with _upstream_errors():+ reply = saas.network_access_policy_delete_network_access_group(+ tenant_id=workspace_id,+ group_id=group_id,+ expected_version=str(expected_version),+ actor_account_id=actor_account_id,+ )+ return reply.deleted@overridedef get_app_binding(self, workspace_id: str, app_id: str, actor_account_id: str) -> NetworkAccessAppConfig:- wire = _decode(- _AppConfigWire,- self._send_request(- "GET",- f"/tenants/{workspace_id}/apps/{app_id}/network-access-group",- params={"actor_account_id": actor_account_id},- ),- )+ with _upstream_errors():+ reply = saas.network_access_policy_get_app_network_access_group(+ tenant_id=workspace_id, app_id=app_id, actor_account_id=actor_account_id+ )+ _require(bool(reply.tenant_id and reply.app_id))return NetworkAccessAppConfig(- wire.tenant_id,- wire.app_id,- wire.entitled,- wire.effective_enabled,- wire.binding.record() if wire.binding is not None else None,+ reply.tenant_id,+ reply.app_id,+ reply.entitled,+ reply.effective_enabled,+ _binding(reply.binding) if reply.binding is not None else None,)@overridedef get_app_status(self, workspace_id: str, app_id: str, actor_account_id: str) -> NetworkAccessAppStatusSnapshot:- wire = _decode(- _AppStatusWire,- self._send_request(- "GET",- f"/tenants/{workspace_id}/apps/{app_id}/network-access-group/status",- params={"actor_account_id": actor_account_id},- ),+ with _upstream_errors():+ reply = saas.network_access_policy_get_app_network_access_group_status(+ tenant_id=workspace_id, app_id=app_id, actor_account_id=actor_account_id+ )+ return NetworkAccessAppStatusSnapshot(+ reply.entitled, reply.configured, reply.enabled, tuple(reply.access_points))- return NetworkAccessAppStatusSnapshot(wire.entitled, wire.configured, wire.enabled, wire.access_points)@overridedef update_app_binding(@@ -356,92 +219,31 @@ class NetworkAccessGroupGateway(NetworkAccessGroupControlPlane):expected_version: int,actor_account_id: str,) -> NetworkAccessBindingUpdate:- wire = _decode(- _BindingUpdateWire,- self._send_request(- "PUT",- f"/tenants/{workspace_id}/apps/{app_id}/network-access-group",- payload_json={- "enabled": enabled,- "group_id": group_id,- "access_points": access_points,- "expected_version": expected_version,- "actor_account_id": actor_account_id,- },- ),- )- return NetworkAccessBindingUpdate(wire.binding.record(), wire.effective_enabled)+ with _upstream_errors():+ reply = saas.network_access_policy_put_app_network_access_group(+ tenant_id=workspace_id,+ app_id=app_id,+ body=saas.PutAppNetworkAccessGroupRequest(+ tenant_id=workspace_id,+ app_id=app_id,+ group_id=group_id,+ expected_version=expected_version,+ actor_account_id=actor_account_id,+ enabled=enabled,+ access_points=access_points,+ ),+ )+ if reply.binding is None:+ raise NetworkAccessGroupInvalidResponseError+ return NetworkAccessBindingUpdate(_binding(reply.binding), reply.effective_enabled)@overridedef cleanup_app_binding(self, workspace_id: str, app_id: str) -> bool:- return _decode(- _DeletedWire,- self._send_request(- "DELETE",- f"/tenants/{workspace_id}/apps/{app_id}/network-access-group-binding",- ),- ).deleted-- def _send_request(- self,- method: Literal["GET", "POST", "PUT", "DELETE"],- endpoint: str,- *,- payload_json: dict[str, Any] | None = None,- params: dict[str, Any] | None = None,- ) -> dict[str, Any]:- try:- response = self._send_http_request(- method,- endpoint,- payload_json=payload_json,- params=params,+ with _upstream_errors():+ reply = saas.network_access_policy_cleanup_app_network_access_group_binding(+ tenant_id=workspace_id, app_id=app_id)- except httpx.RequestError as exc:- raise NetworkAccessGroupUpstreamError(httpx.codes.SERVICE_UNAVAILABLE) from exc-- if response.status_code not in (httpx.codes.OK, httpx.codes.CREATED):- reason = None- try:- error_payload = response.json()- if isinstance(error_payload, dict) and isinstance(error_payload.get("reason"), str):- reason = error_payload["reason"]- except (json.JSONDecodeError, TypeError, ValueError):- pass- raise NetworkAccessGroupUpstreamError(response.status_code, reason)-- try:- payload = response.json()- except (json.JSONDecodeError, TypeError, ValueError) as exc:- raise NetworkAccessGroupInvalidResponseError from exc-- if not isinstance(payload, dict):- raise NetworkAccessGroupInvalidResponseError- return payload-- @retry(- wait=wait_fixed(2),- stop=stop_before_delay(10),- retry=retry_if_exception_type(httpx.RequestError),- reraise=True,- )- def _send_http_request(- self,- method: Literal["GET", "POST", "PUT", "DELETE"],- endpoint: str,- *,- payload_json: dict[str, Any] | None = None,- params: dict[str, Any] | None = None,- ) -> httpx.Response:- headers = {"Content-Type": "application/json", "Billing-Api-Secret-Key": self._secret_key}- return self._http_client.request(- method,- f"{self._base_url.rstrip('/')}{endpoint}",- json=payload_json,- params=params,- headers=headers,- follow_redirects=True,- )+ return reply.deletedclass BillingNetworkAccessGroupEntitlementGateway(NetworkAccessGroupEntitlement):diff --git a/api/services/operation_service.py b/api/services/operation_service.pyindex 6869cf23ea2..89bb20146a9 100644--- a/api/services/operation_service.py+++ b/api/services/operation_service.py@@ -1,9 +1,6 @@-import osfrom typing import TypedDict-import httpx--OPERATION_REQUEST_TIMEOUT = httpx.Timeout(10.0, connect=3.0)+from services.billing_client import saasclass UtmInfo(TypedDict, total=False):@@ -20,28 +17,15 @@ class UtmInfo(TypedDict, total=False):class OperationService:- base_url = os.environ.get("BILLING_API_URL", "BILLING_API_URL")- secret_key = os.environ.get("BILLING_API_SECRET_KEY", "BILLING_API_SECRET_KEY")-@classmethod- def _send_request(cls, method, endpoint, json=None, params=None):- headers = {"Content-Type": "application/json", "Billing-Api-Secret-Key": cls.secret_key}-- url = f"{cls.base_url}{endpoint}"- response = httpx.request(- method, url, json=json, params=params, headers=headers, timeout=OPERATION_REQUEST_TIMEOUT+ def record_utm(cls, tenant_id: str, utm_info: UtmInfo) -> saas.TenantUtmReply:+ return saas.utm_record_tenant_utm(+ body=saas.TenantUtmRequest(+ tenant_id=tenant_id,+ utm_source=utm_info.get("utm_source", ""),+ utm_medium=utm_info.get("utm_medium", ""),+ utm_campaign=utm_info.get("utm_campaign", ""),+ utm_content=utm_info.get("utm_content", ""),+ utm_term=utm_info.get("utm_term", ""),+ ))-- return response.json()-- @classmethod- def record_utm(cls, tenant_id: str, utm_info: UtmInfo):- params = {- "tenant_id": tenant_id,- "utm_source": utm_info.get("utm_source", ""),- "utm_medium": utm_info.get("utm_medium", ""),- "utm_campaign": utm_info.get("utm_campaign", ""),- "utm_content": utm_info.get("utm_content", ""),- "utm_term": utm_info.get("utm_term", ""),- }- return cls._send_request("POST", "/tenant_utms", params=params)diff --git a/api/tests/unit_tests/controllers/console/workspace/test_network_access_group.py b/api/tests/unit_tests/controllers/console/workspace/test_network_access_group.pyindex c410d3942a9..dcbc9f78ad5 100644--- a/api/tests/unit_tests/controllers/console/workspace/test_network_access_group.py+++ b/api/tests/unit_tests/controllers/console/workspace/test_network_access_group.py@@ -1,3 +1,4 @@+import osfrom collections.abc import Callable, Generator, Mappingfrom contextlib import contextmanagerfrom dataclasses import replace@@ -41,6 +42,7 @@ from machinery.context import RequestContextfrom models.account import Account, AccountStatusfrom repositories.network_access_group_repository import SQLAlchemyNetworkAccessGroupAppRepositoryfrom repositories.workspace.workspace_repository import WorkspaceRepository+from services.billing_client import saas, transportfrom services.entities.network_access_group_entities import (NetworkAccessAppConfig,NetworkAccessAppStatus,@@ -64,6 +66,7 @@ from services.network_access_group_service import (NetworkAccessGroupUnsupportedAppModeError,NetworkAccessGroupUpstreamError,)+from tests.helpers.unit.config_override import config_overrides_contextTENANT_ID = "11111111-1111-4111-8111-111111111111"ACCOUNT_ID = "22222222-2222-4222-8222-222222222222"@@ -348,22 +351,27 @@ def test_app_status_uses_minimal_upstream_route_and_filters_scopes_for_current_massert len(requests) == 1assert requests[0].method == "GET"assert requests[0].url.path == f"/tenants/{TENANT_ID}/apps/{APP_ID}/network-access-group/status"- assert dict(requests[0].url.params) == {"actor_account_id": ACCOUNT_ID}+ assert dict(requests[0].url.params) == {"actorAccountId": ACCOUNT_ID}assert requests[0].headers["Billing-Api-Secret-Key"] == "synthetic"+def _status_wire(**overrides: object) -> dict[str, object]:+ reply = saas.GetAppNetworkAccessGroupStatusReply(entitled=False, configured=False, enabled=False, access_points=[])+ return {**reply.model_dump(mode="json"), **overrides}++@pytest.mark.parametrize(("wire", "paid", "expected"),[({}, True, {"entitled": False, "configured": False, "enabled": False, "covered_count": 0}),({"entitled": True}, True, {"entitled": True, "configured": False, "enabled": False, "covered_count": 0}),(- {"entitled": True, "configured": True, "access_points": ["webapp"]},+ {"entitled": True, "configured": True, "accessPoints": ["webapp"]},True,{"entitled": True, "configured": True, "enabled": False, "covered_count": 1},),(- {"entitled": True, "configured": True, "enabled": True, "access_points": ["webapp"]},+ {"entitled": True, "configured": True, "enabled": True, "accessPoints": ["webapp"]},False,{"entitled": False, "configured": True, "enabled": True, "covered_count": 1},),@@ -375,7 +383,7 @@ def test_app_status_preserves_saved_state_and_applies_local_entitlement(paid: bool,expected: dict[str, object],) -> None:- response, _requests = _typed_status_http_response(account_application_services, wire, paid=paid)+ response, _requests = _typed_status_http_response(account_application_services, _status_wire(**wire), paid=paid)assert response.status_code == 200assert response.get_json() == {**expected, "available_count": 4}@@ -403,11 +411,11 @@ def test_app_status_does_not_fall_back_to_full_binding_after_upstream_error(@pytest.mark.parametrize("field", ["entitled", "configured", "enabled"])[email protected]("value", ["false", "true", 0, 1, None])[email protected]("value", ["maybe", 2, None])def test_app_status_rejects_non_boolean_flags(account_application_services: ApplicationServices, field: str, value: object) -> None:- response, _requests = _typed_status_http_response(account_application_services, {field: value})+ response, _requests = _typed_status_http_response(account_application_services, _status_wire(**{field: value}))assert response.status_code == 502@@ -415,15 +423,15 @@ def test_app_status_rejects_non_boolean_flags(@pytest.mark.parametrize("wire",[- {"access_points": "webapp"},- {"access_points": [1]},- {"access_points": ["webapp"], "accessPoints": ["mcp"]},+ {"accessPoints": "webapp"},+ {"accessPoints": [1]},+ {"accessPoints": None},],)-def test_app_status_rejects_malformed_or_conflicting_scopes(+def test_app_status_rejects_malformed_scopes(account_application_services: ApplicationServices, wire: Mapping[str, object]) -> None:- response, _requests = _typed_status_http_response(account_application_services, wire)+ response, _requests = _typed_status_http_response(account_application_services, _status_wire(**wire))assert response.status_code == 502@@ -961,7 +969,7 @@ def test_current_ip_read_response_schema_exposes_only_client_ip() -> None:assert schema["properties"]["client_ip"]["type"] == "string"[email protected]("group_field", ["group_id", "groupId", "policy_id", "policyId"])[email protected]("group_field", ["group_id", "groupId"])@pytest.mark.parametrize("stale_only", [False, True])def test_typed_gateway_service_controller_pipeline_preserves_binding_configuration(account_application_services: ApplicationServices, group_field: str, stale_only: bool@@ -979,6 +987,7 @@ def test_typed_gateway_service_controller_pipeline_preserves_binding_configuratigroup_field: GROUP_ID,"accessPoints": ["future_scope"] if stale_only else ["webapp"],"version": "3",+ "updatedByAccountId": "","createdAt": "2026-08-21T00:00:00Z","updatedAt": "2026-08-21T00:00:00Z",},@@ -1002,7 +1011,8 @@ def test_malformed_upstream_response_maps_to_http_502_before_business_truthiness{"tenantId": TENANT_ID,"appId": APP_ID,- "entitled": "false",+ "entitled": "maybe",+ "binding": None,"effectiveEnabled": False,},)@@ -1015,13 +1025,12 @@ def _typed_binding_http_response(services: ApplicationServices, wire: Mapping[stapps = SQLAlchemyNetworkAccessGroupAppRepository(session_factory=sessionmaker())memberships = WorkspaceRepository(session_factory=sessionmaker())entitlement = BillingNetworkAccessGroupEntitlementGateway()- with httpx.Client(transport=httpx.MockTransport(lambda _request: httpx.Response(200, json=wire))) as client:- gateway = NetworkAccessGroupGateway(- base_url="https://test.invalid",- fallback_base_url="",- secret_key="synthetic",- http_client=client,- )+ with (+ httpx.Client(transport=httpx.MockTransport(lambda _request: httpx.Response(200, json=wire))) as client,+ patch.object(transport, "_http_client", client),+ config_overrides_context(NETWORK_ACCESS_API_URL="https://test.invalid"),+ ):+ gateway = NetworkAccessGroupGateway()service = NetworkAccessGroupService(control_plane=gateway, apps=apps, memberships=memberships, entitlement=entitlement)@@ -1066,13 +1075,13 @@ def _typed_status_http_response(return httpx.Response(403, json={"reason": "FORBIDDEN"})return httpx.Response(upstream_status, json=wire)- with httpx.Client(transport=httpx.MockTransport(respond)) as client:- gateway = NetworkAccessGroupGateway(- base_url="https://test.invalid",- fallback_base_url="",- secret_key="synthetic",- http_client=client,- )+ with (+ httpx.Client(transport=httpx.MockTransport(respond)) as client,+ patch.object(transport, "_http_client", client),+ patch.dict(os.environ, {"BILLING_API_SECRET_KEY": "synthetic"}),+ config_overrides_context(NETWORK_ACCESS_API_URL="https://test.invalid"),+ ):+ gateway = NetworkAccessGroupGateway()service = NetworkAccessGroupService(control_plane=gateway, apps=apps, memberships=memberships, entitlement=entitlement)diff --git a/api/tests/unit_tests/dev/test_generate_billing_client.py b/api/tests/unit_tests/dev/test_generate_billing_client.pyindex f85ebbe6cfe..f34651b69ac 100644--- a/api/tests/unit_tests/dev/test_generate_billing_client.py+++ b/api/tests/unit_tests/dev/test_generate_billing_client.py@@ -36,6 +36,7 @@ def _source_spec() -> generator.JsonObject:"members": {"$ref": f"{PREFIX}Quota"},"usage_unknown": {"type": "boolean", "nullable": True},"tags": {"type": "array", "items": {"type": "string"}},+ "renewed_at": {"type": "string", "format": "date-time"},},},"dify.saas.api.billing.Quota": {"type": "object", "properties": {"limit": {"type": "integer"}}},@@ -74,7 +75,7 @@ def test_snapshot_marks_presence_from_protojson_rules() -> None:]# Proto3 optional fields are omitted when unset, so only they stay out of required.- assert schema["required"] == ["plan", "paid_period_end", "members", "tags"]+ assert schema["required"] == ["plan", "paid_period_end", "members", "tags", "renewed_at"]assert schema["properties"]["members"] == {"allOf": [{"$ref": "#/components/schemas/Quota"}], "nullable": True}assert "nullable" not in schema["properties"]["plan"]@@ -89,10 +90,24 @@ def test_rendered_module_types_fields_and_operations() -> None:assert "paid_period_end: int\n" in sourceassert "members: Quota | None\n" in sourceassert "usage_unknown: bool | None = None\n" in source+ assert "renewed_at: datetime\n" in sourceassert "def subscription_get_subscription_info() -> GetSubscriptionInfoReply:" in sourceassert '"/subscription/info",' in source+def test_long_operation_docstring_is_wrapped() -> None:+ allowed = generator.AllowedOperation("GET", f"/v1/subscription/{'x' * 80}", "BILLING")+ operation = {+ "operationId": "BillingSubscription_GetSubscriptionInfo",+ "responses": {"200": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Reply"}}}}},+ }++ lines = generator.render_operation("billing", allowed, operation)++ assert lines[1] == f' """GET {allowed.path}\n\n BillingSubscription_GetSubscriptionInfo\n """'+ assert all(len(line) <= generator.LINE_LENGTH for line in "\n".join(lines).splitlines())++@pytest.mark.usefixtures("subscription_info_only")def test_upstream_required_message_field_is_non_null() -> None:source = _source_spec()@@ -102,7 +117,7 @@ def test_upstream_required_message_field_is_non_null() -> None:schema = snapshot["components"]["schemas"]["GetSubscriptionInfoReply"]assert schema["properties"]["members"] == {"$ref": "#/components/schemas/Quota"}- assert schema["required"] == ["plan", "paid_period_end", "members", "tags"]+ assert schema["required"] == ["plan", "paid_period_end", "members", "tags", "renewed_at"]assert "members: Quota\n" in generator.render_module("billing", snapshot)diff --git a/api/tests/unit_tests/services/billing_client/test_transport.py b/api/tests/unit_tests/services/billing_client/test_transport.pyindex d1dc1f41dfb..cd4b8469952 100644--- a/api/tests/unit_tests/services/billing_client/test_transport.py+++ b/api/tests/unit_tests/services/billing_client/test_transport.py@@ -1,4 +1,5 @@import logging+from collections.abc import Callableimport httpximport pytest@@ -6,7 +7,12 @@ import tenacityfrom services.billing_client import billing, transportfrom services.billing_client.transport import BillingModel, Upstream-from services.errors.billing import BillingUpstreamInvalidResponseError, BillingUpstreamUnavailableError+from services.errors.billing import (+ BillingUpstreamError,+ BillingUpstreamInvalidResponseError,+ BillingUpstreamUnavailableError,+ UpstreamErrorBody,+)from tests.unit_tests.services.billing_client.conftest import RespondWith@@ -43,11 +49,48 @@ def _get(upstream: Upstream) -> _Reply:],)def test_non_ok_status_maps_to_upstream_errors(respond_with: RespondWith, status: int, error: type[Exception]) -> None:- respond_with(httpx.Response(status, json={}))+ respond_with(httpx.Response(status, json={"code": status, "reason": "QUOTA_EXCEEDED", "message": "over"}))++ with pytest.raises(error) as exc_info:+ _get(Upstream.BILLING)++ assert isinstance(exc_info.value, BillingUpstreamError)+ assert exc_info.value.status_code == status+ assert exc_info.value.body == UpstreamErrorBody(code=status, reason="QUOTA_EXCEEDED", message="over")+++ ("content", "body"),+ [+ (b"upstream crashed", None),+ (b"[]", None),+ (b'{"code": "x", "reason": "CONFLICT", "metadata": {"k": 1}}', UpstreamErrorBody(reason="CONFLICT")),+ ],+)+def test_error_body_keeps_well_typed_fields(+ respond_with: RespondWith, content: bytes, body: UpstreamErrorBody | None+) -> None:+ respond_with(httpx.Response(409, content=content))++ with pytest.raises(BillingUpstreamInvalidResponseError) as exc_info:+ _get(Upstream.BILLING)++ assert exc_info.value.body == body+++def test_unreachable_upstream_has_no_status(monkeypatch: pytest.MonkeyPatch) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("connection refused", request=request)++ monkeypatch.setattr("services.billing_client.transport._send.retry.stop", tenacity.stop_after_attempt(1))+ monkeypatch.setattr(transport, "_http_client", httpx.Client(transport=httpx.MockTransport(handler)))- with pytest.raises(error):+ with pytest.raises(BillingUpstreamUnavailableError) as exc_info:_get(Upstream.BILLING)+ assert exc_info.value.status_code is None+ assert exc_info.value.body is None+def test_request_error_is_retried_then_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:attempts: list[httpx.Request] = []@@ -89,6 +132,24 @@ def test_upstream_selects_base_url(assert str(requests[0].url) == expected+ ("configured", "expected"),+ [+ ("http://network-access/v1/", "http://network-access/v1/probe"),+ ("", "http://billing/v1/probe"),+ ],+)+def test_network_access_upstream_falls_back_to_billing_url(+ respond_with: RespondWith, config_overrides: Callable[..., None], configured: str, expected: str+) -> None:+ config_overrides(NETWORK_ACCESS_API_URL=configured)+ requests = respond_with(httpx.Response(200, json={"ok": True}))++ _get(Upstream.NETWORK_ACCESS)++ assert str(requests[0].url) == expected++def test_invalid_body_is_reported_and_kept_raw_while_observed(respond_with: RespondWith, caplog: pytest.LogCaptureFixture) -> None:diff --git a/api/tests/unit_tests/services/test_network_access_group_gateway.py b/api/tests/unit_tests/services/test_network_access_group_gateway.pyindex 7488916a7b2..1d40259a093 100644--- a/api/tests/unit_tests/services/test_network_access_group_gateway.py+++ b/api/tests/unit_tests/services/test_network_access_group_gateway.py@@ -1,11 +1,14 @@-from collections.abc import Callable, Generator-from typing import Protocol, cast, override-from unittest.mock import call, patch+import json+from collections.abc import Callable+from datetime import UTC, datetime+from unittest.mock import patchimport httpximport pytestfrom enums import CloudPlan+from services.billing_client import saas, transport+from services.billing_client.transport import BillingModelfrom services.errors.billing import BillingUpstreamInvalidResponseError, BillingUpstreamUnavailableErrorfrom services.network_access_group_gateway import (BillingNetworkAccessGroupEntitlementGateway,@@ -22,190 +25,99 @@ TENANT_ID = "11111111-1111-4111-8111-111111111111"ACCOUNT_ID = "22222222-2222-4222-8222-222222222222"APP_ID = "33333333-3333-4333-8333-333333333333"GROUP_ID = "44444444-4444-4444-8444-444444444444"-HEADERS = {"Content-Type": "application/json", "Billing-Api-Secret-Key": "test-secret"}+CREATED_AT = datetime(2026, 9, 1, tzinfo=UTC)+type Respond = Callable[[httpx.Response], list[httpx.Request]]-def _group_wire(**overrides: object) -> dict[str, object]:- return {++def _group(**overrides: object) -> saas.NetworkAccessGroup:+ values: dict[str, object] = {"id": GROUP_ID,"tenant_id": TENANT_ID,"name": "Office",+ "description": "",+ "mode": "","allowed_cidrs": ["203.0.113.7/32"],- "version": "1",- "created_at": "2026-09-01T00:00:00Z",- "updated_at": "2026-09-01T00:00:00Z",- **overrides,+ "version": 1,+ "updated_by_account_id": "",+ "created_at": CREATED_AT,+ "updated_at": CREATED_AT,+ "used_by_count": 0,+ "used_by_app_ids": [],+ "enforcing_count": 0,}+ return saas.NetworkAccessGroup.model_validate({**values, **overrides})-def _binding_wire(**overrides: object) -> dict[str, object]:- return {+def _binding(**overrides: object) -> saas.AppNetworkAccessGroupBinding:+ values: dict[str, object] = {"id": GROUP_ID,"tenant_id": TENANT_ID,"app_id": APP_ID,- "version": "1",- "created_at": "2026-09-01T00:00:00Z",- "updated_at": "2026-09-01T00:00:00Z",- **overrides,+ "group_id": None,+ "version": 1,+ "updated_by_account_id": "",+ "created_at": CREATED_AT,+ "updated_at": CREATED_AT,+ "enabled": False,+ "access_points": [],}+ return saas.AppNetworkAccessGroupBinding.model_validate({**values, **overrides})-class RecordingHTTPClient(httpx.Client):- """Exercise httpx serialization while keeping all requests inside MockTransport."""-- def __init__(self) -> None:- self.response = httpx.Response(200, json={})- self.request_calls: list[object] = []- self.wire_requests: list[httpx.Request] = []- super().__init__(- transport=httpx.MockTransport(self._respond),- timeout=httpx.Timeout(30.0, connect=5.0),- trust_env=False,- )-- @override- def request(self, *args: object, **kwargs: object) -> httpx.Response:- self.request_calls.append(call(*args, **kwargs))- return cast(Callable[..., httpx.Response], super().request)(*args, **kwargs)-- def _respond(self, request: httpx.Request) -> httpx.Response:- self.wire_requests.append(request)- return httpx.Response(self.response.status_code, content=self.response.content, headers=self.response.headers)+def _app_config(binding: saas.AppNetworkAccessGroupBinding | None = None) -> saas.GetAppNetworkAccessGroupReply:+ return saas.GetAppNetworkAccessGroupReply(+ tenant_id=TENANT_ID, app_id=APP_ID, entitled=True, binding=binding, effective_enabled=False+ )-class GatewayFactory(Protocol):- def __call__(- self, *, base_url: str = "https://network-access.internal/v1/"- ) -> tuple[NetworkAccessGroupGateway, RecordingHTTPClient]: ...+def _ok(reply: BillingModel | dict[str, object]) -> httpx.Response:+ payload = reply.model_dump(mode="json") if isinstance(reply, BillingModel) else reply+ return httpx.Response(httpx.codes.OK, json=payload)@pytest.fixture-def gateway_factory() -> Generator[GatewayFactory]:- clients: list[RecordingHTTPClient] = []-- def create(- *, base_url: str = "https://network-access.internal/v1/"- ) -> tuple[NetworkAccessGroupGateway, RecordingHTTPClient]:- http_client = RecordingHTTPClient()- clients.append(http_client)- return (- NetworkAccessGroupGateway(- base_url=base_url,- fallback_base_url="https://billing.internal/v1",- secret_key="test-secret",- http_client=http_client,- ),- http_client,- )+def respond(monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]) -> Respond:+ """Answer every saas request with the latest `response`; the returned list records every request of the test."""+ monkeypatch.setenv("BILLING_API_URL", "https://billing.internal/v1")+ monkeypatch.setenv("BILLING_API_SECRET_KEY", "test-secret")+ config_overrides(NETWORK_ACCESS_API_URL="")- try:- yield create- finally:- for client in clients:- client.close()- assert client.is_closed---def test_network_access_requests_use_independent_api_url_when_configured(gateway_factory: GatewayFactory) -> None:- gateway, http_client = gateway_factory()- response = httpx.Response(httpx.codes.OK, json={"tenant_id": TENANT_ID, "entitled": True, "groups": list[object]()})- http_client.response = response-- gateway.list_groups(TENANT_ID, ACCOUNT_ID)-- assert http_client.request_calls == [- call(- "GET",- f"https://network-access.internal/v1/tenants/{TENANT_ID}/network-access-groups",- json=None,- params={"actor_account_id": ACCOUNT_ID},- headers=HEADERS,- follow_redirects=True,- )- ]+ requests: list[httpx.Request] = []+ def install(response: httpx.Response) -> list[httpx.Request]:+ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return response-def test_network_access_requests_fall_back_to_billing_api_url(gateway_factory: GatewayFactory) -> None:- gateway, http_client = gateway_factory(base_url="")- response = httpx.Response(httpx.codes.OK, json={"tenant_id": TENANT_ID, "entitled": True, "groups": list[object]()})- http_client.response = response+ monkeypatch.setattr(transport, "_http_client", httpx.Client(transport=httpx.MockTransport(handler)))+ return requests- gateway.list_groups(TENANT_ID, ACCOUNT_ID)+ return install- assert http_client.request_calls == [- call(- "GET",- f"https://billing.internal/v1/tenants/{TENANT_ID}/network-access-groups",- json=None,- params={"actor_account_id": ACCOUNT_ID},- headers=HEADERS,- follow_redirects=True,- )- ]+ ("configured", "expected"),+ [+ ("https://network-access.internal/v1/", "https://network-access.internal/v1"),+ (" ", "https://billing.internal/v1"),+ ],+)+def test_requests_use_network_access_url_and_fall_back_to_billing_url(+ respond: Respond, config_overrides: Callable[..., None], configured: str, expected: str+) -> None:+ config_overrides(NETWORK_ACCESS_API_URL=configured)+ requests = respond(_ok(saas.ListNetworkAccessGroupsReply(tenant_id=TENANT_ID, entitled=True, groups=[])))-def test_injected_http_client_keeps_timeout_and_remains_reusable(gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- client.response = httpx.Response(200, json={"tenant_id": TENANT_ID, "entitled": True, "groups": []})+ NetworkAccessGroupGateway().list_groups(TENANT_ID, ACCOUNT_ID)- gateway.list_groups(TENANT_ID, ACCOUNT_ID)-- first = client.wire_requests[0]- assert first.method == "GET"- assert str(first.url) == (- f"https://network-access.internal/v1/tenants/{TENANT_ID}/network-access-groups?actor_account_id={ACCOUNT_ID}"- )- assert first.headers["Billing-Api-Secret-Key"] == "test-secret"- assert first.headers["Content-Type"] == "application/json"- assert first.content == b""- assert first.extensions["timeout"] == {"connect": 5.0, "read": 30.0, "write": 30.0, "pool": 30.0}- assert not client.is_closed-- client.timeout = httpx.Timeout(8.0, connect=1.5)- gateway.list_groups(TENANT_ID, ACCOUNT_ID)-- assert len(client.wire_requests) == 2- assert client.wire_requests[1].extensions["timeout"] == {- "connect": 1.5,- "read": 8.0,- "write": 8.0,- "pool": 8.0,- }- assert not client.is_closed---def test_group_list_and_item_reads_use_authenticated_saas_endpoints(gateway_factory: GatewayFactory) -> None:- gateway, http_client = gateway_factory(base_url="")- http_client.response = httpx.Response(200, json={"tenant_id": TENANT_ID, "entitled": True, "groups": []})- list_result = gateway.list_groups(TENANT_ID, ACCOUNT_ID)- http_client.response = httpx.Response(200, json={"group": _group_wire()})- item_result = gateway.get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)-- assert list_result.groups == ()- assert item_result.id == GROUP_ID- assert http_client.request_calls == [- call(- "GET",- f"https://billing.internal/v1/tenants/{TENANT_ID}/network-access-groups",- json=None,- params={"actor_account_id": ACCOUNT_ID},- headers=HEADERS,- follow_redirects=True,- ),- call(- "GET",- f"https://billing.internal/v1/tenants/{TENANT_ID}/network-access-groups/{GROUP_ID}",- json=None,- params={"actor_account_id": ACCOUNT_ID},- headers=HEADERS,- follow_redirects=True,- ),- ]+ assert str(requests[0].url) == f"{expected}/tenants/{TENANT_ID}/network-access-groups?actorAccountId={ACCOUNT_ID}"+ assert requests[0].headers["Billing-Api-Secret-Key"] == "test-secret"-def test_group_mutations_inject_actor_and_use_expected_version(gateway_factory: GatewayFactory) -> None:- gateway, http_client = gateway_factory(base_url="")- http_client.response = httpx.Response(200, json={"group": _group_wire(version="1")})+def test_group_operations_send_actor_and_expected_version(respond: Respond) -> None:+ gateway = NetworkAccessGroupGateway()+ requests = respond(_ok(saas.NetworkAccessGroupReply(group=_group())))gateway.create_group(TENANT_ID,name="Office",@@ -213,77 +125,48 @@ def test_group_mutations_inject_actor_and_use_expected_version(gateway_factory:allowed_cidrs=["203.0.113.7/32"],actor_account_id=ACCOUNT_ID,)- http_client.response = httpx.Response(200, json={"group": _group_wire(version="2")})+ gateway.get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)gateway.update_group(TENANT_ID,GROUP_ID,name="Office",- description="Updated office egress",+ description="Updated",allowed_cidrs=["203.0.113.0/24"],expected_version=1,actor_account_id=ACCOUNT_ID,)- http_client.response = httpx.Response(200, json={"deleted": True})- gateway.delete_group(- TENANT_ID,- GROUP_ID,- expected_version=2,- actor_account_id=ACCOUNT_ID,- )-- assert http_client.request_calls == [- call(- "POST",- f"https://billing.internal/v1/tenants/{TENANT_ID}/network-access-groups",- json={- "name": "Office",- "description": "Office egress",- "allowed_cidrs": ["203.0.113.7/32"],- "actor_account_id": ACCOUNT_ID,- },- params=None,- headers=HEADERS,- follow_redirects=True,- ),- call(- "PUT",- f"https://billing.internal/v1/tenants/{TENANT_ID}/network-access-groups/{GROUP_ID}",- json={- "name": "Office",- "description": "Updated office egress",- "allowed_cidrs": ["203.0.113.0/24"],- "expected_version": 1,- "actor_account_id": ACCOUNT_ID,- },- params=None,- headers=HEADERS,- follow_redirects=True,- ),- call(- "DELETE",- f"https://billing.internal/v1/tenants/{TENANT_ID}/network-access-groups/{GROUP_ID}",- json=None,- params={"expected_version": 2, "actor_account_id": ACCOUNT_ID},- headers=HEADERS,- follow_redirects=True,- ),+ respond(_ok(saas.DeleteNetworkAccessGroupReply(deleted=True)))+ assert gateway.delete_group(TENANT_ID, GROUP_ID, expected_version=2, actor_account_id=ACCOUNT_ID) is True++ group_path = f"/v1/tenants/{TENANT_ID}/network-access-groups/{GROUP_ID}"+ assert [(request.method, request.url.path) for request in requests] == [+ ("POST", f"/v1/tenants/{TENANT_ID}/network-access-groups"),+ ("GET", group_path),+ ("PUT", group_path),+ ("DELETE", group_path),]+ assert json.loads(requests[0].content) == {+ "tenantId": TENANT_ID,+ "name": "Office",+ "description": "Office egress",+ "mode": "",+ "allowedCidrs": ["203.0.113.7/32"],+ "actorAccountId": ACCOUNT_ID,+ }+ assert requests[1].url.params["actorAccountId"] == ACCOUNT_ID+ assert json.loads(requests[2].content)["expectedVersion"] == 1+ assert dict(requests[3].url.params) == {"expectedVersion": "2", "actorAccountId": ACCOUNT_ID}-def test_app_config_read_and_atomic_write_use_tenant_and_app_path(gateway_factory: GatewayFactory) -> None:- gateway, http_client = gateway_factory(base_url="")- http_client.response = httpx.Response(- 200, json={"tenant_id": TENANT_ID, "app_id": APP_ID, "entitled": True, "binding": None}- )+def test_app_operations_use_tenant_and_app_paths(respond: Respond) -> None:+ gateway = NetworkAccessGroupGateway()+ requests = respond(_ok(_app_config()))gateway.get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID)- http_client.response = httpx.Response(- 200,- json={- "binding": _binding_wire(- enabled=True, group_id=GROUP_ID, access_points=["webapp", "service_api"], version="1"- )- },+ respond(+ _ok(saas.GetAppNetworkAccessGroupStatusReply(entitled=True, configured=True, enabled=True, access_points=[])))+ gateway.get_app_status(TENANT_ID, APP_ID, ACCOUNT_ID)+ respond(_ok(saas.PutAppNetworkAccessGroupReply(binding=_binding(), effective_enabled=True)))gateway.update_app_binding(TENANT_ID,APP_ID,@@ -293,156 +176,198 @@ def test_app_config_read_and_atomic_write_use_tenant_and_app_path(gateway_factorexpected_version=0,actor_account_id=ACCOUNT_ID,)- http_client.response = httpx.Response(- 200,- json={- "binding": _binding_wire(- enabled=False, group_id=GROUP_ID, access_points=["webapp", "service_api"], version="2"- )- },- )- gateway.update_app_binding(- TENANT_ID,- APP_ID,- enabled=False,- group_id=GROUP_ID,- access_points=["webapp", "service_api"],- expected_version=1,- actor_account_id=ACCOUNT_ID,- )-- endpoint = f"https://billing.internal/v1/tenants/{TENANT_ID}/apps/{APP_ID}/network-access-group"- assert http_client.request_calls == [- call(- "GET",- endpoint,- json=None,- params={"actor_account_id": ACCOUNT_ID},- headers=HEADERS,- follow_redirects=True,- ),- call(- "PUT",- endpoint,- json={- "enabled": True,- "group_id": GROUP_ID,- "access_points": ["webapp", "service_api"],- "expected_version": 0,- "actor_account_id": ACCOUNT_ID,- },- params=None,- headers=HEADERS,- follow_redirects=True,- ),- call(- "PUT",- endpoint,- json={- "enabled": False,- "group_id": GROUP_ID,- "access_points": ["webapp", "service_api"],- "expected_version": 1,- "actor_account_id": ACCOUNT_ID,- },- params=None,- headers=HEADERS,- follow_redirects=True,- ),+ respond(_ok(saas.CleanupAppNetworkAccessGroupBindingReply(deleted=True)))+ assert gateway.cleanup_app_binding(TENANT_ID, APP_ID) is True++ app_path = f"/v1/tenants/{TENANT_ID}/apps/{APP_ID}/network-access-group"+ assert [(request.method, request.url.path) for request in requests] == [+ ("GET", app_path),+ ("GET", f"{app_path}/status"),+ ("PUT", app_path),+ ("DELETE", f"{app_path}-binding"),]+ assert json.loads(requests[2].content) == {+ "tenantId": TENANT_ID,+ "appId": APP_ID,+ "groupId": GROUP_ID,+ "expectedVersion": 0,+ "actorAccountId": ACCOUNT_ID,+ "enabled": True,+ "accessPoints": ["webapp", "service_api"],+ }+ assert requests[3].url.params == httpx.QueryParams()-def test_app_lifecycle_cleanup_uses_internal_secret_endpoint(gateway_factory: GatewayFactory) -> None:- gateway, http_client = gateway_factory(base_url="")- response = httpx.Response(httpx.codes.OK, json={"deleted": True})- http_client.response = response+def test_replies_map_to_service_records(respond: Respond) -> None:+ gateway = NetworkAccessGroupGateway()+ wire = _group(version="9007199254740993", used_by_count="1", used_by_app_ids=[APP_ID], enforcing_count="1")+ respond(_ok(saas.ListNetworkAccessGroupsReply(tenant_id=TENANT_ID, entitled=True, groups=[wire])))- result = gateway.cleanup_app_binding(TENANT_ID, APP_ID)+ groups = gateway.list_groups(TENANT_ID, ACCOUNT_ID)- assert result is True- assert http_client.request_calls == [- call(- "DELETE",- f"https://billing.internal/v1/tenants/{TENANT_ID}/apps/{APP_ID}/network-access-group-binding",- json=None,- params=None,- headers=HEADERS,- follow_redirects=True,- )- ]+ assert groups.entitled is True+ (group,) = groups.groups+ assert group.version == 9007199254740993+ assert (group.used_by_count, group.enforcing_count, group.app_ids) == (1, 1, (APP_ID,))+ assert group.allowed_cidrs == ("203.0.113.7/32",)+ assert group.created_at == CREATED_AT++[email protected]("group_id", [GROUP_ID, None, ""])+def test_binding_group_reference_is_none_when_unset(respond: Respond, group_id: str | None) -> None:+ respond(_ok(_app_config(_binding(group_id=group_id, enabled=True, access_points=["webapp", "future_scope"]))))++ binding = NetworkAccessGroupGateway().get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID).binding++ assert binding is not None+ assert binding.group_id == (group_id or None)+ assert binding.access_points == ("webapp", "future_scope")+++def test_snake_case_proto_names_are_accepted(respond: Respond) -> None:+ respond(_ok({"group": _group(used_by_app_ids=[APP_ID]).model_dump(mode="json", by_alias=False)}))++ assert NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID).app_ids == (APP_ID,)@pytest.mark.parametrize("status_code", [400, 403, 404, 409, 500, 503])-def test_network_access_group_request_preserves_upstream_status(- status_code: int, gateway_factory: GatewayFactory-) -> None:- gateway, _ = gateway_factory()- response = httpx.Response(status_code)- with (- patch.object(gateway, "_send_http_request", return_value=response),- pytest.raises(NetworkAccessGroupUpstreamError) as exc_info,- ):- gateway._send_request("GET", "/groups")+def test_error_status_is_preserved(respond: Respond, status_code: int) -> None:+ respond(httpx.Response(status_code))++ with pytest.raises(NetworkAccessGroupUpstreamError) as exc_info:+ NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)assert exc_info.value.status_code == status_code+ assert exc_info.value.reason is None-def test_network_access_group_request_preserves_upstream_reason(gateway_factory: GatewayFactory) -> None:- gateway, _ = gateway_factory()- response = httpx.Response(- httpx.codes.CONFLICT, json={"code": 409, "reason": "NETWORK_ACCESS_VERSION_CONFLICT", "message": "internal"}- )- with (- patch.object(gateway, "_send_http_request", return_value=response),- pytest.raises(NetworkAccessGroupUpstreamError) as exc_info,- ):- gateway._send_request("DELETE", "/groups/id")+ ("body", "reason"),+ [+ (+ {"code": 409, "reason": "NETWORK_ACCESS_VERSION_CONFLICT", "message": "internal"},+ "NETWORK_ACCESS_VERSION_CONFLICT",+ ),+ ({"code": "not-a-code", "reason": "NETWORK_ACCESS_GROUP_NAME_CONFLICT"}, "NETWORK_ACCESS_GROUP_NAME_CONFLICT"),+ ({"reason": 409}, None),+ (["NETWORK_ACCESS_VERSION_CONFLICT"], None),+ ],+)+def test_error_reason_is_preserved_when_it_is_a_string(respond: Respond, body: object, reason: str | None) -> None:+ respond(httpx.Response(httpx.codes.CONFLICT, json=body))++ with pytest.raises(NetworkAccessGroupUpstreamError) as exc_info:+ NetworkAccessGroupGateway().delete_group(TENANT_ID, GROUP_ID, expected_version=1, actor_account_id=ACCOUNT_ID)assert exc_info.value.status_code == httpx.codes.CONFLICT- assert exc_info.value.reason == "NETWORK_ACCESS_VERSION_CONFLICT"+ assert exc_info.value.reason == reason-def test_network_access_group_request_maps_transport_failure_to_service_unavailable(- gateway_factory: GatewayFactory,-) -> None:- gateway, _ = gateway_factory()- request = httpx.Request("GET", "https://network-access.internal/v1/groups")+def test_unreachable_upstream_maps_to_service_unavailable() -> None:with (patch.object(- gateway,- "_send_http_request",- side_effect=httpx.ConnectError("unavailable", request=request),+ saas,+ "network_access_policy_list_network_access_groups",+ side_effect=BillingUpstreamUnavailableError("GET failed"),),pytest.raises(NetworkAccessGroupUpstreamError) as exc_info,):- gateway._send_request("GET", "/groups")+ NetworkAccessGroupGateway().list_groups(TENANT_ID, ACCOUNT_ID)assert exc_info.value.status_code == httpx.codes.SERVICE_UNAVAILABLE+ assert exc_info.value.reason is None-def test_network_access_group_request_rejects_non_object_response(gateway_factory: GatewayFactory) -> None:- gateway, _ = gateway_factory()- response = httpx.Response(httpx.codes.OK, json=list[object]())- with (- patch.object(gateway, "_send_http_request", return_value=response),- pytest.raises(NetworkAccessGroupInvalidResponseError),- ):- gateway._send_request("GET", "/groups")[email protected]("body", [b"{", b"\xff", b"", b"[]"])+def test_unparsable_reply_is_invalid(respond: Respond, body: bytes) -> None:+ respond(httpx.Response(httpx.codes.OK, content=body, headers={"Content-Type": "application/json"}))+ with pytest.raises(NetworkAccessGroupInvalidResponseError) as exc_info:+ NetworkAccessGroupGateway().list_groups(TENANT_ID, ACCOUNT_ID)++ assert isinstance(exc_info.value.__cause__, BillingUpstreamInvalidResponseError)[email protected]("body", [b"{", b"\xff", b""])-def test_invalid_json_is_rejected_after_transport_receives_raw_response(- gateway_factory: GatewayFactory, body: bytes-) -> None:- gateway, client = gateway_factory()- client.response = httpx.Response(200, content=body, headers={"Content-Type": "application/json"})- with pytest.raises(NetworkAccessGroupInvalidResponseError) as raised:- gateway._send_request("GET", "/groups")+VALID_GROUP = _group().model_dump(mode="json")- assert isinstance(raised.value.__cause__, ValueError)- assert len(client.wire_requests) == 1- assert not client.is_closed++ "group",+ [+ None,+ {"version": "1"},+ {**VALID_GROUP, "version": "invalid"},+ {**VALID_GROUP, "version": "1.5"},+ {**VALID_GROUP, "name": 1},+ {**VALID_GROUP, "allowedCidrs": "203.0.113.7/32"},+ {**VALID_GROUP, "usedByCount": "0.5"},+ {**VALID_GROUP, "createdAt": "yesterday"},+ ],+)+def test_replies_failing_the_schema_are_invalid(respond: Respond, group: dict[str, object] | None) -> None:+ respond(_ok({"group": group}))++ with pytest.raises(NetworkAccessGroupInvalidResponseError):+ NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)+++ "overrides",+ [+ {"id": ""},+ {"tenant_id": ""},+ {"allowed_cidrs": []},+ {"allowed_cidrs": ["203.0.113.7/32"] * 101},+ {"version": 0},+ {"version": -1},+ {"version": 2**63},+ {"used_by_count": -1},+ {"enforcing_count": -1},+ {"enforcing_count": 2**63},+ {"used_by_app_ids": [""]},+ ],+)+def test_groups_breaking_service_invariants_are_invalid(respond: Respond, overrides: dict[str, object]) -> None:+ respond(_ok(saas.NetworkAccessGroupReply(group=_group(**overrides))))++ with pytest.raises(NetworkAccessGroupInvalidResponseError):+ NetworkAccessGroupGateway().get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)++[email protected]("overrides", [{"id": ""}, {"app_id": ""}, {"version": 0}, {"version": 2**63}])+def test_bindings_breaking_service_invariants_are_invalid(respond: Respond, overrides: dict[str, object]) -> None:+ respond(_ok(_app_config(_binding(**overrides))))++ with pytest.raises(NetworkAccessGroupInvalidResponseError):+ NetworkAccessGroupGateway().get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID)+++def test_binding_update_without_binding_is_invalid(respond: Respond) -> None:+ respond(_ok(saas.PutAppNetworkAccessGroupReply(binding=None, effective_enabled=True)))++ with pytest.raises(NetworkAccessGroupInvalidResponseError):+ NetworkAccessGroupGateway().update_app_binding(+ TENANT_ID,+ APP_ID,+ enabled=True,+ group_id=GROUP_ID,+ access_points=["webapp"],+ expected_version=1,+ actor_account_id=ACCOUNT_ID,+ )++[email protected]("field", ["entitled", "effectiveEnabled", "enabled"])[email protected]("value", ["maybe", 2, None])+def test_non_boolean_flags_are_invalid(respond: Respond, field: str, value: object) -> None:+ payload = _app_config(_binding()).model_dump(mode="json")+ target = payload["binding"] if field == "enabled" else payload+ assert isinstance(target, dict)+ target[field] = value+ respond(_ok(payload))++ with pytest.raises(NetworkAccessGroupInvalidResponseError):+ NetworkAccessGroupGateway().get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID)@pytest.mark.parametrize("plan", [CloudPlan.PROFESSIONAL, CloudPlan.TEAM])@@ -489,174 +414,3 @@ def test_billing_entitlement_gateway_does_not_mask_unexpected_value_error() -> Npytest.raises(ValueError, match="programming error"),):gateway.is_paid_plan(TENANT_ID)---def test_protojson_defaults_are_materialized_before_service_boundary(gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- client.response = httpx.Response(200, json={"tenantId": TENANT_ID})- groups = gateway.list_groups(TENANT_ID, ACCOUNT_ID)- assert groups.entitled is False- assert groups.groups == ()-- for binding in (None, _binding_wire()):- client.response = httpx.Response(200, json={"tenantId": TENANT_ID, "appId": APP_ID, "binding": binding})- result = gateway.get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID)- assert result.entitled is False- assert result.effective_enabled is False- if binding is None:- assert result.binding is None- else:- assert result.binding is not None- assert result.binding.enabled is False- assert result.binding.access_points == ()- assert result.binding.group_id is None-- client.response = httpx.Response(200, json={"tenantId": TENANT_ID, "appId": APP_ID})- assert gateway.get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID).binding is None- client.response = httpx.Response(200, json={})- assert gateway.cleanup_app_binding(TENANT_ID, APP_ID) is False---def test_policy_protojson_aliases_and_count_defaults_are_decoded_once(gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- wire = {- "id": GROUP_ID,- "tenantId": TENANT_ID,- "name": "Office",- "allowedCidrs": ["203.0.113.7/32"],- "version": "9007199254740993",- "usedByAppIds": [APP_ID],- "createdAt": "2026-09-01T00:00:00Z",- "updatedAt": "2026-09-01T00:00:00Z",- }- response = httpx.Response(200, json={"group": wire})- client.response = response- result = gateway.get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)- assert result.version == 9007199254740993- assert result.used_by_count == 1 # Legacy replies without a count retain the reference fallback.- assert result.enforcing_count == 0- assert result.allowed_cidrs == ("203.0.113.7/32",)- assert result.app_ids == (APP_ID,)- assert result.description == ""- assert result.updated_by_account_id is None- assert "enforcing_count" not in wire--[email protected]("alias", ["group_id", "groupId", "policy_id", "policyId"])[email protected]("group_id", [GROUP_ID, None, ""])-def test_binding_policy_aliases_and_nullable_references(- alias: str, group_id: str | None, gateway_factory: GatewayFactory-) -> None:- gateway, client = gateway_factory()- response = httpx.Response(- 200, json={"tenantId": TENANT_ID, "appId": APP_ID, "binding": _binding_wire(**{alias: group_id})}- )- client.response = response- binding = gateway.get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID).binding- assert binding is not None- assert binding.group_id == (group_id or None)---def test_unknown_scopes_reach_service_without_aliases_or_mutable_payload(gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- scopes = ["webapp", "future_scope", "trigger"]- response = httpx.Response(- 200,- json={- "effectiveEnabled": True,- "binding": _binding_wire(enabled=True, policyId=GROUP_ID, accessPoints=scopes),- },- )- client.response = response- result = gateway.update_app_binding(- TENANT_ID,- APP_ID,- enabled=True,- group_id=GROUP_ID,- access_points=["webapp"],- expected_version=1,- actor_account_id=ACCOUNT_ID,- )- assert result.binding.access_points == ("webapp", "future_scope", "trigger")- assert result.binding.group_id == GROUP_ID- assert result.effective_enabled is True- scopes.clear()- assert result.binding.access_points == ("webapp", "future_scope", "trigger")--[email protected]("value", [True, False, 1.0, "1.5", "invalid", 0, -1, 2**63, str(2**63)])-def test_invalid_versions_are_rejected_at_gateway(value: object, gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- response = httpx.Response(200, json={"group": _group_wire(version=value)})- client.response = response- with pytest.raises(NetworkAccessGroupInvalidResponseError):- gateway.get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)--[email protected]("version", [1, "1", 2**63 - 1, str(2**63 - 1)])-def test_int64_versions_do_not_lose_precision(version: int | str, gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- response = httpx.Response(200, json={"group": _group_wire(version=version)})- client.response = response- assert gateway.get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID).version == int(version)--[email protected]("field", ["entitled", "effective_enabled", "enabled"])[email protected]("value", ["false", "true", 0, 1, None])-def test_wire_flags_are_strict_booleans(field: str, value: object, gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- binding = _binding_wire()- payload: dict[str, object] = {"tenant_id": TENANT_ID, "app_id": APP_ID, "binding": binding}- (binding if field == "enabled" else payload)[field] = value- response = httpx.Response(200, json=payload)- client.response = response- with pytest.raises(NetworkAccessGroupInvalidResponseError):- gateway.get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID)--[email protected]("alias", ["groupId", "policy_id", "policyId"])-def test_conflicting_policy_aliases_fail_instead_of_selecting_one(alias: str, gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- response = httpx.Response(- 200,- json={- "tenant_id": TENANT_ID,- "app_id": APP_ID,- "binding": _binding_wire(group_id=GROUP_ID, **{alias: APP_ID}),- },- )- client.response = response- with pytest.raises(NetworkAccessGroupInvalidResponseError):- gateway.get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID)- client.response = httpx.Response(- 200,- json={- "tenant_id": TENANT_ID,- "app_id": APP_ID,- "binding": _binding_wire(group_id=GROUP_ID, **{alias: GROUP_ID}),- },- )- binding = gateway.get_app_binding(TENANT_ID, APP_ID, ACCOUNT_ID).binding- assert binding is not None- assert binding.group_id == GROUP_ID--[email protected]("payload", [{}, {"group": None}, {"group": {"version": "1"}}])-def test_existing_policy_identity_fields_are_never_fabricated(- payload: dict[str, object], gateway_factory: GatewayFactory-) -> None:- gateway, client = gateway_factory()- response = httpx.Response(200, json=payload)- client.response = response- with pytest.raises(NetworkAccessGroupInvalidResponseError):- gateway.get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)--[email protected]("field", ["used_by_count", "enforcing_count"])[email protected]("value", [True, 0.0, "0.5", -1])-def test_invalid_policy_counts_are_rejected(field: str, value: object, gateway_factory: GatewayFactory) -> None:- gateway, client = gateway_factory()- response = httpx.Response(200, json={"group": _group_wire(**{field: value})})- client.response = response- with pytest.raises(NetworkAccessGroupInvalidResponseError):- gateway.get_group(TENANT_ID, GROUP_ID, ACCOUNT_ID)diff --git a/api/tests/unit_tests/services/test_operation_service.py b/api/tests/unit_tests/services/test_operation_service.pyindex dffded658eb..e01c4bd437d 100644--- a/api/tests/unit_tests/services/test_operation_service.py+++ b/api/tests/unit_tests/services/test_operation_service.py@@ -1,122 +1,61 @@-from typing import Any-from unittest.mock import MagicMock, patch+"""OperationService delegates to the generated saas client; HTTP behavior is covered in billing_client."""-import httpx-import pytest--from services.operation_service import OPERATION_REQUEST_TIMEOUT, OperationService---class TestOperationService:- """Test suite for OperationService"""-- # ===== Internal Method Tests =====-- @patch("httpx.request")- def test_should_call_with_correct_parameters_when__send_request_invoked(- self, mock_request: MagicMock, monkeypatch: pytest.MonkeyPatch- ):- """Test that _send_request calls httpx.request with the correct URL, headers, and data"""- # Arrange- monkeypatch.setattr(OperationService, "base_url", "https://billing.example")- monkeypatch.setattr(OperationService, "secret_key", "s3cr3t")-- mock_response = MagicMock()- mock_response.json.return_value = {"status": "success"}- mock_request.return_value = mock_response-- method = "POST"- endpoint = "/test_endpoint"- json_data = {"key": "value"}+from unittest.mock import patch- # Act- result = OperationService._send_request(method, endpoint, json=json_data)-- # Assert- assert result == {"status": "success"}-- # Verify call parameters- expected_url = "https://billing.example/test_endpoint"- mock_request.assert_called_once()- args, kwargs = mock_request.call_args- assert args[0] == method- assert args[1] == expected_url- assert kwargs["json"] == json_data- assert kwargs["headers"]["Billing-Api-Secret-Key"] == "s3cr3t"- assert kwargs["headers"]["Content-Type"] == "application/json"- assert kwargs["timeout"] == OPERATION_REQUEST_TIMEOUT-- @patch("httpx.request")- def test_should_propagate_httpx_error_when__send_request_raises(- self, mock_request: MagicMock, monkeypatch: pytest.MonkeyPatch- ):- """Test that _send_request handles httpx raising an error"""- # Arrange- monkeypatch.setattr(OperationService, "base_url", "https://billing.example")- mock_request.side_effect = httpx.RequestError("network error")-- # Act & Assert- with pytest.raises(httpx.RequestError):- OperationService._send_request("POST", "/test")-- # ===== Public Method Tests =====+import pytest- @pytest.mark.parametrize(- ("utm_info", "expected_params"),- [- (- {- "utm_source": "google",- "utm_medium": "cpc",- "utm_campaign": "spring_sale",- "utm_content": "ad_1",- "utm_term": "ai_agent",- },- {- "tenant_id": "tenant-123",- "utm_source": "google",- "utm_medium": "cpc",- "utm_campaign": "spring_sale",- "utm_content": "ad_1",- "utm_term": "ai_agent",- },+from services.billing_client import saas+from services.operation_service import OperationService, UtmInfo++TENANT_ID = "tenant-123"+++ ("utm_info", "expected"),+ [+ (+ {+ "utm_source": "google",+ "utm_medium": "cpc",+ "utm_campaign": "spring_sale",+ "utm_content": "ad_1",+ "utm_term": "ai_agent",+ },+ saas.TenantUtmRequest(+ tenant_id=TENANT_ID,+ utm_source="google",+ utm_medium="cpc",+ utm_campaign="spring_sale",+ utm_content="ad_1",+ utm_term="ai_agent",),- (- {}, # Empty utm_info- {- "tenant_id": "tenant-123",- "utm_source": "",- "utm_medium": "",- "utm_campaign": "",- "utm_content": "",- "utm_term": "",- },+ ),+ (+ {},+ saas.TenantUtmRequest(+ tenant_id=TENANT_ID, utm_source="", utm_medium="", utm_campaign="", utm_content="", utm_term=""),- (- {"utm_source": "newsletter"}, # Partial utm_info- {- "tenant_id": "tenant-123",- "utm_source": "newsletter",- "utm_medium": "",- "utm_campaign": "",- "utm_content": "",- "utm_term": "",- },+ ),+ (+ {"utm_source": "newsletter"},+ saas.TenantUtmRequest(+ tenant_id=TENANT_ID,+ utm_source="newsletter",+ utm_medium="",+ utm_campaign="",+ utm_content="",+ utm_term="",),- ],- )- @patch.object(OperationService, "_send_request")- def test_should_map_parameters_correctly_when_record_utm_called(- self, mock_send: MagicMock, utm_info: dict[str, Any], expected_params: dict[str, Any]- ):- """Test that record_utm correctly maps utm_info to parameters and calls _send_request"""- # Arrange- tenant_id = "tenant-123"- mock_send.return_value = {"status": "recorded"}-- # Act- result = OperationService.record_utm(tenant_id, utm_info)-- # Assert- assert result == {"status": "recorded"}- mock_send.assert_called_once_with("POST", "/tenant_utms", params=expected_params)+ ),+ ],+)+def test_record_utm_defaults_missing_fields_to_empty_strings(+ utm_info: UtmInfo, expected: saas.TenantUtmRequest+) -> None:+ reply = saas.TenantUtmReply(result="ok")++ with patch.object(saas, "utm_record_tenant_utm", return_value=reply) as record:+ result = OperationService.record_utm(TENANT_ID, utm_info)++ assert result is reply+ record.assert_called_once_with(body=expected)