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

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added tests/integration/__init__.py
Empty file.
96 changes: 96 additions & 0 deletions tests/integration/redaction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Replaces tenant details with placeholders in anything the tests print.

The tests run on a public repository, where anyone can read the CI logs. The
CI system hides stored secret values, but only exact matches: the same value in
another form (a user's OneDrive address, the tenant name inside a SharePoint
address) is not hidden. So before a test prints anything a tool wrote, every
known form of the secret, tenant, user and site is replaced with a placeholder.

Set MP_IT_RAW_OUTPUT=1 to see the output as it is when debugging locally.
"""

import os
import re
import urllib.parse
from typing import Callable, Dict, Iterable

RAW_OUTPUT_ENV = "MP_IT_RAW_OUTPUT"
SECRET, TENANT_ID, CLIENT_ID = "<SECRET>", "<TENANT_ID>", "<CLIENT_ID>"
TENANT, USER, SITE, OTHER = "<TENANT>", "<USER>", "<SITE>", "<OTHER>"
# A certificate thumbprint, as Microsoft prints it in sign-in errors.
_THUMBPRINT = re.compile(r"\b[0-9A-Fa-f]{40}\b")
# Shorter values are too likely to match ordinary words.
_MIN_LENGTH = 4


def _tenant_forms(name: str) -> Iterable[str]:
return (
f"{name}.onmicrosoft.com", f"{name}-my.sharepoint.com", f"{name}-admin.sharepoint.com",
f"{name}.sharepoint.com", f"{name}_onmicrosoft_com", name,
)


def build(credentials: Dict[str, str], entries: Iterable[str], secrets: Iterable[str] = ()) -> Callable[[str], str]:
"""Returns a function that replaces tenant details in a text with placeholders.

Args:
credentials: TENANT_ID, CLIENT_ID and CLIENT_SECRET.
entries: The users (email addresses) and sites (web addresses) being scanned.
secrets: Any other secret values to hide, such as a deliberately wrong one.
"""
if os.environ.get(RAW_OUTPUT_ENV):
return str
pairs = {credentials["TENANT_ID"]: TENANT_ID, credentials["CLIENT_ID"]: CLIENT_ID}
for secret in (credentials["CLIENT_SECRET"], *secrets):
if secret:
pairs[secret] = SECRET
pairs[urllib.parse.quote(secret, safe="")] = SECRET
tenants = set()
for entry in entries:
entry = str(entry).strip()
if entry.lower().startswith("http"):
url = urllib.parse.urlparse(entry)
pairs[entry.rstrip("/")] = SITE
pairs[urllib.parse.quote(entry.rstrip("/"), safe="")] = SITE
path = url.path.rstrip("/")
if path:
pairs[path] = SITE
pairs[path.rsplit("/", 1)[-1]] = SITE
tenants.add(re.sub(r"-(my|admin)$", "", url.netloc.split(".")[0]))
elif "@" in entry:
local, domain = entry.split("@", 1)
pairs[entry] = USER
pairs[urllib.parse.quote(entry, safe="")] = USER
pairs[re.sub(r"[^A-Za-z0-9]", "_", entry)] = USER # As in a OneDrive address.
pairs[local] = USER
tenants.add(domain.split(".")[0])
for tenant in tenants:
for form in _tenant_forms(tenant):
pairs.setdefault(form, TENANT)
pairs = {value.lower(): placeholder for value, placeholder in pairs.items() if len(value) >= _MIN_LENGTH}
# Longest first, so a whole address is replaced before a part of it.
pattern = re.compile("|".join(re.escape(value) for value in sorted(pairs, key=len, reverse=True)), re.IGNORECASE)
# The planner logs the first characters of the client ID as "App 1a2b3...".
short_id = re.compile(r"\b(app )" + re.escape(credentials["CLIENT_ID"][:5]) + r"\b", re.IGNORECASE)
home = os.path.expanduser("~")

def redact(text: str) -> str:
text = pattern.sub(lambda match: pairs[match.group(0).lower()], str(text))
text = short_id.sub(lambda match: match.group(1) + CLIENT_ID, text)
text = _THUMBPRINT.sub("<THUMBPRINT>", text)
return text.replace(home, "<HOME>") if len(home) > 1 else text

return redact
72 changes: 72 additions & 0 deletions tests/integration/redaction_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for redaction. These run offline and call nothing."""

import unittest
from unittest import mock

from tests.integration import redaction

_CREDENTIALS = {
"TENANT_ID": "11111111-2222-3333-4444-555555555555",
"CLIENT_ID": "abcde123-0000-0000-0000-000000000000",
"CLIENT_SECRET": "s3cr~et.Value+1",
}
_USER = "Test.User1@contoso.onmicrosoft.com"
_SITE = "https://contoso.sharepoint.com/sites/IntegrationTestSite"


class RedactionTest(unittest.TestCase):

def setUp(self):
self.redact = redaction.build(_CREDENTIALS, [_USER, _SITE], secrets=["wrong-secret"])

def test_replaces_credentials(self):
text = f"tenant {_CREDENTIALS['TENANT_ID']} client {_CREDENTIALS['CLIENT_ID']} secret {_CREDENTIALS['CLIENT_SECRET']}"
self.assertEqual(self.redact(text), "tenant <TENANT_ID> client <CLIENT_ID> secret <SECRET>")

def test_replaces_extra_and_url_encoded_secrets(self):
self.assertEqual(self.redact("a wrong-secret b s3cr~et.Value%2B1"), "a <SECRET> b <SECRET>")

def test_replaces_user_in_any_case(self):
self.assertEqual(self.redact("User 'test.user1@CONTOSO.onmicrosoft.com' was not found"), "User '<USER>' was not found")

def test_replaces_onedrive_form_of_user(self):
text = "https://contoso-my.sharepoint.com/personal/test_user1_contoso_onmicrosoft_com/Documents"
self.assertEqual(self.redact(text), "https://<TENANT>/personal/<USER>/Documents")

def test_replaces_site_and_its_parts(self):
self.assertEqual(self.redact(f"Scanning {_SITE}/SubsiteA"), "Scanning <SITE>/SubsiteA")
self.assertEqual(self.redact("GET /sites/IntegrationTestSite/_api/web"), "GET <SITE>/_api/web")

def test_replaces_tenant_name_in_other_addresses(self):
self.assertEqual(self.redact("token for contoso.sharepoint.com and other@contoso.onmicrosoft.com"),
"token for <TENANT> and other@<TENANT>")

def test_replaces_short_client_id_and_thumbprint(self):
text = "App abcde...: signed in. Thumbprint '0C2334DD58F8972A3A3054EE114BEDB6E1390E92'"
self.assertEqual(self.redact(text), "App <CLIENT_ID>...: signed in. Thumbprint '<THUMBPRINT>'")

def test_keeps_text_needed_for_debugging(self):
text = "[2026-01-01 10:00:00] AADSTS7000215: Invalid client secret provided. Trace ID: 0b2e18e1-3440-435e-a9e3-850a79787b01 HTTP 401"
self.assertEqual(self.redact(text), text)

def test_raw_output_can_be_turned_on(self):
with mock.patch.dict("os.environ", {redaction.RAW_OUTPUT_ENV: "1"}):
redact = redaction.build(_CREDENTIALS, [_USER])
self.assertEqual(redact(_USER), _USER)


if __name__ == "__main__":
unittest.main()
Loading