zerobom-azure 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ # Virtual environments
2
+ .venv/
3
+ .venv-*/
4
+ venv/
5
+
6
+ # Python / build artifacts
7
+ __pycache__/
8
+ *.py[cod]
9
+ *$py.class
10
+ *.egg-info/
11
+ dist/
12
+ build/
13
+ site/
14
+ htmlcov/
15
+ .coverage
16
+ .coverage.*
17
+
18
+ # Caches, local state, and generated reports
19
+ .cache/
20
+ .mypy_cache/
21
+ .pytest_cache/
22
+ .ruff_cache/
23
+ .zerobom/
24
+ .zerobom-reports/
25
+ *.sqlite
26
+ *.sqlite3
27
+ *.sqlite-wal
28
+ *.sqlite-shm
29
+
30
+ # Local secrets & environment overrides
31
+ .env
32
+ .env.*
33
+ !.env.example
@@ -0,0 +1,200 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, in at least one of the following
110
+ places: within a NOTICE text file distributed as part of the
111
+ Derivative Works; within the Source form or documentation,
112
+ if provided along with the Derivative Works; or, within a
113
+ display generated by the Derivative Works, if and wherever such
114
+ third-party notices appear. The contents of the NOTICE file
115
+ are for informational purposes only and do not modify the
116
+ License. You may add Your own attribution notices within
117
+ Derivative Works that You distribute, alongside or as an
118
+ addendum to the NOTICE text file from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright notice to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, or distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate gross
155
+ negligence) or agreed to in writing, shall any Contributor be liable
156
+ to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any kind arising as a result of
158
+ this License or out of the use or inability to use the Work (including
159
+ but not limited to damages for loss of goodwill, work stoppage,
160
+ computer failure or malfunction, or any and all other commercial
161
+ damages or losses), even if such Contributor has been advised of the
162
+ possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ APPENDIX: How to apply the Apache License to your work.
178
+
179
+ To apply the Apache License to your work, attach the following
180
+ boilerplate notice, with the fields enclosed by brackets "[]"
181
+ replaced with your own identifying information. (Don't include
182
+ the brackets!) The text should be enclosed in the appropriate
183
+ comment syntax for the file format. We also recommend that a
184
+ file or class name and description of purpose be included on the
185
+ same "printed page" as the copyright notice for easier
186
+ identification within third-party archives.
187
+
188
+ Copyright 2026 zerobom Contributors
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: zerobom-azure
3
+ Version: 0.1.0
4
+ Summary: Azure Resource Graph and Blob Storage SBOM inventory backend plugins for zerobom.
5
+ Project-URL: Homepage, https://zerobom.dev/
6
+ Project-URL: Documentation, https://zerobom.dev/backends/
7
+ Project-URL: Repository, https://github.com/zerobom-dev/zerobom
8
+ Project-URL: Issues, https://github.com/zerobom-dev/zerobom/issues
9
+ Author: zerobom Contributors
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: azure,blob-storage,pre-cve,resource-graph,sbom,zerobom
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Information Technology
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Security
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: azure-identity>=1.19
25
+ Requires-Dist: httpx>=0.27
26
+ Requires-Dist: zerobom<0.2.0,>=0.1.0
27
+ Provides-Extra: identity
28
+ Description-Content-Type: text/markdown
29
+
30
+ # zerobom-azure
31
+
32
+ Microsoft Azure inventory backend plugins for [`zerobom`](https://github.com/zerobom-dev/zerobom), integrating via standard `zerobom.backends` entry points:
33
+
34
+ - **`azure_resource_graph`**: Queries Microsoft Defender for Cloud / Azure Resource Graph (`microsoft.security/softwareinventories`) across `subscriptions`, `management_groups`, or `tenant_scope=true` with quota-aware `$skipToken` pacing, `osPlatform` distro mapping, and sovereign cloud presets (`commercial`, `usgov`, `china`).
35
+ - **`azure_blob_sbom`**: Streams plain or `.gz`-compressed CycloneDX (1.4–1.6) and SPDX (2.2–2.3) JSON SBOMs concurrently from Azure Blob Storage containers while skipping `Archive`-tier blobs cleanly.
36
+
37
+ > **Coverage note:** `azure_resource_graph` (`microsoft.security/softwareinventories`) covers VM and Arc-enabled server software inventories via Defender TVM; pair it with `oci_sbom` (for ACR container images) or `azure_blob_sbom` for exported container SBOMs.
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ uvx "zerobom[azure]" scan --osv advisory.osv.json --backend azure_resource_graph --backend-opt subscriptions=00000000-0000-0000-0000-000000000000
43
+ ```
44
+
45
+ Or install into an existing project environment:
46
+
47
+ ```bash
48
+ pip install "zerobom[azure]"
49
+ ```
50
+
51
+ `azure-identity` (`DefaultAzureCredential`) is included directly and refreshes bearer tokens automatically across long-lived `watch` sessions.
52
+
53
+ ## Usage Examples
54
+
55
+ ### Azure Resource Graph (`azure_resource_graph`)
56
+
57
+ ```bash
58
+ zerobom scan \
59
+ --osv advisory.osv.json \
60
+ --backend azure_resource_graph \
61
+ --backend-opt subscriptions=11111111-1111-1111-1111-111111111111 \
62
+ --format sarif > results.sarif
63
+ ```
64
+
65
+ Scope options (mutually exclusive):
66
+ - `--backend-opt subscriptions=<guid>` (or `ZEROBOM_AZURE_SUBSCRIPTION_ID`)
67
+ - `--backend-opt management_groups=<mg-id>`
68
+ - `--backend-opt tenant_scope=true`
69
+
70
+ Authentication priority:
71
+ 1. Explicit `access_token` option
72
+ 2. `ZEROBOM_AZURE_ACCESS_TOKEN` or `ZEROBOM_AZURE_TOKEN`
73
+ 3. Automatic `DefaultAzureCredential` (disable fallback with `--backend-opt use_default_credential=false`)
74
+
75
+ Least-privilege RBAC role: **Reader** (plus **Security Reader** on target subscriptions/management groups).
76
+
77
+ ### Azure Blob Storage SBOM Prefix (`azure_blob_sbom`)
78
+
79
+ ```bash
80
+ zerobom scan \
81
+ --osv advisory.osv.json \
82
+ --backend azure_blob_sbom \
83
+ --backend-opt account_name=corpsbomstore \
84
+ --backend-opt container=sboms \
85
+ --backend-opt prefix=prod/
86
+ ```
87
+
88
+ Supports Entra bearer auth (`DefaultAzureCredential` / token env vars) or SAS tokens (`sas_token` / `ZEROBOM_AZURE_SAS_TOKEN`, preserving literal `+` characters in `sig=`).
89
+
90
+ Least-privilege RBAC role: **Storage Blob Data Reader**.
91
+
92
+ ## Documentation & License
93
+
94
+ - Documentation: https://zerobom.dev/backends/
95
+ - License: Apache-2.0
@@ -0,0 +1,66 @@
1
+ # zerobom-azure
2
+
3
+ Microsoft Azure inventory backend plugins for [`zerobom`](https://github.com/zerobom-dev/zerobom), integrating via standard `zerobom.backends` entry points:
4
+
5
+ - **`azure_resource_graph`**: Queries Microsoft Defender for Cloud / Azure Resource Graph (`microsoft.security/softwareinventories`) across `subscriptions`, `management_groups`, or `tenant_scope=true` with quota-aware `$skipToken` pacing, `osPlatform` distro mapping, and sovereign cloud presets (`commercial`, `usgov`, `china`).
6
+ - **`azure_blob_sbom`**: Streams plain or `.gz`-compressed CycloneDX (1.4–1.6) and SPDX (2.2–2.3) JSON SBOMs concurrently from Azure Blob Storage containers while skipping `Archive`-tier blobs cleanly.
7
+
8
+ > **Coverage note:** `azure_resource_graph` (`microsoft.security/softwareinventories`) covers VM and Arc-enabled server software inventories via Defender TVM; pair it with `oci_sbom` (for ACR container images) or `azure_blob_sbom` for exported container SBOMs.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ uvx "zerobom[azure]" scan --osv advisory.osv.json --backend azure_resource_graph --backend-opt subscriptions=00000000-0000-0000-0000-000000000000
14
+ ```
15
+
16
+ Or install into an existing project environment:
17
+
18
+ ```bash
19
+ pip install "zerobom[azure]"
20
+ ```
21
+
22
+ `azure-identity` (`DefaultAzureCredential`) is included directly and refreshes bearer tokens automatically across long-lived `watch` sessions.
23
+
24
+ ## Usage Examples
25
+
26
+ ### Azure Resource Graph (`azure_resource_graph`)
27
+
28
+ ```bash
29
+ zerobom scan \
30
+ --osv advisory.osv.json \
31
+ --backend azure_resource_graph \
32
+ --backend-opt subscriptions=11111111-1111-1111-1111-111111111111 \
33
+ --format sarif > results.sarif
34
+ ```
35
+
36
+ Scope options (mutually exclusive):
37
+ - `--backend-opt subscriptions=<guid>` (or `ZEROBOM_AZURE_SUBSCRIPTION_ID`)
38
+ - `--backend-opt management_groups=<mg-id>`
39
+ - `--backend-opt tenant_scope=true`
40
+
41
+ Authentication priority:
42
+ 1. Explicit `access_token` option
43
+ 2. `ZEROBOM_AZURE_ACCESS_TOKEN` or `ZEROBOM_AZURE_TOKEN`
44
+ 3. Automatic `DefaultAzureCredential` (disable fallback with `--backend-opt use_default_credential=false`)
45
+
46
+ Least-privilege RBAC role: **Reader** (plus **Security Reader** on target subscriptions/management groups).
47
+
48
+ ### Azure Blob Storage SBOM Prefix (`azure_blob_sbom`)
49
+
50
+ ```bash
51
+ zerobom scan \
52
+ --osv advisory.osv.json \
53
+ --backend azure_blob_sbom \
54
+ --backend-opt account_name=corpsbomstore \
55
+ --backend-opt container=sboms \
56
+ --backend-opt prefix=prod/
57
+ ```
58
+
59
+ Supports Entra bearer auth (`DefaultAzureCredential` / token env vars) or SAS tokens (`sas_token` / `ZEROBOM_AZURE_SAS_TOKEN`, preserving literal `+` characters in `sig=`).
60
+
61
+ Least-privilege RBAC role: **Storage Blob Data Reader**.
62
+
63
+ ## Documentation & License
64
+
65
+ - Documentation: https://zerobom.dev/backends/
66
+ - License: Apache-2.0
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "zerobom-azure"
7
+ version = "0.1.0"
8
+ description = "Azure Resource Graph and Blob Storage SBOM inventory backend plugins for zerobom."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.11"
13
+ authors = [
14
+ { name = "zerobom Contributors" },
15
+ ]
16
+ keywords = ["zerobom", "azure", "resource-graph", "blob-storage", "sbom", "pre-cve"]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Intended Audience :: Developers",
20
+ "Intended Audience :: Information Technology",
21
+ "License :: OSI Approved :: Apache Software License",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Security",
27
+ "Typing :: Typed",
28
+ ]
29
+ dependencies = [
30
+ "zerobom>=0.1.0,<0.2.0",
31
+ "httpx>=0.27",
32
+ "azure-identity>=1.19",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://zerobom.dev/"
37
+ Documentation = "https://zerobom.dev/backends/"
38
+ Repository = "https://github.com/zerobom-dev/zerobom"
39
+ Issues = "https://github.com/zerobom-dev/zerobom/issues"
40
+
41
+ [project.optional-dependencies]
42
+ identity = []
43
+
44
+ [project.entry-points."zerobom.backends"]
45
+ azure_resource_graph = "zerobom_azure.resource_graph:AzureResourceGraphBackend"
46
+ azure_blob_sbom = "zerobom_azure.blob_sbom:AzureBlobSbomBackend"
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["src/zerobom_azure"]
50
+
51
+ [tool.hatch.build.targets.sdist]
52
+ include = [
53
+ "/src/zerobom_azure",
54
+ "/README.md",
55
+ "/LICENSE",
56
+ "/pyproject.toml",
57
+ ]
@@ -0,0 +1,9 @@
1
+ """Azure inventory backend plugins for ``zerobom``."""
2
+
3
+ from zerobom_azure.blob_sbom import AzureBlobSbomBackend
4
+ from zerobom_azure.resource_graph import AzureResourceGraphBackend
5
+
6
+ __all__ = [
7
+ "AzureBlobSbomBackend",
8
+ "AzureResourceGraphBackend",
9
+ ]
@@ -0,0 +1,218 @@
1
+ """Azure sovereign cloud presets and thread-safe auto-refreshing OAuth2 credentials."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import os
7
+ import threading
8
+ import time
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ from zerobom.backends import BackendConfigError, BackendQueryError
14
+ from zerobom.backends._http import validate_no_control_chars
15
+
16
+ AZURE_MGMT_SCOPE = "https://management.azure.com/.default"
17
+ AZURE_STORAGE_SCOPE = "https://storage.azure.com/.default"
18
+ _REFRESH_SKEW_SECONDS = 60.0
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class AzureCloudPreset:
23
+ """Regional and sovereign Azure cloud endpoints and Entra authorities."""
24
+
25
+ name: str
26
+ resource_manager_url: str
27
+ blob_endpoint_suffix: str
28
+ resource_manager_scope: str
29
+ storage_scope: str
30
+ authority: str
31
+
32
+
33
+ AZURE_CLOUD_PRESETS: dict[str, AzureCloudPreset] = {
34
+ "commercial": AzureCloudPreset(
35
+ name="commercial",
36
+ resource_manager_url="https://management.azure.com",
37
+ blob_endpoint_suffix="blob.core.windows.net",
38
+ resource_manager_scope="https://management.azure.com/.default",
39
+ storage_scope="https://storage.azure.com/.default",
40
+ authority="https://login.microsoftonline.com",
41
+ ),
42
+ "usgov": AzureCloudPreset(
43
+ name="usgov",
44
+ resource_manager_url="https://management.usgovcloudapi.net",
45
+ blob_endpoint_suffix="blob.core.usgovcloudapi.net",
46
+ resource_manager_scope="https://management.usgovcloudapi.net/.default",
47
+ storage_scope="https://storage.azure.com/.default",
48
+ authority="https://login.microsoftonline.us",
49
+ ),
50
+ "china": AzureCloudPreset(
51
+ name="china",
52
+ resource_manager_url="https://management.chinacloudapi.cn",
53
+ blob_endpoint_suffix="blob.core.chinacloudapi.cn",
54
+ resource_manager_scope="https://management.chinacloudapi.cn/.default",
55
+ storage_scope="https://storage.azure.com/.default",
56
+ authority="https://login.chinacloudapi.cn",
57
+ ),
58
+ }
59
+
60
+
61
+ def resolve_azure_cloud_preset(cloud: str) -> AzureCloudPreset:
62
+ """Validate and resolve a named Azure cloud environment preset."""
63
+ cleaned = validate_no_control_chars(cloud, field_name="cloud", max_length=32).lower()
64
+ preset = AZURE_CLOUD_PRESETS.get(cleaned)
65
+ if preset is None:
66
+ valid = ", ".join(sorted(AZURE_CLOUD_PRESETS))
67
+ raise BackendConfigError(f"Invalid Azure cloud preset {cloud!r}; expected one of: {valid}.")
68
+ return preset
69
+
70
+
71
+ class AzureTokenProvider:
72
+ """Thread-safe Azure OAuth2 bearer token provider supporting ``DefaultAzureCredential``."""
73
+
74
+ def __init__(
75
+ self,
76
+ *,
77
+ access_token: str | None = None,
78
+ scope: str = AZURE_MGMT_SCOPE,
79
+ env_var: str = "ZEROBOM_AZURE_ACCESS_TOKEN",
80
+ use_default_credential: bool | None = None,
81
+ authority: str | None = None,
82
+ credential: Any | None = None,
83
+ time_fn: Callable[[], float] = time.time,
84
+ ) -> None:
85
+ """Initialize the Azure OAuth2 token provider.
86
+
87
+ Resolution priority (unless explicit ``credential`` test double is provided):
88
+ 1. Explicit ``access_token`` string (static).
89
+ 2. Environment variables ``env_var`` or ``ZEROBOM_AZURE_TOKEN`` (static).
90
+ 3. ``azure.identity.DefaultAzureCredential`` when ``use_default_credential`` is
91
+ ``True`` or ``None`` (auto-fallback). Setting ``use_default_credential=False``
92
+ disables fallback.
93
+
94
+ Raises:
95
+ BackendConfigError: If no credential source succeeds or validation fails.
96
+ """
97
+ if use_default_credential is not None and not isinstance(use_default_credential, bool):
98
+ raise BackendConfigError(
99
+ "Configuration option 'use_default_credential' must be a bool."
100
+ )
101
+
102
+ self._lock = threading.Lock()
103
+ self._scope = scope
104
+ self._time_fn = time_fn
105
+ self._static_token: str | None = None
106
+ self._credential: Any | None = None
107
+ self._cached_token: str | None = None
108
+ self._expires_on: float | None = None
109
+
110
+ if credential is not None:
111
+ self._credential = credential
112
+ self._acquire_initial_token()
113
+ return
114
+
115
+ if access_token is not None:
116
+ self._static_token = validate_no_control_chars(
117
+ access_token, field_name="access_token", max_length=8192
118
+ )
119
+ return
120
+
121
+ for candidate_env in (env_var, "ZEROBOM_AZURE_TOKEN"):
122
+ raw_env = os.environ.get(candidate_env)
123
+ if raw_env and raw_env.strip():
124
+ self._static_token = validate_no_control_chars(
125
+ raw_env, field_name=candidate_env, max_length=8192
126
+ )
127
+ return
128
+
129
+ if use_default_credential is False:
130
+ raise BackendConfigError(
131
+ f"Azure backend requires 'access_token', {env_var}, ZEROBOM_AZURE_TOKEN, "
132
+ "or use_default_credential=True."
133
+ )
134
+
135
+ try:
136
+ azure_identity = importlib.import_module("azure.identity")
137
+ cred = (
138
+ azure_identity.DefaultAzureCredential(authority=authority)
139
+ if authority is not None
140
+ else azure_identity.DefaultAzureCredential()
141
+ )
142
+ except ImportError as exc:
143
+ raise BackendConfigError(
144
+ "Azure credential fallback requires 'azure-identity' to be installed."
145
+ ) from exc
146
+ except Exception as exc:
147
+ raise BackendConfigError(
148
+ f"Failed to initialize Azure DefaultAzureCredential: {exc}"
149
+ ) from exc
150
+
151
+ self._credential = cred
152
+ self._acquire_initial_token()
153
+
154
+ def _acquire_initial_token(self) -> None:
155
+ """Acquire initial token eagerly so missing/invalid credentials fail at startup."""
156
+ try:
157
+ self.get_token()
158
+ except BackendQueryError as exc:
159
+ raise BackendConfigError(str(exc)) from exc
160
+
161
+ @property
162
+ def can_refresh(self) -> bool:
163
+ """Return True if backed by a refreshable ``DefaultAzureCredential``."""
164
+ return self._credential is not None
165
+
166
+ def get_token(self, *, force_refresh: bool = False) -> str:
167
+ """Return a valid Azure OAuth2 bearer token, refreshing before expiry."""
168
+ if self._static_token is not None:
169
+ return self._static_token
170
+
171
+ with self._lock:
172
+ cred = self._credential
173
+ if cred is None:
174
+ raise BackendConfigError("Azure credentials are not configured.")
175
+
176
+ now = self._time_fn()
177
+ expired = (
178
+ self._expires_on is not None and (now + _REFRESH_SKEW_SECONDS) >= self._expires_on
179
+ )
180
+ if force_refresh or self._cached_token is None or expired:
181
+ try:
182
+ token_obj = cred.get_token(self._scope)
183
+ except Exception as exc:
184
+ raise BackendQueryError(
185
+ f"Failed to acquire/refresh Azure token via DefaultAzureCredential: {exc}"
186
+ ) from exc
187
+
188
+ token_str = validate_no_control_chars(
189
+ getattr(token_obj, "token", None),
190
+ field_name="azure_default_credential_token",
191
+ max_length=8192,
192
+ )
193
+ expires_on = getattr(token_obj, "expires_on", None)
194
+ self._cached_token = token_str
195
+ self._expires_on = (
196
+ float(expires_on)
197
+ if isinstance(expires_on, (int, float)) and not isinstance(expires_on, bool)
198
+ else None
199
+ )
200
+
201
+ return self._cached_token
202
+
203
+
204
+ def resolve_azure_bearer_token(
205
+ access_token: str | None,
206
+ *,
207
+ scope: str = AZURE_MGMT_SCOPE,
208
+ env_var: str = "ZEROBOM_AZURE_ACCESS_TOKEN",
209
+ use_default_credential: bool | None = None,
210
+ ) -> str:
211
+ """Resolve an initial bounded Azure OAuth2 bearer credential without control characters."""
212
+ provider = AzureTokenProvider(
213
+ access_token=access_token,
214
+ scope=scope,
215
+ env_var=env_var,
216
+ use_default_credential=use_default_credential,
217
+ )
218
+ return provider.get_token()