"""Prove the fixed project's effective ACL with live, owner-visible Drive metadata.""" import hashlib import http.client import json import os import re from urllib.parse import urlencode PROJECT_FOLDER = '1quVPlAkM8lK95siVoA0YQ23I9I-0kch3' PROJECT_MY_DRIVE_ROOT = '0AD1IMHKOPZB4Uk9PVA' PROJECT_OWNER_SHA256 = 'feb12acc4cc98e55902b56268f726f3489d3e5baaf6aafef2fbff7e485f2a1b2' TOKEN_FD = 'MELTMIND_DRIVE_METADATA_TOKEN_FD' HOST = 'www.googleapis.com' FOLDER_TYPE = 'application/vnd.google-apps.folder' FILE_FIELDS = 'id,parents,driveId,mimeType,ownedByMe,trashed,permissionIds,version,size,sha256Checksum' ACL_FIELDS = ('nextPageToken,permissions(id,type,role,emailAddress,domain,allowFileDiscovery,deleted,view,' 'permissionDetails(inherited,inheritedFrom,permissionType,role))') ID = re.compile(r'[A-Za-z0-9_-]+\Z') def _credential(): fd = os.environ.get(TOKEN_FD, '') if not fd.isascii() or not fd.isdecimal() or int(fd) < 3: raise PermissionError('Existing authorized Drive metadata transport is unavailable') try: with os.fdopen(os.dup(int(fd)), 'rb') as source: token = source.readline(8193).strip().decode('ascii') except (OSError, ValueError, UnicodeError): raise PermissionError('Existing authorized Drive metadata transport is unavailable') from None if not token or len(token) > 8192 or any(not 33 <= ord(ch) <= 126 for ch in token): raise PermissionError('Drive metadata transport provided no usable credential') return token def _get_json(path, query, token): connection = http.client.HTTPSConnection(HOST, timeout=15) try: connection.request('GET', '/drive/v3/files/' + path + '?' + urlencode(query), headers={'Authorization': 'Bearer ' + token, 'Accept': 'application/json'}) response = connection.getresponse() if response.status != 200: raise PermissionError(f'Authoritative Drive metadata status {response.status}') data = response.read(2**20 + 1) if len(data) > 2**20: raise PermissionError('Oversized Drive metadata') value = json.loads(data) if not isinstance(value, dict): raise PermissionError('Invalid Drive metadata response') return value except PermissionError: raise except (OSError, ValueError, http.client.HTTPException): raise PermissionError('Authoritative Drive metadata could not be verified') from None finally: connection.close() def _listed_permissions(file_id, token): query = dict(fields=ACL_FIELDS, pageSize=100, supportsAllDrives='true', includePermissionsForView='published') rows, seen = [], set() for _ in range(20): page = _get_json(file_id + '/permissions', query, token) permissions = page.get('permissions') if not isinstance(permissions, list): raise PermissionError('Missing effective Drive permissions') rows.extend(permissions) if 'nextPageToken' not in page: return rows next_page = page['nextPageToken'] if not isinstance(next_page, str) or not next_page or next_page in seen: raise PermissionError('Incomplete Drive permissions pagination') seen.add(next_page) query['pageToken'] = next_page raise PermissionError('Incomplete Drive permissions pagination') def _member_evidence(item, token): rows = _listed_permissions(item['id'], token) provider_ids = item.get('permissionIds') if not rows or not isinstance(provider_ids, list) or not all(isinstance(p, str) and p for p in provider_ids): raise PermissionError('No complete effective Drive permissions evidence') matches, ids = [], set() for row in rows: if not isinstance(row, dict) or row.get('type') != 'user' or row.get('view') == 'published': raise PermissionError('Public, linked, group or domain Drive access is out of scope') email, pid, role = row.get('emailAddress'), row.get('id'), row.get('role') if (not isinstance(email, str) or not isinstance(pid, str) or not pid or pid in ids or role not in ('owner', 'writer', 'commenter', 'reader') or row.get('deleted') is True): raise PermissionError('Unverifiable Drive principal or role') principal = hashlib.sha256(email.strip().casefold().encode()).hexdigest() if principal != PROJECT_OWNER_SHA256: raise PermissionError('Drive access outside the verified project principal') ids.add(pid) matches.append(dict(id=pid,type='user',role=role,principal_sha256=principal, permission_details=row.get('permissionDetails', []))) if ids != set(provider_ids) or not any(p['role']=='owner' for p in matches): raise PermissionError('Owner-visible effective Drive ACL is incomplete') return matches def _prove_chain(lookup, archive=None): token = _credential() query = dict(fields=FILE_FIELDS, supportsAllDrives='true') observations = [] for locator, expected_id, parents in lookup: item = _get_json(locator, query, token) if (item.get('id') != expected_id or item.get('parents', []) != parents or item.get('driveId') or item.get('ownedByMe') is not True or item.get('trashed') is not False or not isinstance(item.get('version'), str) or not item['version'].isdecimal()): raise PermissionError('Drive archive or inheritance chain does not match the fixed project') if archive and locator == archive['file_id']: if (item.get('mimeType') not in ('application/zip','application/x-zip','application/x-zip-compressed') or (item.get('sha256Checksum'),item.get('size')) != (archive['sha256'],str(archive['bytes']))): raise PermissionError('Authoritative Drive archive bytes do not match the frozen bundle') elif item.get('mimeType') != FOLDER_TYPE: raise PermissionError('Drive inheritance parent is not a folder') observations.append((locator, item, _member_evidence(item, token))) # Require stable metadata across the three ACL reads, including each ancestor's version. for locator, item, _ in observations: if _get_json(locator, query, token) != item: raise PermissionError('Drive metadata changed during ACL verification') return dict(source='live Google Drive v3 files.get and exhaustive permissions.list', chain=[dict(file_id=item['id'],version=item['version'],parents=item.get('parents', []), effective_permissions=permissions) for _,item,permissions in observations]) def _fixed_parent_chain(folder_id): if folder_id != PROJECT_FOLDER: raise PermissionError('Drive destination must be the fixed project folder') return ((PROJECT_FOLDER, PROJECT_FOLDER, [PROJECT_MY_DRIVE_ROOT]), ('root', PROJECT_MY_DRIVE_ROOT, [])) def prove_folder(folder_id): return dict(_prove_chain(_fixed_parent_chain(folder_id)), parent_id=folder_id) def prove(file_id, folder_id, digest, size): parents = _fixed_parent_chain(folder_id) if (not isinstance(file_id, str) or not ID.fullmatch(file_id) or file_id in (PROJECT_FOLDER, PROJECT_MY_DRIVE_ROOT, 'root')): raise PermissionError('Archive must be in the fixed project folder') archive = dict(file_id=file_id,parent_id=folder_id,bytes=size,sha256=digest) return dict(_prove_chain(((file_id, file_id, [PROJECT_FOLDER]),) + parents, archive), **archive)