"""Secret-scanning authority from permission properties and collected scope data. No capability edges are inputs. Cached inventory is shared across alert and credential conversion, so evaluation is independent of graph emission order. """ from dataclasses import dataclass from functools import cached_property from openhound.core.lookup import logger from openhound.core.models.entries_dataclass import Edge, EdgePath, EdgeProperties from openhound_github.kinds import edges as ek from openhound_github.kinds import nodes as nk from openhound_github.models.organization_role_management import unexpired from openhound_github.models.repository_role_access import RepositoryRoleAccess, predefined from openhound_github.secret_scanning_ids import collected_secret_scanning_alert_node_id MANAGE = "manage_security_products" VIEW = "view_secret_scanning_alerts" FINE_READ = {"secret_scanning_alerts:read", "secret_scanning_alerts:write"} @dataclass class AlertReadEdgeProperties(EdgeProperties): reason: str @dataclass class AlertTarget: node_id: str org_id: str | None repo_id: str | None repo_database_id: int | None private: bool | None owner: dict class SecretScanningAccess(RepositoryRoleAccess): def alert_target(self, number, repository, org_login): repo = repository or {} node_id = collected_secret_scanning_alert_node_id(repo.get("id"), number) if node_id is None: return None owner = repo.get("owner") or {} org_id = ( None if owner.get("type") == "User" else owner.get("node_id") if owner.get("type") == "Organization" else self.org_id(org_login) ) known_repo = self.repositories.get(repo.get("node_id"), {}) known_org = self.org_id(known_repo.get("org_login")) if known_org and org_id != known_org: logger.warning( "Skipping inconsistent secret-scanning alert repository ownership" ) return None private = repo.get("private") visibility = (known_repo.get("visibility") or "").lower() if visibility in {"private", "internal"}: private = True elif visibility == "public" and private is not True: private = False return AlertTarget( node_id, org_id, repo.get("node_id"), repo.get("id"), private, owner, ) @staticmethod def _authority_scope(target): owner = ( ("Organization", target.org_id) if target.org_id is not None else (target.owner.get("type"), target.owner.get("node_id")) ) return target.repo_id, owner @cached_property def _alert_targets(self): targets = {} repository_visibility = {} inventoried = {repo.get("database_id") for repo in self.repositories.values()} for row in self.rows("secret_scanning_alerts"): target = self.alert_target( row["number"], row.get("repository"), row.get("org_login") ) if target is None: continue if target.repo_database_id not in inventoried: repo_id = target.repo_database_id if repo_id not in repository_visibility: repository_visibility[repo_id] = target.private elif repository_visibility[repo_id] != target.private: repository_visibility[repo_id] = True if target.node_id not in targets: targets[target.node_id] = target continue previous = targets[target.node_id] if previous is None: continue # An unresolved conflict cannot be undone by another copy. if self._authority_scope(previous) != self._authority_scope(target): targets[target.node_id] = None logger.warning( "Skipping secret-scanning alert with conflicting ownership" ) elif previous.private != target.private: # Never let record order promote conflicting evidence to public. previous.private = True for target in targets.values(): if target is not None and target.repo_database_id in repository_visibility: target.private = repository_visibility[target.repo_database_id] return targets @cached_property def alerts(self): return [target for target in self._alert_targets.values() if target is not None] def target_for_alert(self, number, repository, org_login): """Share reconciled visibility and authority with alert node/edge export.""" target = self.alert_target(number, repository, org_login) if target is None: return None return self._alert_targets.get(target.node_id, target) def direct_access(self, role, target): if role.org_id != target.org_id: return None if role.kind == nk.ORG_ROLE and MANAGE in ( role.properties.get("permissions_organization") or [] ): return "organization_security_products" if target.repo_id in role.repositories and VIEW in ( role.properties.get("permissions_repository") or [] ): return "scoped_repository_alert_permission" return None def role_edges(self, target): if target is None: return for role in self.roles: reason = self.direct_access(role, target) if not reason: continue yield Edge( kind=ek.CAN_READ_SECRET_SCANNING_ALERT, start=EdgePath(value=role.node_id, match_by="id"), end=EdgePath(value=target.node_id, match_by="id"), properties=AlertReadEdgeProperties( traversable=True, composed=True, reason=reason, ), ) def owner_access(self, user_id, target): def grants_alert_access(role): return bool(self.direct_access(role, target)) return bool(user_id) and any( self.role_has_access(role, target.org_id, target.repo_id, grants_alert_access) for role in self.user_roles(user_id, target.org_id) ) def enterprise_member(self, user_id, credential): return any( r.get("id") == user_id and ( r.get("enterprise_node_id") == credential.enterprise_node_id or ( not r.get("enterprise_node_id") and (r.get("enterprise_slug") or "").casefold() == credential.enterprise_name.casefold() ) ) for r in self.rows("enterprise_users") ) def enterprise_org_access(self, user_id, credential, target): if credential.enterprise_authorized is not True or not self.enterprise_member( user_id, credential ): return False if not any( r.get("id") == target.org_id and r.get("enterprise_node_id") == credential.enterprise_node_id for r in self.rows("enterprise_organizations") ): return False return any( predefined(r.row) and r.row["name"] in {"owners", "security_manager"} and MANAGE in (r.properties.get("permissions_organization") or []) for r in self.user_roles(user_id, target.org_id) ) def credential_alert_edges(lookup, credential, kind): properties = credential.as_node if properties is None: return props = properties.properties fine_permission = bool( FINE_READ.intersection(getattr(props, "permissions_repository", None) or ()) ) owner_id = None if kind == nk.APP_INSTALLATION: if ( credential.target_type != "Organization" or credential.suspended_at is not None or not fine_permission ): return elif kind == nk.PERSONAL_ACCESS_TOKEN: if ( credential.token_expired or not unexpired(credential.expires_at, credential.token_expires_at) or not fine_permission ): return owner_id = credential.owner.node_id if not owner_id: return else: scopes = set(props.scopes or ()) if ( credential.credential_state != "active" or not unexpired(credential.expires_at) or not scopes.intersection({"repo", "security_events", "public_repo"}) ): return if credential.owner_id is not None: owner_id = lookup.enterprise_user_id_for_database_id(credential.owner_id) if not owner_id: return access = lookup.secret_scanning_access() if kind in {nk.APP_INSTALLATION, nk.PERSONAL_ACCESS_TOKEN}: org_id = credential.org_node_id repositories = access.repository_scope( org_id=org_id, selection=credential.repository_selection, access_rows="app_installation_repo_access" if kind == nk.APP_INSTALLATION else "pat_repo_access", principal_id=credential.node_id if kind == nk.APP_INSTALLATION else credential.id, id_field="installation_node_id" if kind == nk.APP_INSTALLATION else "pat_id", repository_field="repository_database_id" if kind == nk.APP_INSTALLATION else "node_id", ) for target in access.alerts: if kind in {nk.APP_INSTALLATION, nk.PERSONAL_ACCESS_TOKEN}: if target.org_id != org_id or target.repo_id not in repositories: continue if kind == nk.PERSONAL_ACCESS_TOKEN and not access.owner_access( owner_id, target ): continue reason = ( "installation_repository_grant" if kind == nk.APP_INSTALLATION else "token_and_owner_repository_authority" ) else: if ( not scopes.intersection({"repo", "security_events"}) and target.private is not False ): continue authorized = target.org_id and target.org_id in { access.org_id(login) for login in credential.authorized_organizations } org_access = authorized and access.owner_access(owner_id, target) enterprise_access = bool( scopes.intersection({"repo", "security_events"}) ) and access.enterprise_org_access(owner_id, credential, target) personal_access = ( target.owner.get("type") == "User" and target.owner.get("node_id") == owner_id and credential.enterprise_authorized is True and bool(scopes.intersection({"repo", "security_events"})) and access.enterprise_member(owner_id, credential) ) if not (org_access or enterprise_access or personal_access): continue reason = ( "classic_scope_and_owner_authority" if org_access else "enterprise_filtered_classic_access" ) yield Edge( kind=ek.CAN_READ_SECRET_SCANNING_ALERT, start=EdgePath(value=props.node_id, match_by="id"), end=EdgePath(value=target.node_id, match_by="id"), properties=AlertReadEdgeProperties( traversable=True, composed=True, reason=reason, ), )