Skip to content
Merged
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ env/
outputs/
data/
test_*.py
.DS_Store
.DS_Store
certificate/
149 changes: 149 additions & 0 deletions core/cert_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# 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.

"""Certificate helper management functions for local authentication mapping to Microsoft Graph API."""

import os
import logging
import datetime
from typing import Tuple
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.serialization import pkcs12

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

def update_log_directory(tenant_id: str = None, client_id: str = None) -> None:
"""No-op as logging is handled centrally by the root logger."""
pass


def get_project_root() -> str:
"""Helper to locate the root path of migration-planner."""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def get_cert_paths(cert_dir: str = "certificate", tenant_id: str = None, client_id: str = None) -> Tuple[str, str, str]:
"""Returns absolute paths for cert directory, certificate.pem, and passkey.pfx."""
root = get_project_root()
if tenant_id and client_id:
dir_path = os.path.join(root, cert_dir, f"{tenant_id}_{client_id}")
else:
dir_path = os.path.join(root, cert_dir)
pem_path = os.path.join(dir_path, "certificate.pem")
pfx_path = os.path.join(dir_path, "passkey.pfx")
return dir_path, pem_path, pfx_path

def check_certificate_exists(cert_dir: str = "certificate", tenant_id: str = None, client_id: str = None) -> bool:
"""Checks if the certificate directory exists and contains a valid cert.pfx file."""
_, _, pfx_path = get_cert_paths(cert_dir, tenant_id, client_id)
exists = os.path.exists(pfx_path)
logger.info("Checking if certificate exists at %s: %s", pfx_path, exists)
return exists

def generate_certificate(client_secret: str, cert_dir: str = "certificate", common_name: str = "LocalAppHybridAuth", tenant_id: str = None, client_id: str = None) -> Tuple[str, str]:
"""Generates a self-signed certificate and PFX bundle using client_secret as the password.

Returns:
Tuple containing absolute paths to the generated cert.pem and cert.pfx files.
"""
logger.info("Initializing certificate generation flow...")
dir_path, pem_path, pfx_path = get_cert_paths(cert_dir, tenant_id, client_id)

os.makedirs(dir_path, exist_ok=True)
logger.info("Certificate directory confirmed: %s", dir_path)

secret_bytes = client_secret.encode('utf-8')

logger.info("Generating secure RSA private key...")
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)

logger.info("Generating self-signed certificate with CN: %s...", common_name)
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
])

cert = x509.CertificateBuilder().subject_name(
subject
).issuer_name(
issuer
).public_key(
private_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.datetime.now(datetime.timezone.utc)
).not_valid_after(
# Valid for 2 years
datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=730)
).sign(private_key, hashes.SHA256())

logger.info("Writing PEM public certificate to %s...", pem_path)
with open(pem_path, "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))

logger.info("Serializing and writing PFX encrypted with client secret to %s...", pfx_path)
pfx_bytes = pkcs12.serialize_key_and_certificates(
name=common_name.encode('utf-8'),
key=private_key,
cert=cert,
cas=None,
encryption_algorithm=serialization.BestAvailableEncryption(secret_bytes)
)
with open(pfx_path, "wb") as f:
f.write(pfx_bytes)

logger.info("Certificate generation complete! Files written successfully.")
return pem_path, pfx_path

def load_certificate(client_secret: str, cert_dir: str = "certificate", tenant_id: str = None, client_id: str = None) -> Tuple[str, str]:
"""Decrypts PFX bundle using client_secret, extracting private key PEM and SHA1 thumbprint.

Returns:
Tuple containing private_key_pem (str) and thumbprint (str).
"""
logger.info("Loading certificate files...")
_, _, pfx_path = get_cert_paths(cert_dir, tenant_id, client_id)

if not os.path.exists(pfx_path):
raise FileNotFoundError(f"PFX certificate file not found at {pfx_path}")

logger.info("Unlocking PFX file with client secret...")
with open(pfx_path, "rb") as f:
pfx_data = f.read()

password_bytes = client_secret.encode('utf-8')
private_key, certificate, _ = pkcs12.load_key_and_certificates(
pfx_data,
password_bytes
)

logger.info("Extracting private key PEM...")
private_key_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
).decode("utf-8")

logger.info("Calculating certificate SHA1 fingerprint...")
thumbprint = certificate.fingerprint(hashes.SHA1()).hex()
logger.info("Loaded certificate successfully. Thumbprint: %s", thumbprint)

return private_key_pem, thumbprint
35 changes: 35 additions & 0 deletions estimators/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
from estimators.eo_in_place_archive_estimator import EOInPlaceArchiveEstimator
from estimators.eo_shared_mailbox_estimator import EOSharedMailBoxEstimator
from estimators.file_estimator import FileEstimator
from estimators.files_shallow.shallow_file_estimator import ShallowFileEstimator
from tests.files.mocks import MockUrlInvoker
from util.auth_manager import TokenManager
from util.files_shallow.cert_token_manager import CertTokenManager
from util.connectors import UrlInvoker
from util.utils import ScanConfig
import json
Expand Down Expand Up @@ -36,6 +38,8 @@ def __init__(
self.mock_url_invoker = None
self.one_token_per_app_manager = one_token_per_app_manager
self.child_folder_url_invoker = None
self.cert_token_manager = None
self.shallow_files_estimator = None

def isEmpty(self, data):
return data is None or len(data) == 0
Expand All @@ -55,6 +59,20 @@ def get_manager(self):

return self.manager

def get_cert_token_manager(self):
if not self.cert_token_manager:
if self.isEmpty(self.config.client_ids) or self.isEmpty(self.config.client_secrets) or self.isEmpty(self.config.tenant_id):
raise Exception("Missing credentials for certificate token manager!!")
self.cert_token_manager = CertTokenManager(
self.config.tenant_id,
self.config.client_ids,
self.config.client_secrets,
self.config.concurrency,
self.config.retries,
self.config.backoff,
)
return self.cert_token_manager

def set_id_to_display_name(self, id_to_display_name):
self.id_to_display_name = (
id_to_display_name if id_to_display_name is not None else {}
Expand Down Expand Up @@ -200,6 +218,23 @@ def get_files_estimator(self, progress_update_callback=lambda x: None, hard_rese

return self.files_estimator

def get_shallow_files_estimator(self, progress_update_callback=lambda x: None, hard_reset=False):
if self.shallow_files_estimator is None or hard_reset:
if self.shallow_files_estimator is not None:
self.shallow_files_estimator.shutdown()
url_invoker = self.get_url_invoker()
cert_manager = self.get_cert_token_manager()
self.shallow_files_estimator = ShallowFileEstimator(
self.config,
url_invoker,
cert_manager,
logger=self.logger,
stop_event=self.stop_event,
progress_update_callback=progress_update_callback
)
self.shallow_files_estimator.set_id_to_display_name_map(self.id_to_display_name)
return self.shallow_files_estimator

def get_email_estimator(self, hard_reset=False):
if self.email_estimator is None or hard_reset:
if self.email_estimator is not None:
Expand Down
Loading