Examples and guides for using the OpenAI API
[chatgpt] Add SharePoint site allowlist Admin API example (#3032)
hmittal-oai86af94f494ee
diff --git a/examples/chatgpt/sharepoint_site_access/sharepoint_site_access.md b/examples/chatgpt/sharepoint_site_access/sharepoint_site_access.mdnew file mode 100644index 00000000..6be3ddae--- /dev/null+++ b/examples/chatgpt/sharepoint_site_access/sharepoint_site_access.md@@ -0,0 +1,256 @@+# Manage SharePoint site access with the ChatGPT Admin API++ChatGPT workspace administrators can restrict the SharePoint app to approved+SharePoint site collections. This example resolves ordinary SharePoint URLs into+Microsoft Graph site-collection identifiers, previews changes, and manages the+workspace allowlist through the ChatGPT Admin API.++The accompanying [administration script](sharepoint_site_access_admin.py) uses+only the Python standard library. It accepts multiple URLs or a CSV/text file,+deduplicates site collections, preserves existing allowlist entries when adding+new collections, supports optional idempotency keys, and requires explicit+confirmation before clearing a policy.++> An empty allowlist permits access to all SharePoint sites that the individual+> user can access. Clearing the allowlist removes the site restriction; it does+> not block every site. Personal OneDrive access is controlled separately and is+> not automatically restricted by the SharePoint site-collection allowlist.++## Prerequisites++- Python 3.10 or later.+- A ChatGPT workspace ID.+- A ChatGPT workspace Admin API key with the `chatgpt.enterprise.apps.write`+ permission.+- A Microsoft Graph access token that can resolve the relevant SharePoint sites,+ typically with the `Sites.Read.All` permission.+- SharePoint site-access controls and the Admin API enabled for your workspace.++A Microsoft Graph token is necessary only for commands that resolve SharePoint+URLs. Reading or clearing an existing allowlist requires only the ChatGPT+workspace Admin API key.++### Create a workspace Admin API key++1. Open the ChatGPT Admin Console and select your workspace.+2. Navigate to **Credentials** and select the **Admin keys** tab.+3. Create a key with **Restricted** permissions and set **Apps** to **Write**.+4. Store the key securely. Use it as the `CHATGPT_ADMIN_TOKEN` environment+ variable.++The required permission is `chatgpt.enterprise.apps.write`. An OpenAI API+Platform key and a Microsoft Graph token are different credentials and cannot+replace the ChatGPT workspace Admin API key.++In a Bash shell, prompt for each credential without writing its value into the+command or shell history:++```bash+read -r -s -p "ChatGPT workspace admin key: " CHATGPT_ADMIN_TOKEN+echo+export CHATGPT_ADMIN_TOKEN++read -r -s -p "Microsoft Graph access token: " MICROSOFT_GRAPH_TOKEN+echo+export MICROSOFT_GRAPH_TOKEN+```++Do not commit tokens, include them in screenshots, or copy them into shared+documents.++## Understand SharePoint site identifiers++Microsoft Graph resolves a SharePoint URL into an identifier containing three+comma-separated components:++```text+hostname,site-collection-GUID,site-GUID+```++For example, a request for `https://contoso.sharepoint.com/sites/Finance`+returns an identifier such as:++```json+{+ "id": "contoso.sharepoint.com,da60e844-ba1d-49bc-b4d4-d5e36bae9019,712a596e-90a1-49e3-9b48-bfa80bee8740",+ "webUrl": "https://contoso.sharepoint.com/sites/Finance"+}+```++The allowlist accepts the middle value:+`da60e844-ba1d-49bc-b4d4-d5e36bae9019`. This GUID identifies the entire+SharePoint site collection, so all sites or webs within that collection are+included. Different URLs can resolve to the same collection GUID. The allowlist+does not restrict individual subsites, folders, or files.++## Inspect SharePoint URLs++From the directory containing `sharepoint_site_access_admin.py`, run:++```bash+python3 sharepoint_site_access_admin.py inspect \+ --site-url https://contoso.sharepoint.com/sites/Finance \+ --site-url https://contoso.sharepoint.com/sites/Research+```++This command calls Microsoft Graph and prints each resolved site identifier and+the deduplicated collection GUIDs. It does not read or modify the ChatGPT+workspace allowlist. Tenant-root URLs and percent-encoded paths, such as+`https://contoso.sharepoint.com/sites/Finance%20Team`, are both supported.++## Prepare a list of sites++For larger updates, create a CSV file named `sites.csv` with a `site_url` or+`url` column:++```csv+site_url+https://contoso.sharepoint.com/sites/Finance+https://contoso.sharepoint.com/sites/Research+https://contoso.sharepoint.com/sites/Operations+```++A text file containing one URL per line also works. Blank lines and lines+starting with `#` are ignored, as are CSV rows without a site URL. Each request+supports up to 10,000 unique site collections.++## Read the existing allowlist++Replace `<workspace-id>` with your ChatGPT workspace UUID:++```bash+python3 sharepoint_site_access_admin.py list \+ --workspace-id <workspace-id>+```++The command reads the current policy from:++```text+GET https://api.chatgpt.com/v1/manage/workspaces/<workspace-id>/sharepoint/site-access/allow-list+```++## Preview and add site collections++Preview the URLs, resolved collection GUIDs, and existing policy before changing+workspace access:++```bash+python3 sharepoint_site_access_admin.py add \+ --workspace-id <workspace-id> \+ --sites-file sites.csv \+ --dry-run+```++When the preview is correct, add the approved site collections:++```bash+python3 sharepoint_site_access_admin.py add \+ --workspace-id <workspace-id> \+ --sites-file sites.csv+```++The script sends one additive `PUT` request:++```http+PUT /v1/manage/workspaces/<workspace-id>/sharepoint/site-access/allow-list+Authorization: Bearer <CHATGPT_ADMIN_TOKEN>+Content-Type: application/json++{+ "collection_guids": [+ "da60e844-ba1d-49bc-b4d4-d5e36bae9019"+ ]+}+```++Existing allowed collections are preserved. The script rejects an empty input+list, preventing an accidental empty `PUT` from clearing site restrictions.++## Remove a site collection++Resolve a site URL and remove its collection from the allowlist:++```bash+python3 sharepoint_site_access_admin.py remove \+ --workspace-id <workspace-id> \+ --site-url https://contoso.sharepoint.com/sites/Finance+```++The script sends one request for each unique collection GUID:++```text+DELETE /v1/manage/workspaces/<workspace-id>/sharepoint/site-access/allow-list/<collection-guid>+```++Use `--sites-file sites.csv` to remove multiple site collections. Add+`--dry-run` to review the identifiers and current policy before deleting them.++## Clear the allowlist++Preview the existing policy before removing every site restriction:++```bash+python3 sharepoint_site_access_admin.py clear \+ --workspace-id <workspace-id> \+ --dry-run+```++Clearing the allowlist restores access to all SharePoint sites permitted by each+user's Microsoft account. The script requires explicit confirmation:++```bash+python3 sharepoint_site_access_admin.py clear \+ --workspace-id <workspace-id> \+ --yes+```++The command sends:++```text+DELETE /v1/manage/workspaces/<workspace-id>/sharepoint/site-access/allow-list+```++## Retry a policy update safely++If idempotent policy writes are enabled for your workspace, provide a UUID when+adding, removing, or clearing site collections:++```bash+python3 sharepoint_site_access_admin.py add \+ --workspace-id <workspace-id> \+ --sites-file sites.csv \+ --idempotency-key 3b5e9666-f01e-4f8b-9336-e70b67c07cf5+```++The script sends this value in the optional `Idempotency-Key` header. Reuse the+same key only when retrying the same logical write. When a removal includes+multiple site collections, the script derives a distinct, stable key for each+collection so separate deletion requests do not conflict.++Do not provide `--idempotency-key` unless idempotency support is enabled for your+workspace. Omitting the option preserves the standard request behavior.++## Troubleshooting++- **HTTP 401 or 403:** Verify your workspace Admin API key, the selected+ workspace, the `chatgpt.enterprise.apps.write` permission, and whether the+ feature is enabled for your workspace.+- **Microsoft Graph HTTP 404:** Verify the SharePoint URL and the Microsoft+ Graph token's site permissions.+- **HTTP 409:** Review conflicting policy changes or confirm that an+ idempotency key was not reused for a different request.+- **HTTP 429 or 503:** The script retries throttling and temporary service+ failures up to two times.+- **Multiple URLs resolve to one GUID:** Those URLs belong to the same+ SharePoint site collection. The script adds or removes that collection once.++## Run the offline tests++The example includes tests that mock both Microsoft Graph and the ChatGPT Admin+API. No credentials or network access are required:++```bash+python3 -m unittest discover \+ -s examples/chatgpt/sharepoint_site_access \+ -p 'test_*.py'+```diff --git a/examples/chatgpt/sharepoint_site_access/sharepoint_site_access_admin.py b/examples/chatgpt/sharepoint_site_access/sharepoint_site_access_admin.pynew file mode 100755index 00000000..e3053f9e--- /dev/null+++ b/examples/chatgpt/sharepoint_site_access/sharepoint_site_access_admin.py@@ -0,0 +1,290 @@+#!/usr/bin/env python3+"""Resolve SharePoint URLs and manage a ChatGPT workspace site allowlist."""++from __future__ import annotations++import argparse+import csv+import json+import os+import time+import uuid+from pathlib import Path+from typing import Any+from urllib.error import HTTPError, URLError+from urllib.parse import quote, unquote, urlencode, urlparse+from urllib.request import Request, urlopen++CHATGPT_API_BASE_URL = "https://api.chatgpt.com"+MICROSOFT_GRAPH_BASE_URL = "https://graph.microsoft.com/v1.0"+MAX_COLLECTIONS_PER_REQUEST = 10_000+++def request_json(+ method: str,+ url: str,+ token: str,+ *,+ body: dict[str, Any] | None = None,+ idempotency_key: str | None = None,+) -> dict[str, Any]:+ """Send an authenticated JSON request and retry temporary failures."""+ headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}+ data = None+ if body is not None:+ headers["Content-Type"] = "application/json"+ data = json.dumps(body).encode("utf-8")+ if idempotency_key is not None:+ headers["Idempotency-Key"] = idempotency_key++ for attempt in range(3):+ try:+ request = Request(url, data=data, headers=headers, method=method)+ with urlopen(request, timeout=30) as response:+ payload = response.read()+ return json.loads(payload) if payload else {}+ except HTTPError as error:+ details = error.read().decode("utf-8", errors="replace")+ if error.code in {429, 503} and attempt < 2:+ time.sleep(2**attempt)+ continue+ raise SystemExit(+ f"{method} {url} failed: HTTP {error.code}: {details}"+ ) from error+ except URLError as error:+ if attempt < 2:+ time.sleep(2**attempt)+ continue+ raise SystemExit(f"{method} {url} failed: {error.reason}") from error++ raise AssertionError("unreachable")+++def resolve_sharepoint_url(site_url: str, graph_token: str) -> dict[str, str]:+ """Resolve a SharePoint site URL to its canonical site-collection GUID."""+ parsed = urlparse(site_url.strip())+ if parsed.scheme != "https" or not parsed.hostname or parsed.username:+ raise SystemExit(f"SharePoint URLs must be valid HTTPS URLs: {site_url!r}")++ site_path = unquote(parsed.path.rstrip("/") or "/")+ site_resource = f"{parsed.hostname}:{quote(site_path, safe='/')}"+ graph_url = f"{MICROSOFT_GRAPH_BASE_URL}/sites/{site_resource}?" + urlencode(+ {"$select": "id,webUrl"}+ )+ site = request_json("GET", graph_url, graph_token)+ site_id = str(site.get("id", ""))+ components = [component.strip() for component in site_id.split(",")]+ if len(components) != 3 or components[0].casefold() != parsed.hostname.casefold():+ raise SystemExit(+ f"Microsoft Graph returned an unexpected site ID for {site_url!r}"+ )++ try:+ collection_guid = str(uuid.UUID(components[1]))+ web_guid = str(uuid.UUID(components[2]))+ except ValueError as error:+ raise SystemExit(+ f"Microsoft Graph returned an invalid site ID: {site_id!r}"+ ) from error++ return {+ "requested_url": site_url,+ "resolved_url": str(site.get("webUrl", site_url)),+ "site_id": f"{components[0].casefold()},{collection_guid},{web_guid}",+ "collection_guid": collection_guid,+ }+++def read_site_urls(inline_urls: list[str], sites_file: str | None) -> list[str]:+ """Read unique site URLs from command-line arguments or a text/CSV file."""+ values = list(inline_urls)+ if sites_file:+ source = Path(sites_file)+ with source.open(encoding="utf-8-sig", newline="") as handle:+ if source.suffix.casefold() == ".csv":+ reader = csv.DictReader(handle)+ if not reader.fieldnames:+ raise SystemExit(+ "The CSV file must contain a site_url or url column"+ )+ field = next(+ (name for name in reader.fieldnames if name in {"site_url", "url"}),+ None,+ )+ if field is None:+ raise SystemExit(+ "The CSV file must contain a site_url or url column"+ )+ for row in reader:+ site_url = row.get(field)+ if site_url and site_url.strip():+ values.append(site_url.strip())+ else:+ values.extend(+ line.strip()+ for line in handle+ if line.strip() and not line.lstrip().startswith("#")+ )++ return list(dict.fromkeys(value.strip() for value in values if value.strip()))+++def mutation_key(+ seed: str | None, action: str, identifier: str | None = None+) -> str | None:+ """Return a stable optional key, unique for each multi-site deletion."""+ if seed is None:+ return None++ try:+ root = uuid.UUID(seed)+ except ValueError as error:+ raise SystemExit("--idempotency-key must be a valid UUID") from error++ return str(uuid.uuid5(root, f"{action}:{identifier}")) if identifier else str(root)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("action", choices=["inspect", "list", "add", "remove", "clear"])+ parser.add_argument("--workspace-id", help="ChatGPT workspace UUID")+ parser.add_argument(+ "--site-url",+ action="append",+ default=[],+ help="Repeat for multiple HTTPS SharePoint URLs",+ )+ parser.add_argument(+ "--sites-file",+ help="Text file with one URL per line or CSV with a site_url column",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Resolve and inspect without changing the allowlist",+ )+ parser.add_argument(+ "--yes",+ action="store_true",+ help="Confirm that clearing the allowlist restores access",+ )+ parser.add_argument(+ "--idempotency-key",+ help="Optional UUID for safe write retries when workspace support is enabled",+ )+ args = parser.parse_args()++ site_urls = read_site_urls(args.site_url, args.sites_file)+ if args.action in {"inspect", "add", "remove"} and not site_urls:+ raise SystemExit("Provide at least one --site-url or --sites-file")+ if args.action in {"list", "clear"} and site_urls:+ raise SystemExit(f"The {args.action} action does not accept site URLs")++ sites: list[dict[str, str]] = []+ if site_urls:+ graph_token = os.environ.get("MICROSOFT_GRAPH_TOKEN")+ if not graph_token:+ raise SystemExit(+ "Set MICROSOFT_GRAPH_TOKEN before resolving SharePoint URLs"+ )+ sites = [+ resolve_sharepoint_url(site_url, graph_token) for site_url in site_urls+ ]++ collection_guids = list(dict.fromkeys(site["collection_guid"] for site in sites))+ if len(collection_guids) > MAX_COLLECTIONS_PER_REQUEST:+ raise SystemExit(+ "A policy request cannot contain more than 10,000 unique site collections"+ )++ if args.action == "inspect":+ print(+ json.dumps({"sites": sites, "collection_guids": collection_guids}, indent=2)+ )+ return++ if not args.workspace_id:+ raise SystemExit("--workspace-id is required for allowlist operations")+ try:+ workspace_id = str(uuid.UUID(args.workspace_id))+ except ValueError as error:+ raise SystemExit("--workspace-id must be a valid UUID") from error++ admin_token = os.environ.get("CHATGPT_ADMIN_TOKEN")+ if not admin_token:+ raise SystemExit(+ "Set CHATGPT_ADMIN_TOKEN before inspecting or updating the allowlist"+ )++ allowlist_url = (+ f"{CHATGPT_API_BASE_URL}/v1/manage/workspaces/{workspace_id}"+ "/sharepoint/site-access/allow-list"+ )+ current_policy = request_json("GET", allowlist_url, admin_token)+ if args.action == "list":+ print(json.dumps(current_policy, indent=2))+ return++ if args.dry_run:+ print(+ json.dumps(+ {+ "dry_run": True,+ "workspace_id": workspace_id,+ "action": args.action,+ "sites": sites,+ "collection_guids": collection_guids,+ "current_policy": current_policy,+ },+ indent=2,+ )+ )+ return++ if args.action == "clear":+ if not args.yes:+ raise SystemExit(+ "Clearing the allowlist restores access to all permitted SharePoint sites; "+ "repeat with --yes to confirm"+ )+ response = request_json(+ "DELETE",+ allowlist_url,+ admin_token,+ idempotency_key=mutation_key(args.idempotency_key, "clear"),+ )+ elif args.action == "add":+ response = request_json(+ "PUT",+ allowlist_url,+ admin_token,+ body={"collection_guids": collection_guids},+ idempotency_key=mutation_key(args.idempotency_key, "add"),+ )+ else:+ response = current_policy+ for collection_guid in collection_guids:+ response = request_json(+ "DELETE",+ f"{allowlist_url}/{quote(collection_guid, safe='')}",+ admin_token,+ idempotency_key=mutation_key(+ args.idempotency_key, "remove", collection_guid+ ),+ )++ print(+ json.dumps(+ {+ "workspace_id": workspace_id,+ "action": args.action,+ "processed_count": len(collection_guids),+ "policy": response,+ },+ indent=2,+ )+ )+++if __name__ == "__main__":+ main()diff --git a/examples/chatgpt/sharepoint_site_access/test_sharepoint_site_access_admin.py b/examples/chatgpt/sharepoint_site_access/test_sharepoint_site_access_admin.pynew file mode 100644index 00000000..78dffcf4--- /dev/null+++ b/examples/chatgpt/sharepoint_site_access/test_sharepoint_site_access_admin.py@@ -0,0 +1,530 @@+"""Offline tests for the SharePoint site-collection allowlist example."""++from __future__ import annotations++import io+import json+import tempfile+import unittest+import uuid+from pathlib import Path+from unittest import mock+from urllib.error import HTTPError++import sharepoint_site_access_admin as site_access++WORKSPACE_ID = "2a171a87-9cc8-453c-b7c4-0e0316903eb3"+COLLECTION_GUID = "da60e844-ba1d-49bc-b4d4-d5e36bae9019"+WEB_GUID = "712a596e-90a1-49e3-9b48-bfa80bee8740"+SITE_URL = "https://contoso.sharepoint.com/sites/Finance"+IDEMPOTENCY_KEY = "3b5e9666-f01e-4f8b-9336-e70b67c07cf5"+ALLOWLIST_URL = (+ f"https://api.chatgpt.com/v1/manage/workspaces/{WORKSPACE_ID}"+ "/sharepoint/site-access/allow-list"+)+++def graph_site(*, web_guid: str = WEB_GUID) -> dict[str, str]:+ return {+ "id": f"contoso.sharepoint.com,{COLLECTION_GUID},{web_guid}",+ "webUrl": SITE_URL,+ }+++class RequestJsonTests(unittest.TestCase):+ @mock.patch.object(site_access, "urlopen")+ def test_sends_idempotency_header_only_when_provided(+ self, urlopen: mock.Mock+ ) -> None:+ response = mock.MagicMock()+ response.__enter__.return_value.read.return_value = b'{"ok":true}'+ urlopen.return_value = response++ site_access.request_json(+ "PUT",+ "https://api.chatgpt.com/example",+ "admin-token",+ body={"collection_guids": [COLLECTION_GUID]},+ idempotency_key=IDEMPOTENCY_KEY,+ )++ request = urlopen.call_args.args[0]+ self.assertEqual(request.get_header("Idempotency-key"), IDEMPOTENCY_KEY)++ site_access.request_json(+ "GET", "https://api.chatgpt.com/example", "admin-token"+ )++ request_without_key = urlopen.call_args.args[0]+ self.assertFalse(request_without_key.has_header("Idempotency-key"))++ @mock.patch.object(site_access.time, "sleep")+ @mock.patch.object(site_access, "urlopen")+ def test_retries_temporary_rate_limit(+ self, urlopen: mock.Mock, sleep: mock.Mock+ ) -> None:+ throttled = HTTPError(+ "https://api.chatgpt.com/example",+ 429,+ "Too Many Requests",+ None,+ io.BytesIO(b'{"error":"rate limited"}'),+ )+ response = mock.MagicMock()+ response.__enter__.return_value.read.return_value = b'{"ok":true}'+ urlopen.side_effect = [throttled, response]++ result = site_access.request_json(+ "GET", "https://api.chatgpt.com/example", "admin-token"+ )++ self.assertEqual(result, {"ok": True})+ self.assertEqual(urlopen.call_count, 2)+ sleep.assert_called_once_with(1)++ @mock.patch.object(site_access.time, "sleep")+ @mock.patch.object(site_access, "urlopen")+ def test_does_not_retry_authorization_failures(+ self, urlopen: mock.Mock, sleep: mock.Mock+ ) -> None:+ urlopen.side_effect = HTTPError(+ "https://api.chatgpt.com/example",+ 403,+ "Forbidden",+ None,+ io.BytesIO(b'{"error":"permission denied"}'),+ )++ with self.assertRaisesRegex(SystemExit, "HTTP 403"):+ site_access.request_json(+ "GET", "https://api.chatgpt.com/example", "admin-token"+ )++ urlopen.assert_called_once()+ sleep.assert_not_called()+++class ResolveSharePointUrlTests(unittest.TestCase):+ @mock.patch.object(site_access, "request_json")+ def test_resolves_and_normalizes_collection_guid(+ self, request_json: mock.Mock+ ) -> None:+ request_json.return_value = graph_site()++ result = site_access.resolve_sharepoint_url(SITE_URL, "graph-token")++ self.assertEqual(result["collection_guid"], COLLECTION_GUID)+ self.assertEqual(+ result["site_id"], f"contoso.sharepoint.com,{COLLECTION_GUID},{WEB_GUID}"+ )+ request_json.assert_called_once_with(+ "GET",+ "https://graph.microsoft.com/v1.0/sites/contoso.sharepoint.com:/sites/Finance"+ "?%24select=id%2CwebUrl",+ "graph-token",+ )++ @mock.patch.object(site_access, "request_json")+ def test_preserves_percent_encoded_sharepoint_paths(+ self, request_json: mock.Mock+ ) -> None:+ request_json.return_value = graph_site()++ site_access.resolve_sharepoint_url(+ "https://contoso.sharepoint.com/sites/Finance%20Team", "graph-token"+ )++ request_json.assert_called_once_with(+ "GET",+ "https://graph.microsoft.com/v1.0/sites/contoso.sharepoint.com:"+ "/sites/Finance%20Team?%24select=id%2CwebUrl",+ "graph-token",+ )++ @mock.patch.object(site_access, "request_json")+ def test_uses_by_path_syntax_for_tenant_root_site(+ self, request_json: mock.Mock+ ) -> None:+ request_json.return_value = graph_site()++ site_access.resolve_sharepoint_url(+ "https://contoso.sharepoint.com/", "graph-token"+ )++ request_json.assert_called_once_with(+ "GET",+ "https://graph.microsoft.com/v1.0/sites/contoso.sharepoint.com:/"+ "?%24select=id%2CwebUrl",+ "graph-token",+ )++ def test_rejects_non_https_urls(self) -> None:+ with self.assertRaisesRegex(SystemExit, "valid HTTPS URLs"):+ site_access.resolve_sharepoint_url(+ "http://contoso.sharepoint.com/sites/Finance", "token"+ )++ @mock.patch.object(site_access, "request_json")+ def test_rejects_mismatched_graph_hostname(self, request_json: mock.Mock) -> None:+ request_json.return_value = {+ "id": f"other.sharepoint.com,{COLLECTION_GUID},{WEB_GUID}"+ }++ with self.assertRaisesRegex(SystemExit, "unexpected site ID"):+ site_access.resolve_sharepoint_url(SITE_URL, "graph-token")++ @mock.patch.object(site_access, "request_json")+ def test_rejects_invalid_graph_guids(self, request_json: mock.Mock) -> None:+ request_json.return_value = {+ "id": f"contoso.sharepoint.com,not-a-guid,{WEB_GUID}"+ }++ with self.assertRaisesRegex(SystemExit, "invalid site ID"):+ site_access.resolve_sharepoint_url(SITE_URL, "graph-token")+++class ReadSiteUrlsTests(unittest.TestCase):+ def test_reads_csv_and_deduplicates_inline_urls(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ sites_file = Path(directory) / "sites.csv"+ sites_file.write_text(+ "site_url\nhttps://contoso.sharepoint.com/sites/Finance\n"+ "https://contoso.sharepoint.com/sites/Research\n",+ encoding="utf-8",+ )++ result = site_access.read_site_urls([SITE_URL], str(sites_file))++ self.assertEqual(+ result, [SITE_URL, "https://contoso.sharepoint.com/sites/Research"]+ )++ def test_reads_text_and_skips_comments(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ sites_file = Path(directory) / "sites.txt"+ sites_file.write_text(f"# Approved sites\n\n{SITE_URL}\n", encoding="utf-8")++ result = site_access.read_site_urls([], str(sites_file))++ self.assertEqual(result, [SITE_URL])++ def test_skips_csv_rows_with_missing_or_empty_site_urls(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ sites_file = Path(directory) / "sites.csv"+ sites_file.write_text(+ f"name,site_url\nFinance\nEmpty,\nResearch,{SITE_URL}\n",+ encoding="utf-8",+ )++ result = site_access.read_site_urls([], str(sites_file))++ self.assertEqual(result, [SITE_URL])++ def test_rejects_csv_without_site_url_column(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ sites_file = Path(directory) / "sites.csv"+ sites_file.write_text("name\nFinance\n", encoding="utf-8")++ with self.assertRaisesRegex(SystemExit, "site_url or url column"):+ site_access.read_site_urls([], str(sites_file))+++class AllowlistCommandTests(unittest.TestCase):+ def run_command(+ self,+ arguments: list[str],+ *,+ responses: list[dict[str, object]],+ ) -> tuple[dict[str, object], mock.Mock]:+ output = io.StringIO()+ environment = {+ "MICROSOFT_GRAPH_TOKEN": "graph-token",+ "CHATGPT_ADMIN_TOKEN": "admin-token",+ }+ with (+ mock.patch("sys.argv", ["sharepoint_site_access_admin.py", *arguments]),+ mock.patch.dict(site_access.os.environ, environment, clear=True),+ mock.patch.object(+ site_access, "request_json", side_effect=responses+ ) as request_json,+ mock.patch("sys.stdout", output),+ ):+ site_access.main()++ return json.loads(output.getvalue()), request_json++ def test_inspect_does_not_call_chatgpt_admin_api(self) -> None:+ result, request_json = self.run_command(+ ["inspect", "--site-url", SITE_URL], responses=[graph_site()]+ )++ self.assertEqual(result["collection_guids"], [COLLECTION_GUID])+ self.assertEqual(request_json.call_count, 1)++ def test_add_deduplicates_collections_and_uses_one_put(self) -> None:+ research_url = "https://contoso.sharepoint.com/sites/Research"+ second_web_guid = "4318127b-8167-42de-82f3-e4e41a6e5c1a"+ result, request_json = self.run_command(+ [+ "add",+ "--workspace-id",+ WORKSPACE_ID,+ "--site-url",+ SITE_URL,+ "--site-url",+ research_url,+ ],+ responses=[+ graph_site(),+ graph_site(web_guid=second_web_guid),+ {"allow_list": {}},+ {"allow_list": {COLLECTION_GUID: {}}},+ ],+ )++ self.assertEqual(result["processed_count"], 1)+ self.assertEqual(+ request_json.call_args,+ mock.call(+ "PUT",+ ALLOWLIST_URL,+ "admin-token",+ body={"collection_guids": [COLLECTION_GUID]},+ idempotency_key=None,+ ),+ )++ def test_add_forwards_optional_idempotency_key(self) -> None:+ result, request_json = self.run_command(+ [+ "add",+ "--workspace-id",+ WORKSPACE_ID,+ "--site-url",+ SITE_URL,+ "--idempotency-key",+ IDEMPOTENCY_KEY,+ ],+ responses=[graph_site(), {"allow_list": {}}, {"allow_list": {}}],+ )++ self.assertEqual(result["processed_count"], 1)+ self.assertEqual(+ request_json.call_args,+ mock.call(+ "PUT",+ ALLOWLIST_URL,+ "admin-token",+ body={"collection_guids": [COLLECTION_GUID]},+ idempotency_key=IDEMPOTENCY_KEY,+ ),+ )++ def test_dry_run_reads_policy_without_writing(self) -> None:+ result, request_json = self.run_command(+ [+ "add",+ "--workspace-id",+ WORKSPACE_ID,+ "--site-url",+ SITE_URL,+ "--dry-run",+ ],+ responses=[graph_site(), {"allow_list": {}}],+ )++ self.assertTrue(result["dry_run"])+ self.assertEqual(result["collection_guids"], [COLLECTION_GUID])+ self.assertEqual(+ [call.args[0] for call in request_json.call_args_list], ["GET", "GET"]+ )++ def test_add_rejects_empty_input_before_any_request(self) -> None:+ with (+ mock.patch("sys.argv", ["script", "add", "--workspace-id", WORKSPACE_ID]),+ mock.patch.object(site_access, "request_json") as request_json,+ self.assertRaisesRegex(SystemExit, "Provide at least one"),+ ):+ site_access.main()++ request_json.assert_not_called()++ def test_list_does_not_require_graph_token(self) -> None:+ output = io.StringIO()+ with (+ mock.patch("sys.argv", ["script", "list", "--workspace-id", WORKSPACE_ID]),+ mock.patch.dict(+ site_access.os.environ,+ {"CHATGPT_ADMIN_TOKEN": "admin-token"},+ clear=True,+ ),+ mock.patch.object(+ site_access, "request_json", return_value={"allow_list": {}}+ ),+ mock.patch("sys.stdout", output),+ ):+ site_access.main()++ self.assertEqual(json.loads(output.getvalue()), {"allow_list": {}})++ def test_remove_deletes_the_collection_guid(self) -> None:+ result, request_json = self.run_command(+ ["remove", "--workspace-id", WORKSPACE_ID, "--site-url", SITE_URL],+ responses=[+ graph_site(),+ {"allow_list": {COLLECTION_GUID: {}}},+ {"allow_list": {}},+ ],+ )++ self.assertEqual(result["processed_count"], 1)+ self.assertEqual(+ request_json.call_args,+ mock.call(+ "DELETE",+ f"{ALLOWLIST_URL}/{COLLECTION_GUID}",+ "admin-token",+ idempotency_key=None,+ ),+ )++ def test_remove_derives_distinct_stable_keys_for_each_collection(self) -> None:+ other_collection_guid = "b70d36d6-06d8-4591-964a-848f46c56b40"+ other_url = "https://contoso.sharepoint.com/sites/Research"+ other_site = {+ "id": f"contoso.sharepoint.com,{other_collection_guid},{WEB_GUID}",+ "webUrl": other_url,+ }+ result, request_json = self.run_command(+ [+ "remove",+ "--workspace-id",+ WORKSPACE_ID,+ "--site-url",+ SITE_URL,+ "--site-url",+ other_url,+ "--idempotency-key",+ IDEMPOTENCY_KEY,+ ],+ responses=[+ graph_site(),+ other_site,+ {"allow_list": {}},+ {"allow_list": {}},+ {"allow_list": {}},+ ],+ )++ self.assertEqual(result["processed_count"], 2)+ delete_calls = request_json.call_args_list[-2:]+ self.assertEqual(+ [call.kwargs["idempotency_key"] for call in delete_calls],+ [+ str(+ uuid.uuid5(uuid.UUID(IDEMPOTENCY_KEY), f"remove:{COLLECTION_GUID}")+ ),+ str(+ uuid.uuid5(+ uuid.UUID(IDEMPOTENCY_KEY), f"remove:{other_collection_guid}"+ )+ ),+ ],+ )++ def test_clear_requires_explicit_confirmation(self) -> None:+ with (+ mock.patch("sys.argv", ["script", "clear", "--workspace-id", WORKSPACE_ID]),+ mock.patch.dict(+ site_access.os.environ,+ {"CHATGPT_ADMIN_TOKEN": "admin-token"},+ clear=True,+ ),+ mock.patch.object(+ site_access, "request_json", return_value={"allow_list": {}}+ ) as request_json,+ self.assertRaisesRegex(SystemExit, "repeat with --yes"),+ ):+ site_access.main()++ request_json.assert_called_once_with("GET", ALLOWLIST_URL, "admin-token")++ def test_clear_with_confirmation_deletes_allowlist(self) -> None:+ result, request_json = self.run_command(+ ["clear", "--workspace-id", WORKSPACE_ID, "--yes"],+ responses=[{"allow_list": {COLLECTION_GUID: {}}}, {"allow_list": {}}],+ )++ self.assertEqual(result["action"], "clear")+ self.assertEqual(+ request_json.call_args,+ mock.call("DELETE", ALLOWLIST_URL, "admin-token", idempotency_key=None),+ )++ def test_clear_forwards_optional_idempotency_key(self) -> None:+ result, request_json = self.run_command(+ [+ "clear",+ "--workspace-id",+ WORKSPACE_ID,+ "--yes",+ "--idempotency-key",+ IDEMPOTENCY_KEY,+ ],+ responses=[{"allow_list": {COLLECTION_GUID: {}}}, {"allow_list": {}}],+ )++ self.assertEqual(result["action"], "clear")+ self.assertEqual(+ request_json.call_args,+ mock.call(+ "DELETE", ALLOWLIST_URL, "admin-token", idempotency_key=IDEMPOTENCY_KEY+ ),+ )++ def test_clear_dry_run_does_not_require_confirmation_or_write(self) -> None:+ result, request_json = self.run_command(+ ["clear", "--workspace-id", WORKSPACE_ID, "--dry-run"],+ responses=[{"allow_list": {COLLECTION_GUID: {}}}],+ )++ self.assertTrue(result["dry_run"])+ request_json.assert_called_once_with("GET", ALLOWLIST_URL, "admin-token")++ def test_rejects_invalid_workspace_uuid_before_admin_request(self) -> None:+ with (+ mock.patch("sys.argv", ["script", "list", "--workspace-id", "not-a-uuid"]),+ mock.patch.dict(+ site_access.os.environ,+ {"CHATGPT_ADMIN_TOKEN": "admin-token"},+ clear=True,+ ),+ mock.patch.object(site_access, "request_json") as request_json,+ self.assertRaisesRegex(SystemExit, "valid UUID"),+ ):+ site_access.main()++ request_json.assert_not_called()+++class MutationKeyTests(unittest.TestCase):+ def test_omitted_key_leaves_existing_behavior_unchanged(self) -> None:+ self.assertIsNone(site_access.mutation_key(None, "add"))++ def test_rejects_invalid_idempotency_uuid(self) -> None:+ with self.assertRaisesRegex(+ SystemExit, "--idempotency-key must be a valid UUID"+ ):+ site_access.mutation_key("not-a-uuid", "add")++ def test_remove_keys_are_stable_and_unique_per_identifier(self) -> None:+ first = site_access.mutation_key(IDEMPOTENCY_KEY, "remove", COLLECTION_GUID)+ repeated = site_access.mutation_key(IDEMPOTENCY_KEY, "remove", COLLECTION_GUID)+ second = site_access.mutation_key(IDEMPOTENCY_KEY, "remove", WEB_GUID)++ self.assertEqual(first, repeated)+ self.assertNotEqual(first, second)+++if __name__ == "__main__":+ unittest.main()diff --git a/registry.yaml b/registry.yamlindex 55de71e3..9cb02fcc 100644--- a/registry.yaml+++ b/registry.yaml@@ -4,6 +4,21 @@# should build pages for, and indicates metadata such as tags, creation date and# authors for each page.+- title: Manage SharePoint site access with the ChatGPT Admin API+ path: examples/chatgpt/sharepoint_site_access/sharepoint_site_access.md+ slug: manage-sharepoint-site-access-chatgpt-admin-api+ description: Resolve SharePoint URLs into site-collection identifiers and safely manage a ChatGPT workspace allowlist with the Admin API.+ date: 2026-08-27+ authors:+ - hmittal-oai+ tags:+ - chatgpt+ - chatgpt-and-api+ - enterprise+ - api+ - sharepoint+ - security+- title: Generate Transparent Image Assets for Campaigns and Presentationspath: examples/multimodal/transparent-image-assets-for-campaigns-and-presentations.ipynbslug: transparent-image-assets-for-campaigns-and-presentations