o k`@s|ddlZddlZddlmZddlmZmZmZddlm Z ddl m Z m Z ddl TddlmZmZddlmZmZdd lmZdd lmZmZmZmZmZmZdd lmZmZgd Z Gd dde!Z"Gddde#Z$Gddde%Z&Gddde%Z'Gddde%Z(Gddde%Z)Gddde*Z+Gddde*Z,Gddde*Z-Gdd d e*Z.Gd!d"d"e/Z0Gd#d$d$e*Z1dS)%N)groupby)AdminCommandErrorIAdminCommandProvider get_dir_list)cached)ExtensionOptionOrderedExtensionsOption)*)Resourceget_resource_name) file_or_stdlazy)time_now)path_to_unicode print_tableprintoutstream_encoding to_unicodewrap)_N_)IPermissionRequestorIPermissionStoreIPermissionPolicyIPermissionGroupProviderPermissionErrorPermissionSystemcs6eZdZdZedZdfdd ZeddZZ S) rz2Insufficient permissions to perform the operation. ForbiddenNcsr||_||_||_|jr)|jr!|jjr!td|jt|j|jd}ntd|jd}n|dur1td}t|dS)Nzt%(perm)s privileges are required to perform this operation on %(resource)s. You don't have the required permissions.)permresourcezd%(perm)s privileges are required to perform this operation. You don't have the required permissions.)rz2Insufficient privileges to perform this operation.)actionrenvidrr super__init__)selfr rr!msg __class__+/usr/lib/python3/dist-packages/trac/perm.pyr$+s zPermissionError.__init__cCs |jdSNr)argsr%r)r)r*message>s zPermissionError.messageNNNN) __name__ __module__ __qualname____doc__rtitler$propertyr. __classcell__r)r)r'r*r&s rc@seZdZdZdS)PermissionExistsErrorz0Thrown when a unique key constraint is violated.N)r0r1r2r3r)r)r)r*r7Csr7c@eZdZdZddZdS)rz=Extension point interface for components that define actions.cCdS)akReturn a list of actions defined by this component. The items in the list may either be simple strings, or `(string, sequence)` tuples. The latter are considered to be "meta permissions" that group several simple actions under one name for convenience, adding to it if another component already defined that name. Nr)r)r)r)r*get_permission_actionsJz+IPermissionRequestor.get_permission_actionsN)r0r1r2r3r:r)r)r)r*rG rc@s8eZdZdZddZddZddZdd Zd d Zd S) rzeExtension point interface for components that provide storage and management of permissions. cCr9)z=Return a list of permissions for the specified user. Nr)usernamer)r)r*get_user_permissionsZr;z%IPermissionStore.get_user_permissionscCr9)zSReturn a list of users that have any of the specified permissions. Nr)) permissionsr)r)r*get_users_with_permissions^r;z+IPermissionStore.get_users_with_permissionscCr9)Return all permissions for all users. The permissions are returned as a list of (subject, action) formatted tuples. Nr)r)r)r)r*get_all_permissionscr;z$IPermissionStore.get_all_permissionscCr9)z-Grant a user permission to perform an action.Nr)r>r r)r)r*grant_permissionjr;z!IPermissionStore.grant_permissioncCr9)z>Revokes the permission of the given user to perform an action.Nr)rDr)r)r*revoke_permissionmr;z"IPermissionStore.revoke_permissionN) r0r1r2r3r?rArCrErFr)r)r)r*rUs rc@r8)rz]Extension point interface for components that provide information about user groups. cCr9)kReturn a list of names of the groups that the user with the specified name is a member of. Nr)r=r)r)r*get_permission_groupsvr;z.IPermissionGroupProvider.get_permission_groupsN)r0r1r2r3rHr)r)r)r*rqs rc@r8)rzCA security policy provider used for fine grained permission checks.cCr9)aCheck that the action can be performed by username on the resource :param action: the name of the permission :param username: the username string or 'anonymous' if there's no authenticated user :param resource: the resource on which the check applies. Will be `None`, if the check is a global one and not made on a resource in particular :param perm: the permission cache for that username and resource, which can be used for doing secondary checks on other permissions. Care must be taken to avoid recursion. :return: `True` if action is allowed, `False` if action is denied, or `None` if indifferent. If `None` is returned, the next policy in the chain will be consulted. Note that when checking a permission on a realm resource (i.e. when `.id` is `None`), this usually corresponds to some preliminary check done before making a fine-grained check on some resource. Therefore the `IPermissionPolicy` should be conservative and return: * `True` if the action *can* be allowed for some resources in that realm. Later, for specific resource, the policy will be able to return `True` (allow), `False` (deny) or `None` (don't decide). * `None` if the action *can not* be performed for *some* resources. This corresponds to situation where the policy is only interested in returning `False` or `None` on specific resources. * `False` if the action *can not* be performed for *any* resource in that realm (that's a very strong decision as that will usually prevent any fine-grained check to even happen). Note that performing permission checks on realm resources may seem redundant for now as the action name itself contains the realm, but this will probably change in the future (e.g. `'VIEW' in ...`). Nr))r r>rrr)r)r*check_permissionr;z"IPermissionPolicy.check_permissionN)r0r1r2r3rIr)r)r)r*r|r<rc@sfeZdZdZeeeeeZddZ ddZ ddZ dd Z d d Z d d ZeddZddZdS)DefaultPermissionStorezDefault implementation of permission storage and group management. This component uses the `permission` table in the database to store both permissions and groups. cCst||hdS)rG)sorted_get_actions_and_groups)r%r>r)r)r*rHsz,DefaultPermissionStore.get_permission_groupscCs@|h}|jD]}||ur|||pgqt||dS)aqRetrieve a list of permissions for the given user. The permissions are stored in the database as (username, action) records. There's simple support for groups by using lowercase names for the action column: such a record represents a group and not an actual permission, and declares that the user is part of that group. r)group_providersupdaterHrLrM)r%r>subjectsproviderr)r)r*r?s  z+DefaultPermissionStore.get_user_permissionscCsRt}dd|jD}|D]}||}|D] }||vr#||qqt|S)zRetrieve a list of users that have any of the specified permissions Users are returned as a list of usernames. cSsh|]}|dqS)rr)).0ur)r)r* zDDefaultPermissionStore.get_users_with_permissions..)setr!get_known_usersr?addrL)r%r@resultusersuser user_permsgroupr)r)r*rAs   z1DefaultPermissionStore.get_users_with_permissionscCs|jSrB)_all_permissionsr-r)r)r*rCsz*DefaultPermissionStore.get_all_permissionscC*|jd||f|jd|||`dS)z=Grants a user the permission to perform the specified action.z&INSERT INTO permission VALUES (%s, %s)zGranted permission for %s to %sNr!db_transactionloginfor_r%r>r r)r)r*rEs z'DefaultPermissionStore.grant_permissioncCr`)zrjr)r)r*rHs  z4DefaultPermissionGroupProvider.get_permission_groupsN)r0r1r2r3requiredrnrrHr)r)r)r*rps  rpc@s0eZdZdZeedZdZddZddZ dS) DefaultPermissionPolicyzrrnow timestampr@r)r)r*rI1s  z(DefaultPermissionPolicy.check_permissionN) r0r1r2r3rnrrrr$rIr)r)r)r*ru!s ruc@seZdZdZdZeeeeZee Z e dde ddZ eddedd d Zd Zd Zd dZddZddZd,ddZeddZd,ddZddZddZ d-ddZd d!Zd"d#Zd$d%Zd&d'Z  d.d(d)Z!d*d+Z"dS)/rz!Permission management sub-system.Ttracpermission_storerJzuName of the component implementing `IPermissionStore`, which is used for managing user and group permissions.permission_policieszWDefaultWikiPolicy, DefaultTicketPolicy, DefaultPermissionPolicy, LegacyAttachmentPolicyFzList of components implementing `IPermissionPolicy`, in the order in which they will be applied. These components manage fine-grained access control to Trac resources.rvrwcCrxryrzr-r)r)r*r$br}zPermissionSystem.__init__c Cs|r||vrttd|d|s&||vr&ttd|dz |j||WdS|jjj yR||vrIt td||dt td||dw) a<Grant the user with the given name permission to perform to specified action. :raises PermissionExistsError: if user already has the permission or is a member of the group. :since 1.3.1: raises PermissionExistsError rather than IntegrityError %(name)s is not a valid action.namezWPermission %(name)s differs from a defined action by casing only, which is not allowed.z4The user %(user)s already has permission %(action)s.)r[r z4The user %(user)s is already in the group %(group)s.)r[r]N) rh get_actions TracErrorrupperstorerEr!db_excIntegrityErrorr7rer)r)r*rEhs*  z!PermissionSystem.grant_permissioncCs|j||dS)zJRevokes the permission of the specified user to perform an action.N)rrFrer)r)r*rFsz"PermissionSystem.revoke_permissionNcCsbi}|jD])}||ur q|pgD]}t|tr'||dg|dq||gqq|S)aUGet all actions from permission requestors as a `dict`. The keys are the action names. The values are the additional actions granted by each action. For simple actions, this is an empty list. For meta actions, this is the list of actions covered by the action. :since 1.0.17: added `skip` argument. rrK) requestorsr: isinstancetuple setdefaultextendr%skipri requestorr r)r)r*get_actions_dicts  z!PermissionSystem.get_actions_dictcCs|Sryrr-r)r)r*riszPermissionSystem.actionscCsZt}|jD]"}||ur q|pgD]}t|tr"||dq||qqt|S)z;Get a list of all actions defined by permission requestors.r)rVrr:rrrXrLrr)r)r*rs   zPermissionSystem.get_actionscC8tdd|Dddd}ddt|dddDS) zGet all groups as a `dict`. The keys are the group names. The values are the group members. :since: 1.1.3 css |] }|ds|VqdSrKNrhrRpr)r)r*  z3PermissionSystem.get_groups_dict..cS|dSNrKr)rr)r)r*z2PermissionSystem.get_groups_dict..keycS(i|]\}}|tddt|DqS)cs|]}|dVqdSr~r)rRir)r)r*rz>PermissionSystem.get_groups_dict...rLlistrRkgr)r)r* z4PermissionSystem.get_groups_dict..cSrrr)rr)r)r*rrrLrCr)r%rjr)r)r*get_groups_dicts z PermissionSystem.get_groups_dictcCr) zGet all users as a `dict`. The keys are the user names. The values are the actions possessed by the user. :since: 1.1.3 css |] }|dr|VqdSrrrr)r)r*rrz2PermissionSystem.get_users_dict..cSrr+r)rr)r)r*rrz1PermissionSystem.get_users_dict..rcSr)csrrr)rr)r)r*rrz=PermissionSystem.get_users_dict...rrr)r)r*rrz3PermissionSystem.get_users_dict..cSrr+r)rr)r)r*rrr)r%rkr)r)r*get_users_dicts zPermissionSystem.get_users_dictcs^|s t|dS||j|pg}|r%fdd||DSfdd|DS)aReturn the permissions of the specified user. The return value is a dictionary containing all the actions granted to the user mapped to `True`. :param undefined: if `True`, include actions that are not defined in any of the `IPermissionRequestor` implementations. :param expand_meta: if `True`, expand meta permissions. :since 1.3.1: added the `undefined` parameter. :since 1.3.3: added the `expand_meta` parameter. Tci|] }s |vr|dqSTr)rri undefinedr)r*r z9PermissionSystem.get_user_permissions..crrr)rrr)r*rr)dictfromkeysrrrr?expand_actions)r%r>r expand_metauser_permissionsr)rr*r?sz%PermissionSystem.get_user_permissionscCs.t}|jD] }|||pgqt|S)aReturn a sorted list of groups that `username` belongs to. Groups are recursively expanded such that if `username` is a member of `group1` and `group1` is a member of `group2`, both `group1` and `group2` will be returned. :since: 1.3.3 )rVrNrOrHrL)r%r> user_groupsrQr)r)r*rHs z&PermissionSystem.get_permission_groupscCs|jpgSr^)rrCr-r)r)r*rCsz$PermissionSystem.get_all_permissionsc st}||j|jkri|_||_|j|d\}}|||jkr#|Si|D]\}}|D] }|t  |q1q+t fdd||j pUg}||f|j|<|S)zrReturn all users that have the specified permission. Users are returned as a list of user names. r~cs4|vr||dD]}|qdSdSNr)rXr)r append_with_parents parent_mapsatisfying_permsr)r*r   zGPermissionSystem.get_users_with_permission..append_with_parents) rr|rr{rrritemsrrVrXrrA) r% permissionrrr@parentchildrenchildrkr)rr*get_users_with_permissions(z*PermissionSystem.get_users_with_permissioncs8|tfdd|D]}|qtS)z-Helper method for expanding all meta actions.cs4|vr||dD]}|qdSdSrr)r a all_actions expand_actionexpanded_actionsr)r*rrz6PermissionSystem.expand_actions..expand_action)rrVrL)r%rirr)rr*rs  zPermissionSystem.expand_actionsc Cs|durd}|r|jdurd}|jD]#}|||||}|dur5|jd|jj|r+dnd||||Sq|jd|||dS)z_Return True if permission to perform action for the given resource is allowed. Nrqz%s %s %s performing %s on %rallowsdeniesz(No policy allowed %s performing %s on %rF)realmpoliciesrIrcdebugr(r0)r%r r>rrpolicydecisionr)r)r*rI(s(   z!PermissionSystem.check_permissioncCs|j|d}d|fgS)z;Implement the global `TRAC_ADMIN` meta permission. )r TRAC_ADMINr)r%rir)r)r*r:@s  z'PermissionSystem.get_permission_actionsry)NFT)NNN)#r0r1r2r3rtrnrrorrrNrrrrrrrrr$rErFrr rirrrr?rHrCrrrIr:r)r)r)r*rEsL         rc@s`eZdZdZdZ  dddZddZdd d Z  dd d Zd dZ eZ  dddZ e Z dS)PermissionCacheaaCache that maintains the permissions of a single user. Permissions are usually checked using the following syntax: 'WIKI_MODIFY' in perm One can also apply more fine grained permission checks and specify a specific resource for which the permission should be available: 'WIKI_MODIFY' in perm('wiki', 'WikiStart') If there's already a `page` object available, the check is simply: 'WIKI_MODIFY' in perm(page.resource) If instead of a check, one wants to assert that a given permission is available, the following form should be used: perm.require('WIKI_MODIFY') or perm('wiki', 'WikiStart').require('WIKI_MODIFY') or perm(page.resource).require('WIKI_MODIFY') When using `require`, a `PermissionError` exception is raised if the permission is missing. r!r> _resource_cacheNcCs,||_|pd|_||_|duri}||_dS)Nrqr)r%r!r>rcacherjr)r)r*r$js   zPermissionCache.__init__cCs|rt|||S|jSry)r r)r%realm_or_resourcer"versionr)r)r*_normalize_resourcess z#PermissionCache._normalize_resourceFcCs@|rt|||nd}|r|jr||jkr|St|j|j||jS)zConvenience function for using thus: 'WIKI_VIEW' in perm(context) or 'WIKI_VIEW' in perm(realm, id, version) or 'WIKI_VIEW' in perm(resource) N)r rrr!r>r)r%rr"rrr)r)r*__call__ys  zPermissionCache.__call__cCs||||}|||Sry)r_has_permission)r%r rr"rrr)r)r*has_permissions zPermissionCache.has_permissionc Cs|jt||f}|j|}|r|\}}||kr|Sd|f|j|<|}||jur2t|j|j||j}t|j||j||}||f|j|<|S)NF) r>hashrrrrr!rrI) r%r rrrcache_decisioncache_resourcerrr)r)r*rs"   zPermissionCache._has_permissioncCs>||||}|||s|durt|||jt|ddS)N)r&)rrrr!)r%r rr"rr.rr)r)r*requires   zPermissionCache.requirer/)FF)NFF)NFFN) r0r1r2r3 __slots__r$rrrr __contains__rassert_permissionr)r)r)r*rGs"     rc@s~eZdZdZeeddZddZddZdd Z d d Z d d Z ddZ dddZ ddZddZdddZdddZdS)PermissionAdminzAtrac-admin command provider for permission system administration.ccsjddd|j|jfVddd|j|jfVddd|j|jfVd d d |j|jfVd d d |j|jfVdS)Nzpermission listz[user]zList permission ruleszpermission addz [action] [...]zAdd a new permission rulezpermission removezRemove a permission rulezpermission exportz[file]z2Export permission rules to a file or stdout as CSVzpermission importz3Import permission rules from a file or stdin as CSV) _complete_list_do_list _complete_add_do_add_complete_remove _do_remove_complete_import_export _do_export _do_importr-r)r)r*get_admin_commandss* z"PermissionAdmin.get_admin_commandscCsddt|jDS)NcSsh|]\}}|qSr)r))rRr[r r)r)r*rTrUz0PermissionAdmin.get_user_list..rr!rCr-r)r)r* get_user_lists zPermissionAdmin.get_user_listcsfddt|jDS)Ncsg|] \}}|kr|qSr)r))rRsubjectr r[r)r* s z2PermissionAdmin.get_user_perms..r)r%r[r)rr*get_user_permss  zPermissionAdmin.get_user_permscCst|dkr |SdSr)rgrr%r,r)r)r*rs zPermissionAdmin._complete_listcCsXt|dkr |St|dkr*tt|jt||dt|ddSdSNrKr)rgrrVrr!rrrr)r)r*rs  zPermissionAdmin._complete_addcCsFt|dkr |St|dkr!t||dt|ddSdSr)rgrrVrrr)r)r*rs  "z PermissionAdmin._complete_removecCst|dkr t|dSdS)NrKr)rgrrr)r)r*rs  z'PermissionAdmin._complete_import_exportNcCst|j}|r!g}|j|dd}|D] }||r|||fqn|}|t|tdtdgtt td| }|d |}t t |dddd tdS) NT)rUserActionzAvailable actions:z,   )initial_indentsubsequent_indentlinesep) rr!r?rsrCsortrrprintrrjoinr)r%r[permsysrowsrkr ritextr)r)r*rs*     zPermissionAdmin._do_listcsdtjrttdfdd}t|}|r0||}|dur'dS|||sdSdS)Nz8All upper-cased tokens are reserved for permission namesc sd}z$jj|D]}|q WdWdS1swYWdSty>}z t||WYd}~Sd}~wtyN}zt||d}~wwry)r!rbrEr7rrr)rir er r%r[r)r*grant_actions_atomicallys & z9PermissionAdmin._do_add..grant_actions_atomically)rr!rhrrrremove)r%r[riractions_to_grantaction_that_failedr)rr*rs    zPermissionAdmin._do_addc Gst|j}|}|D]T}d}|D]\}}||dfvr)||dfvr)|||d}q|s_||vrD|||vrDtd||d} t| ||vrUtd||d} t| td|d} t| q dS) NFr TztCannot remove permission %(action)s for user %(user)s. The permission is granted through a meta-permission or group.)r r[zdCannot remove permission %(action)s for user %(user)s. The user has not been granted the permission.rr) rr!rCrFrr?rrr) r%r[rir rr foundrSrr&r)r)r*rs4      zPermissionAdmin._do_removec CszKt|d;}|r tjnd}tj||d}|}t|D]}t||}|dd|g|Dq| WdWdS1sDwYWdSt ye}zt t dt |pZd|jdd}~ww) NwrlineterminatorcSsg|]}|qSr)r))rRsr)r)r*r6sz.PermissionAdmin._do_export..z(Cannot export to %(filename)s: %(error)sstdoutfilenameerror)r osr csvwriterrrLrwriterowflushIOErrorrrrstrerror) r%rfr r!rZr[rirr)r)r*r.s&   & zPermissionAdmin._do_exportc CsJt|j}|r tjnd}zct|dS}tj||d}|D]?}t|dkr-tt d|j d|d}|dd}| rEtt d ||j d | |} t |t | D]} ||| qRqWdWdS1shwYWdStjy} ztt d t|pd |j | d d} ~ wty} ztt dt|pd | jdd} ~ ww)Nrrrrz@Invalid row %(line)d. Expected , , [action], [...])linerrKzaInvalid user %(user)s on line %(line)d: All upper-cased tokens are reserved for permission names.)r[r(z9Cannot import from %(filename)s line %(line)d: %(error)s stdin)rr(rz*Cannot import from %(filename)s: %(error)sr)rr!rr r r readerrgrrline_numrhrrVrEErrorrr$r%) r%rr r r&r*rowr[ri old_actionsr rr)r)r*r>sV     &  zPermissionAdmin._do_importry)r0r1r2r3rnrrrrrrrrrrrrrr)r)r)r*rs  r)2r r itertoolsr trac.adminrrr trac.cacher trac.configrr trac.core trac.resourcer r trac.utilr r trac.util.datefmtrtrac.util.textrrrrrrtrac.util.translationrr__all__ TracBaseErrorrrr7 Interfacerrrr ComponentrJrprurobjectrrr)r)r)r*s6     )l$g