Skip to content

armgit / dify

Public Imported from GitHub
0

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.

refactor(api): enforce that only the billing client reaches billing and saas (#45145)

yyh34c94386237a
diff --git a/api/.ruff.toml b/api/.ruff.toml
index 1e24ca0831c..f7ee8ce1ee2 100644
--- a/api/.ruff.toml
+++ b/api/.ruff.toml
@@ -71,6 +71,9 @@ ignore = [
"libs/gmpy2_pkcs10aep_cipher.py" = [
"N803", # invalid-argument-name
]
+"services/billing_client/*" = [
+ "TID251", # the billing client is the one place that reads billing settings and calls the transport
+]
"tests/*" = [
"T201", # allow print in tests,
"S110", # allow ignoring exceptions in tests code (currently)
@@ -82,5 +85,20 @@ msg = "Use Pydantic payload/query models instead of reqparse."
[lint.flake8-tidy-imports.banned-api."flask_restx.reqparse.RequestParser"]
msg = "Use Pydantic payload/query models instead of reqparse."
+[lint.flake8-tidy-imports.banned-api."configs.dify_config.BILLING_API_URL"]
+msg = "Only services.billing_client reaches billing/saas. Call a generated operation from services.billing_client instead."
+
+[lint.flake8-tidy-imports.banned-api."configs.dify_config.BILLING_API_SECRET_KEY"]
+msg = "Only services.billing_client reaches billing/saas. Call a generated operation from services.billing_client instead."
+
+[lint.flake8-tidy-imports.banned-api."configs.dify_config.BILLING_QUOTA_API_URL"]
+msg = "Only services.billing_client reaches billing/saas. Call a generated operation from services.billing_client instead."
+
+[lint.flake8-tidy-imports.banned-api."configs.dify_config.NETWORK_ACCESS_API_URL"]
+msg = "Only services.billing_client reaches billing/saas. Call a generated operation from services.billing_client instead."
+
+[lint.flake8-tidy-imports.banned-api."services.billing_client.transport.request"]
+msg = "Allowlist the operation in api/dev/generate_billing_client.py, regenerate, and call the generated function."
+
[lint.isort]
known-first-party = ["graphon"]
diff --git a/api/AGENTS.md b/api/AGENTS.md
index 7d6c1fb7a18..803ec1dd018 100644
--- a/api/AGENTS.md
+++ b/api/AGENTS.md
@@ -40,6 +40,7 @@ changes, and CI checks the PR against its target revision.
## Billing And SaaS Calls
- Call billing and saas only through the generated functions in `services/billing_client`; do not hand-write paths or response types.
+- Ruff's banned-api rule (TID251) enforces this: outside `services/billing_client`, reading the billing URL and secret settings or calling `transport.request` fails lint.
- To call a new endpoint, add it to `ALLOWED_OPERATIONS` in `dev/generate_billing_client.py` and rerun that script against a dify-saas checkout. Never edit the generated modules or snapshots by hand.
## Typing Best Practises
diff --git a/api/configs/feature/__init__.py b/api/configs/feature/__init__.py
index 2ac8c78f331..774605b2cd3 100644
--- a/api/configs/feature/__init__.py
+++ b/api/configs/feature/__init__.py
@@ -426,6 +426,23 @@ class EndpointConfig(BaseSettings):
TRIGGER_URL: str = Field(description="Template url for triggers", default="http://localhost:5001")
+ BILLING_API_URL: str = Field(
+ description="Internal billing and SaaS API base URL, including the API version path; Cloud edition only. "
+ "Only services.billing_client may read it",
+ default="",
+ )
+
+ BILLING_API_SECRET_KEY: str = Field(
+ description="Shared secret sent to the billing and SaaS APIs. Only services.billing_client may read it",
+ default="",
+ )
+
+ BILLING_QUOTA_API_URL: str = Field(
+ description="Optional billing API base URL for quota requests; falls back to BILLING_API_URL. "
+ "Only services.billing_client may read it",
+ default="",
+ )
+
NETWORK_ACCESS_API_URL: str = Field(
description="Optional internal SaaS API base URL for network access policy requests; "
"falls back to BILLING_API_URL",
diff --git a/api/services/billing_client/transport.py b/api/services/billing_client/transport.py
index 4cc485cf7f7..d81619ac721 100644
--- a/api/services/billing_client/transport.py
+++ b/api/services/billing_client/transport.py
@@ -1,6 +1,7 @@
"""HTTP transport shared by the generated billing and saas operations.
-Reuses the pooled client, auth header, and connection retry of `services.billing_service`.
+This is the only module that reads the billing URLs and secret, and only the generated modules
+call `request`; ruff's banned-api rule (TID251) rejects both anywhere else.
Network failures, timeouts, throttling, and 5xx raise `BillingUpstreamUnavailableError`;
any other non-200 status or an enforced response that fails model validation raises
`BillingUpstreamInvalidResponseError`. For a non-200 status, the error carries the status
@@ -17,7 +18,6 @@ each item before returning it.
import json
import logging
-import os
import types
from collections.abc import Mapping
from enum import StrEnum
@@ -92,9 +92,9 @@ class BillingModel(BaseModel):
def _base_url(upstream: Upstream) -> str:
- billing_url = os.environ.get("BILLING_API_URL", "BILLING_API_URL")
+ billing_url = dify_config.BILLING_API_URL
if upstream == Upstream.BILLING_QUOTA:
- return os.environ.get("BILLING_QUOTA_API_URL") or billing_url
+ return dify_config.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
@@ -109,7 +109,7 @@ def _base_url(upstream: Upstream) -> str:
def _send(method: HTTPMethod, url: str, *, params: Mapping[str, QueryValue], json: object | None) -> httpx.Response:
headers = {
"Content-Type": "application/json",
- "Billing-Api-Secret-Key": os.environ.get("BILLING_API_SECRET_KEY", "BILLING_API_SECRET_KEY"),
+ "Billing-Api-Secret-Key": dify_config.BILLING_API_SECRET_KEY,
}
return _http_client.request(method, url, params=params, json=json, headers=headers, follow_redirects=True)
diff --git a/api/services/billing_portal_service.py b/api/services/billing_portal_service.py
index 601e61de66b..972fd54b718 100644
--- a/api/services/billing_portal_service.py
+++ b/api/services/billing_portal_service.py
@@ -1,15 +1,16 @@
"""Application service for Console Billing portal links."""
from collections.abc import Callable
-from typing import TypedDict
+from typing import Protocol
from machinery.context import RequestContext
from services.account_errors import AccountNotFoundError
from services.account_ports import AccountRepository
-class BillingPortalLink(TypedDict):
- url: str
+class BillingPortalLink(Protocol):
+ @property
+ def url(self) -> str: ...
class BillingPortalService:
diff --git a/api/services/billing_service.py b/api/services/billing_service.py
index 7ee9286e24f..d500806ae30 100644
--- a/api/services/billing_service.py
+++ b/api/services/billing_service.py
@@ -7,8 +7,6 @@ from pydantic import ValidationError
from extensions.ext_redis import redis_client
from services.billing_client import billing, saas
-from services.billing_portal_service import BillingPortalLink
-from services.compliance_download_service import ComplianceDownloadLink
logger = logging.getLogger(__name__)
@@ -133,11 +131,10 @@ class BillingService:
@classmethod
def get_subscription(
cls, plan: str, interval: str, prefilled_email: str = "", tenant_id: str = ""
- ) -> BillingPortalLink:
- reply = billing.subscription_get_subscription_payment_link(
+ ) -> billing.GetSubscriptionPaymentLinkReply:
+ return billing.subscription_get_subscription_payment_link(
plan=plan, interval=interval, prefilled_email=prefilled_email, tenant_id=tenant_id
)
- return {"url": reply.url}
@classmethod
@deprecated("Only used by the deprecated model-provider checkout endpoint.")
@@ -149,9 +146,8 @@ class BillingService:
)
@classmethod
- def get_invoices(cls, prefilled_email: str = "", tenant_id: str = "") -> BillingPortalLink:
- reply = billing.invoice_get_invoices(prefilled_email=prefilled_email, tenant_id=tenant_id)
- return {"url": reply.url}
+ def get_invoices(cls, prefilled_email: str = "", tenant_id: str = "") -> billing.GetInvoicesReply:
+ return billing.invoice_get_invoices(prefilled_email=prefilled_email, tenant_id=tenant_id)
@classmethod
def delete_account(cls, account_id: str) -> saas.DeleteAccountReply:
@@ -219,13 +215,12 @@ class BillingService:
tenant_id: str,
ip: str,
device_info: str,
- ) -> ComplianceDownloadLink:
- reply = billing.compliance_download_compliance_document(
+ ) -> billing.DownloadComplianceDocumentReply:
+ return billing.compliance_download_compliance_document(
body=billing.DownloadComplianceDocumentReq(
doc_name=doc_name, account_id=account_id, tenant_id=tenant_id, ip_address=ip, device_info=device_info
)
)
- return {"url": reply.url}
@classmethod
def clean_billing_info_cache(cls, tenant_id: str) -> None:
diff --git a/api/services/compliance_download_service.py b/api/services/compliance_download_service.py
index f4b8701c9c4..f4653e5ef5c 100644
--- a/api/services/compliance_download_service.py
+++ b/api/services/compliance_download_service.py
@@ -1,14 +1,15 @@
"""Application service for compliance document downloads."""
from collections.abc import Callable
-from typing import Protocol, TypedDict
+from typing import Protocol
from machinery.context import RequestContext
from services.errors.billing import ComplianceRateLimitExceededError
-class ComplianceDownloadLink(TypedDict):
- url: str
+class ComplianceDownloadLink(Protocol):
+ @property
+ def url(self) -> str: ...
class ComplianceDownloadRateLimiter(Protocol):
diff --git a/api/tests/unit_tests/controllers/console/billing/test_billing.py b/api/tests/unit_tests/controllers/console/billing/test_billing.py
index ea509ee8f03..e562a33067d 100644
--- a/api/tests/unit_tests/controllers/console/billing/test_billing.py
+++ b/api/tests/unit_tests/controllers/console/billing/test_billing.py
@@ -13,6 +13,7 @@ from controllers.console.billing.error import (
)
from enums import CloudPlan
from machinery.context import RequestContext
+from services.billing_client import billing
from services.errors.billing import (
BillingUpstreamInvalidResponseError,
BillingUpstreamUnavailableError,
@@ -56,7 +57,9 @@ class TestBillingPortal:
resource = Subscription()
method = unwrap(resource.get)
query = SubscriptionQuery(plan=CloudPlan.PROFESSIONAL, interval="month")
- billing_portal.get_subscription.return_value = {"url": "https://billing.example.com/checkout"}
+ billing_portal.get_subscription.return_value = billing.GetSubscriptionPaymentLinkReply(
+ url="https://billing.example.com/checkout"
+ )
with app.test_request_context("/billing/subscription"):
result = method(resource, query, request_context)
@@ -76,7 +79,7 @@ class TestBillingPortal:
) -> None:
resource = Invoices()
method = unwrap(resource.get)
- billing_portal.get_invoices.return_value = {"url": "https://billing.example.com/portal"}
+ billing_portal.get_invoices.return_value = billing.GetInvoicesReply(url="https://billing.example.com/portal")
with app.test_request_context("/billing/invoices"):
result = method(resource, request_context)
diff --git a/api/tests/unit_tests/controllers/console/billing/test_compliance.py b/api/tests/unit_tests/controllers/console/billing/test_compliance.py
index fc39909bddb..167df938eb1 100644
--- a/api/tests/unit_tests/controllers/console/billing/test_compliance.py
+++ b/api/tests/unit_tests/controllers/console/billing/test_compliance.py
@@ -9,6 +9,7 @@ from flask import Flask
from controllers.console.billing.compliance import ComplianceApi, ComplianceDownloadQuery
from controllers.console.billing.error import ComplianceRateLimitError
from machinery.context import RequestContext
+from services.billing_client import billing
from services.errors.billing import ComplianceRateLimitExceededError
@@ -51,7 +52,9 @@ def test_get_compliance_download_link(
resource = ComplianceApi()
method = unwrap(resource.get)
query = ComplianceDownloadQuery(doc_name="SOC2_Type_II")
- compliance_downloads.get_link.return_value = {"url": "https://example.com/report", "ignored": True}
+ compliance_downloads.get_link.return_value = billing.DownloadComplianceDocumentReply(
+ url="https://example.com/report"
+ )
with (
app.test_request_context("/compliance/download", headers={"User-Agent": "test-agent"}),
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.py
index dcbc9f78ad5..a8eaf273cb4 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,4 +1,3 @@
-import os
from collections.abc import Callable, Generator, Mapping
from contextlib import contextmanager
from dataclasses import replace
@@ -1078,8 +1077,7 @@ def _typed_status_http_response(
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"),
+ config_overrides_context(NETWORK_ACCESS_API_URL="https://test.invalid", BILLING_API_SECRET_KEY="synthetic"),
):
gateway = NetworkAccessGroupGateway()
service = NetworkAccessGroupService(
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
index f19fca88930..f27ab593aa6 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_workflow.py
@@ -559,10 +559,9 @@ class TestWorkflowCases:
sqlite_session: Session,
config_overrides: Callable[..., None],
) -> None:
- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
+ config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD, BILLING_API_URL="http://billing/v1")
payload = builders.subscription_info().model_dump()
del payload["subscription"]["plan"]
- monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")
def unexpected_generation(*_args: object, **_kwargs: object) -> None:
pytest.fail("Invalid billing data must be rejected before workflow execution")
diff --git a/api/tests/unit_tests/services/billing_client/conftest.py b/api/tests/unit_tests/services/billing_client/conftest.py
index d72a59e2be7..5f626ce4a5f 100644
--- a/api/tests/unit_tests/services/billing_client/conftest.py
+++ b/api/tests/unit_tests/services/billing_client/conftest.py
@@ -9,10 +9,13 @@ type RespondWith = Callable[[httpx.Response], list[httpx.Request]]
@pytest.fixture(autouse=True)
-def billing_env(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")
- monkeypatch.setenv("BILLING_QUOTA_API_URL", "http://quota/v1")
- monkeypatch.setenv("BILLING_API_SECRET_KEY", "secret")
+def billing_config(config_overrides: Callable[..., None]) -> None:
+ config_overrides(
+ BILLING_API_URL="http://billing/v1",
+ BILLING_QUOTA_API_URL="http://quota/v1",
+ BILLING_API_SECRET_KEY="secret",
+ NETWORK_ACCESS_API_URL="",
+ )
@pytest.fixture
diff --git a/api/tests/unit_tests/services/billing_client/test_transport.py b/api/tests/unit_tests/services/billing_client/test_transport.py
index cd4b8469952..0e3a4026789 100644
--- a/api/tests/unit_tests/services/billing_client/test_transport.py
+++ b/api/tests/unit_tests/services/billing_client/test_transport.py
@@ -123,9 +123,13 @@ def test_request_error_is_retried_then_unavailable(monkeypatch: pytest.MonkeyPat
],
)
def test_upstream_selects_base_url(
- monkeypatch: pytest.MonkeyPatch, respond_with: RespondWith, upstream: Upstream, quota_url: str, expected: str
+ config_overrides: Callable[..., None],
+ respond_with: RespondWith,
+ upstream: Upstream,
+ quota_url: str,
+ expected: str,
) -> None:
- monkeypatch.setenv("BILLING_QUOTA_API_URL", quota_url)
+ config_overrides(BILLING_QUOTA_API_URL=quota_url)
requests = respond_with(httpx.Response(200, json={"ok": True}))
assert _get(upstream).ok is True
diff --git a/api/tests/unit_tests/services/retention/conversation/test_messages_clean_policy.py b/api/tests/unit_tests/services/retention/conversation/test_messages_clean_policy.py
index 3833b1d10f3..c5b4fd78c91 100644
--- a/api/tests/unit_tests/services/retention/conversation/test_messages_clean_policy.py
+++ b/api/tests/unit_tests/services/retention/conversation/test_messages_clean_policy.py
@@ -1,4 +1,5 @@
import datetime
+from collections.abc import Callable
from unittest.mock import MagicMock, patch
import httpx
@@ -52,7 +53,9 @@ class TestBillingSandboxPolicy:
policy = self._policy({})
assert policy.filter_message_ids([], {"app1": "t1"}) == []
- def test_malformed_billing_item_does_not_interrupt_other_tenants(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def test_malformed_billing_item_does_not_interrupt_other_tenants(
+ self, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+ ) -> None:
payload = {
"data": {
"t1": {"plan": "sandbox", "expiration_date": "-1"},
@@ -60,7 +63,7 @@ class TestBillingSandboxPolicy:
}
}
policy = BillingSandboxPolicy(plan_provider=BillingService.get_plan_bulk)
- monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")
+ config_overrides(BILLING_API_URL="http://billing/v1")
with httpx.Client(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload))) as client:
monkeypatch.setattr(transport, "_http_client", client)
diff --git a/api/tests/unit_tests/services/test_billing_portal_service.py b/api/tests/unit_tests/services/test_billing_portal_service.py
index b8a7c9e62c5..47c08a08ea3 100644
--- a/api/tests/unit_tests/services/test_billing_portal_service.py
+++ b/api/tests/unit_tests/services/test_billing_portal_service.py
@@ -8,6 +8,7 @@ from machinery.context import RequestContext
from models.account import Account
from repositories.account.repository import SQLAlchemyAccountRepository
from services.account_errors import AccountNotFoundError
+from services.billing_client import billing
from services.billing_portal_service import BillingPortalService
from tests.helpers.unit.model_factories import make_account
@@ -52,7 +53,8 @@ def test_get_subscription_loads_email_and_delegates(
mocker: MockerFixture,
) -> None:
lookup = mocker.spy(accounts, "get")
- get_subscription.return_value = {"url": "https://billing.example.com/checkout"}
+ link = billing.GetSubscriptionPaymentLinkReply(url="https://billing.example.com/checkout")
+ get_subscription.return_value = link
result = service.get_subscription(
_context(),
@@ -60,7 +62,7 @@ def test_get_subscription_loads_email_and_delegates(
interval="month",
)
- assert result == {"url": "https://billing.example.com/checkout"}
+ assert result is link
lookup.assert_called_once_with("account-1")
get_subscription.assert_called_once_with("professional", "month", "[email protected]", "workspace-1")
@@ -72,11 +74,12 @@ def test_get_invoices_loads_email_and_delegates(
mocker: MockerFixture,
) -> None:
lookup = mocker.spy(accounts, "get")
- get_invoices.return_value = {"url": "https://billing.example.com/portal"}
+ link = billing.GetInvoicesReply(url="https://billing.example.com/portal")
+ get_invoices.return_value = link
result = service.get_invoices(_context())
- assert result == {"url": "https://billing.example.com/portal"}
+ assert result is link
lookup.assert_called_once_with("account-1")
get_invoices.assert_called_once_with("[email protected]", "workspace-1")
diff --git a/api/tests/unit_tests/services/test_billing_service.py b/api/tests/unit_tests/services/test_billing_service.py
index d3fedcf55bf..cb810b557b0 100644
--- a/api/tests/unit_tests/services/test_billing_service.py
+++ b/api/tests/unit_tests/services/test_billing_service.py
@@ -1,5 +1,6 @@
"""BillingService delegates to the generated billing and saas clients; HTTP behavior is covered in billing_client."""
+from collections.abc import Callable
from unittest.mock import patch
import httpx
@@ -53,7 +54,7 @@ class TestBillingServiceSubscriptionInfo:
with patch.object(billing, "subscription_get_subscription_payment_link", return_value=reply) as get:
result = BillingService.get_subscription("professional", "month", "[email protected]", TENANT_ID)
- assert result == {"url": "https://payment.example.com/checkout"}
+ assert result is reply
get.assert_called_once_with(
plan="professional", interval="month", prefilled_email="[email protected]", tenant_id=TENANT_ID
)
@@ -64,7 +65,7 @@ class TestBillingServiceSubscriptionInfo:
with patch.object(billing, "invoice_get_invoices", return_value=reply) as get:
result = BillingService.get_invoices("[email protected]", TENANT_ID)
- assert result == {"url": "https://billing.example.com/invoices"}
+ assert result is reply
get.assert_called_once_with(prefilled_email="[email protected]", tenant_id=TENANT_ID)
def test_get_model_provider_payment_link_returns_the_generated_reply(self):
@@ -96,7 +97,9 @@ class TestBillingServiceSubscriptionInfo:
assert set(result) == set(tenant_ids[:200] + tenant_ids[400:])
assert result["tenant-0"] == builders.plan_item("team", 1735689600)
- def test_get_plan_bulk_skips_invalid_items_from_http_response(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def test_get_plan_bulk_skips_invalid_items_from_http_response(
+ self, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+ ) -> None:
payload = {
"data": {
"valid": {"plan": "sandbox", "expiration_date": "-1"},
@@ -107,7 +110,7 @@ class TestBillingServiceSubscriptionInfo:
"null_item": None,
}
}
- monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")
+ config_overrides(BILLING_API_URL="http://billing/v1")
with httpx.Client(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload))) as client:
monkeypatch.setattr(transport, "_http_client", client)
@@ -291,7 +294,7 @@ class TestBillingServiceAccountAndEducation:
with patch.object(billing, "compliance_download_compliance_document", return_value=reply) as download:
result = BillingService.get_compliance_download_link("soc2", ACCOUNT_ID, TENANT_ID, "127.0.0.1", "ua")
- assert result == {"url": "https://billing.example.com/compliance"}
+ assert result is reply
download.assert_called_once_with(
body=billing.DownloadComplianceDocumentReq(
doc_name="soc2", account_id=ACCOUNT_ID, tenant_id=TENANT_ID, ip_address="127.0.0.1", device_info="ua"
diff --git a/api/tests/unit_tests/services/test_compliance_download_service.py b/api/tests/unit_tests/services/test_compliance_download_service.py
index a5042ffac5a..7451ff710dd 100644
--- a/api/tests/unit_tests/services/test_compliance_download_service.py
+++ b/api/tests/unit_tests/services/test_compliance_download_service.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from unittest.mock import MagicMock
import httpx
@@ -6,7 +7,7 @@ import pytest
from extensions.ext_redis import RedisClientWrapper
from libs.helper import RateLimiter
from machinery.context import RequestContext
-from services.billing_client import transport
+from services.billing_client import billing, transport
from services.billing_service import BillingService
from services.compliance_download_service import ComplianceDownloadService
from services.errors.billing import (
@@ -65,7 +66,8 @@ def test_get_link_checks_limit_fetches_and_increments(
return 0
commands.side_effect = execute
- fetch_link.side_effect = lambda *_args: events.append("fetch") or {"url": "https://example.com/report"}
+ link = billing.DownloadComplianceDocumentReply(url="https://example.com/report")
+ fetch_link.side_effect = lambda *_args: events.append("fetch") or link
result = service.get_link(
request_context=request_context,
@@ -74,7 +76,7 @@ def test_get_link_checks_limit_fetches_and_increments(
device_info="test-agent",
)
- assert result == {"url": "https://example.com/report"}
+ assert result is link
assert events == ["check", "fetch", "increment"]
assert [call.args[0] for call in commands.call_args_list] == ["ZREMRANGEBYSCORE", "ZCARD", "ZADD", "EXPIRE"]
assert all(call.args[1] == "compliance:account-1:workspace-1" for call in commands.call_args_list)
@@ -132,6 +134,7 @@ def test_get_link_does_not_increment_after_fetch_failure(
@pytest.mark.parametrize("payload", [{}, {"url": None}, {"url": 123}])
def test_invalid_billing_response_does_not_consume_download_limit(
monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
rate_limiter: RateLimiter,
request_context: RequestContext,
redis_transport: tuple[RedisClientWrapper, MagicMock],
@@ -142,7 +145,7 @@ def test_invalid_billing_response_does_not_consume_download_limit(
service = ComplianceDownloadService(
fetch_link=BillingService.get_compliance_download_link, rate_limiter=rate_limiter
)
- monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")
+ config_overrides(BILLING_API_URL="http://billing/v1")
with httpx.Client(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload))) as client:
monkeypatch.setattr(transport, "_http_client", client)
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.py
index 1d40259a093..29d8d073e7b 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
@@ -79,9 +79,9 @@ def _ok(reply: BillingModel | dict[str, object]) -> httpx.Response:
@pytest.fixture
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="")
+ config_overrides(
+ BILLING_API_URL="https://billing.internal/v1", BILLING_API_SECRET_KEY="test-secret", NETWORK_ACCESS_API_URL=""
+ )
requests: list[httpx.Request] = []
diff --git a/api/tests/unit_tests/services/test_notification_gateway.py b/api/tests/unit_tests/services/test_notification_gateway.py
index 1b5f5af3645..e76f15029d2 100644
--- a/api/tests/unit_tests/services/test_notification_gateway.py
+++ b/api/tests/unit_tests/services/test_notification_gateway.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from unittest.mock import patch
import httpx
@@ -44,7 +45,9 @@ def test_get_active_maps_billing_proto_json_contract() -> None:
@pytest.mark.parametrize("localized_content", [None, {}])
def test_get_active_falls_back_to_english_for_empty_upstream_translation(
- monkeypatch: pytest.MonkeyPatch, localized_content: dict[str, str] | None
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
+ localized_content: dict[str, str] | None,
) -> None:
payload = {
"shouldShow": True,
@@ -70,7 +73,7 @@ def test_get_active_falls_back_to_english_for_empty_upstream_translation(
request_id="request-1", trace_id="trace-1", account_id="account-1", active_workspace_id="workspace-1"
)
service = NotificationService(notifications=BillingNotificationGateway())
- monkeypatch.setenv("BILLING_API_URL", "http://billing/v1")
+ config_overrides(BILLING_API_URL="http://billing/v1")
with httpx.Client(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload))) as client:
monkeypatch.setattr(transport, "_http_client", client)
result = service.get_active(context, "zh-Hans")