"""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 datetime import timezone from functools import cached_property from openhound.core.lookup import logger from openhound.core.models.entries_dataclass import Edge, EdgePath from openhound_github.graph import GHEdgeProperties 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 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 def escape(value): return value.replace("\\", "\\\\").replace("'", "\\'") principal = escape(role.node_id) alert = escape(target.node_id) if reason == "organization_security_products": path = "-[:GH_CanAccess]->(:GH_Organization)-[:GH_Contains]->" predicate = f"'{MANAGE}' IN principal.permissions_organization" else: path = "-[:GH_CanAccess|GH_ScopedTo*1..2]->(:GH_Repository)-[:GH_Contains]->" predicate = f"'{VIEW}' IN principal.permissions_repository" 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=GHEdgeProperties( traversable=True, composed=True, reason=reason, query_composition=f"MATCH p=(principal:{role.kind} {{node_id:'{principal}'}}){path}(:GH_SecretScanningAlert {{node_id:'{alert}'}}) WHERE {predicate} RETURN p", ), ) 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 _cypher_string(value): return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'" def _owner_authority_composition(target): """Unroll owner assignments and inheritance, then inspect grant properties.""" org_id = _cypher_string(target.org_id) matches = ( "MATCH owner_roles=(owner)-[:GH_HasRole|GH_HasBaseRole|GH_MemberOf*1..]->(role:GH_Role)\n" "MATCH authority=(role)-[:GH_CanAccess|GH_ScopedTo*1..2]->(resource)\n" ) predicate = ( f"(resource.node_id = {org_id} AND '{MANAGE}' IN role.permissions_organization)" ) if target.repo_id: repo_id = _cypher_string(target.repo_id) predicate = ( f"({predicate} OR (resource.node_id = {repo_id} " f"AND '{VIEW}' IN role.permissions_repository))" ) return matches, predicate def _expiration_composition(credential, kind): """Recheck the emission-time expiration evidence when explaining an edge.""" expirations = [getattr(credential, "expires_at", None)] if kind == nk.PERSONAL_ACCESS_TOKEN: expirations.append(credential.token_expires_at) known = [ expiration if expiration.tzinfo else expiration.replace(tzinfo=timezone.utc) for expiration in expirations if expiration is not None ] if not known: return "" earliest = min(known).astimezone(timezone.utc).isoformat() return f" AND datetime() < datetime({_cypher_string(earliest)})" def credential_composition_query(credential, kind, target, owner_id, reason): """Show grant, resource scope, and owner evidence without the computed edge.""" principal = _cypher_string(credential.node_id) alert_id = _cypher_string(target.node_id) expiration = _expiration_composition(credential, kind) fine_grant = ( "('secret_scanning_alerts:read' IN credential.permissions_repository " "OR 'secret_scanning_alerts:write' IN credential.permissions_repository)" ) if kind in {nk.APP_INSTALLATION, nk.PERSONAL_ACCESS_TOKEN}: org_id = _cypher_string(target.org_id) repo_id = _cypher_string(target.repo_id) query = ( f"MATCH p=(credential:{kind} {{node_id:{principal}}})" "-[:GH_CanAccess|GH_ScopedTo*1..2]->" f"(repository:GH_Repository {{node_id:{repo_id}}})" f"-[:GH_Contains]->(alert:GH_SecretScanningAlert {{node_id:{alert_id}}})\n" f"MATCH context=(org:GH_Organization {{node_id:{org_id}}})-[:GH_Contains]->(alert)\n" ) if kind == nk.APP_INSTALLATION: return ( query + "WHERE credential.target_type = 'Organization' " "AND credential.suspended_at IS NULL AND credential.environmentid = org.node_id " f"AND {fine_grant}\nRETURN p, context" ) owner = _cypher_string(owner_id) authority, predicate = _owner_authority_composition(target) return ( query + f"MATCH ownership=(owner:GH_User {{node_id:{owner}}})-[:GH_HasPersonalAccessToken]->(credential)\n" + authority + "WHERE credential.token_expired = false AND credential.environmentid = org.node_id " + f"AND {fine_grant} AND {predicate}{expiration}\n" + "RETURN p, context, ownership, owner_roles, authority" ) owner = _cypher_string(owner_id) query = ( f"MATCH ownership=(owner:GH_User {{node_id:{owner}}})" f"-[:GH_HasPersonalAccessToken]->(credential:{kind} {{node_id:{principal}}})\n" ) broad_scope = ( "('repo' IN credential.scopes OR 'security_events' IN credential.scopes)" ) if reason == "classic_scope_and_owner_authority": org_id = _cypher_string(target.org_id) repository_match = "" public_scope = " OR ('public_repo' IN credential.scopes AND alert.repository_private = false)" repository_return = "" if target.repo_id: repo_id = _cypher_string(target.repo_id) repository_match = f"OPTIONAL MATCH repository=(repo:GH_Repository {{node_id:{repo_id}}})-[:GH_Contains]->(alert)\n" repository_return = ", repository" authority, predicate = _owner_authority_composition(target) return ( query + "MATCH authorization=(credential)-[:GH_AuthorizedForOrganization]->" + f"(org:GH_Organization {{node_id:{org_id}}})" + f"-[:GH_Contains]->(alert:GH_SecretScanningAlert {{node_id:{alert_id}}})\n" + repository_match + authority + "WHERE credential.credential_state = 'active' " + f"AND ({broad_scope}{public_scope}) " + f"AND {predicate}{expiration}\nRETURN ownership, authorization{repository_return}, owner_roles, authority" ) enterprise_id = _cypher_string(credential.enterprise_node_id) query += ( f"MATCH inventory=(enterprise:GH_Enterprise {{node_id:{enterprise_id}}})-[:GH_Contains]->(credential)\n" "MATCH membership=(enterprise)-[:GH_HasMember|GH_MapsToUser*1..2]->(owner)\n" ) enterprise_predicate = ( "credential.credential_state = 'active' AND credential.enterprise_authorized = true " f"AND {broad_scope}{expiration}" ) if target.owner.get("type") == "User": # Personal alert ownership is exported as the alert's environment ID, # even when its repository was not collected as a separate node. return ( query + f"MATCH alert=(target:GH_SecretScanningAlert {{node_id:{alert_id}}})\n" + f"WHERE {enterprise_predicate} AND target.environmentid = owner.node_id\n" + "RETURN ownership, inventory, membership, alert" ) org_id = _cypher_string(target.org_id) return ( query + f"MATCH context=(enterprise)-[:GH_Contains]->(org:GH_Organization {{node_id:{org_id}}})" + f"-[:GH_Contains]->(alert:GH_SecretScanningAlert {{node_id:{alert_id}}})\n" + "MATCH owner_roles=(owner)-[:GH_HasRole|GH_HasBaseRole|GH_MemberOf*1..]->(role:GH_OrgRole)\n" + "MATCH authority=(role)-[:GH_CanAccess]->(org)\n" + f"WHERE {enterprise_predicate} AND '{MANAGE}' IN role.permissions_organization " + "AND role.short_name IN ['owners', 'security_manager'] " + "AND (role.source = 'Predefined' OR " + "(role.type = 'default' AND (role.source IS NULL OR role.source = 'Default')))\n" + "RETURN ownership, inventory, membership, context, owner_roles, authority" ) 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=GHEdgeProperties( traversable=True, composed=True, reason=reason, query_composition=credential_composition_query( credential, kind, target, owner_id, reason ), ), )