Skip to content

Commit 037ba30

Browse files
committed
fix: delete proxy does not need a group
1 parent 8874013 commit 037ba30

4 files changed

Lines changed: 40 additions & 82 deletions

File tree

src/DIRAC/FrameworkSystem/DB/ProxyDB.py

Lines changed: 19 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1-
""" ProxyDB class is a front-end to the ProxyDB MySQL database.
1+
"""ProxyDB class is a front-end to the ProxyDB MySQL database.
22
3-
Database contains the following tables:
3+
Database contains the following tables:
44
5-
* ProxyDB_Requests -- a delegation requests storage table for a given proxy Chain
6-
* ProxyDB_CleanProxies -- table for storing proxies in "clean" form, ie without
7-
the presence of DIRAC and VOMS extensions.
8-
* ProxyDB_VOMSProxies -- proxy storage table with VOMS extension already added.
9-
* ProxyDB_Log -- table with logs.
5+
* ProxyDB_Requests -- a delegation requests storage table for a given proxy Chain
6+
* ProxyDB_CleanProxies -- table for storing proxies in "clean" form, ie without
7+
the presence of DIRAC and VOMS extensions.
8+
* ProxyDB_VOMSProxies -- proxy storage table with VOMS extension already added.
9+
* ProxyDB_Log -- table with logs.
1010
"""
11+
1112
import textwrap
1213
from threading import Lock
1314

@@ -167,8 +168,7 @@ def generateDelegationRequest(self, proxyChain, userDN):
167168
data = retVal["Value"]
168169
if not data:
169170
return S_ERROR("Insertion of the request in the db didn't work as expected")
170-
userGroup = proxyChain.getDIRACGroup().get("Value") or "unset"
171-
self.logAction("request upload", userDN, userGroup, userDN, "any")
171+
self.logAction("request upload", userDN, userDN)
172172
# Here we go!
173173
return S_OK({"id": data[0][0], "request": reqStr})
174174

@@ -249,8 +249,7 @@ def completeDelegation(self, requestId, userDN, delegatedPem):
249249
return self.deleteRequest(requestId) if retVal["OK"] else retVal
250250

251251
def __storeProxy(self, userDN, chain, proxyProvider=None):
252-
"""Store user proxy into the Proxy repository for a user specified by his
253-
DN and group or proxy provider.
252+
"""Store user proxy into the Proxy repository for a user specified by their DN
254253
255254
:param str userDN: user DN from proxy
256255
:param X509Chain() chain: proxy chain
@@ -353,7 +352,7 @@ def __storeProxy(self, userDN, chain, proxyProvider=None):
353352
sqlSet.append(f"{k} = {dValues[k]}")
354353
cmd = f"UPDATE `{sTable}` SET {', '.join(sqlSet)} WHERE {' AND '.join(sqlWhere)}"
355354

356-
self.logAction("store proxy", userDN, proxyProvider, userDN, proxyProvider)
355+
self.logAction("store proxy", userDN, userDN)
357356
return self._update(cmd)
358357

359358
def purgeExpiredProxies(self, sendNotifications=True):
@@ -376,23 +375,17 @@ def purgeExpiredProxies(self, sendNotifications=True):
376375
return result
377376
return S_OK(purged)
378377

379-
def deleteProxy(self, userDN, userGroup=None, proxyProvider=None):
378+
def deleteProxy(self, userDN):
380379
"""Remove proxy of the given user from the repository
381380
382381
:param str userDN: user DN
383-
:param str userGroup: DIRAC group
384-
:param str proxyProvider: proxy provider name
385382
386383
:return: S_OK()/S_ERROR()
387384
"""
388385
try:
389386
userDN = self._escapeString(userDN)["Value"]
390-
if userGroup:
391-
userGroup = self._escapeString(userGroup)["Value"]
392-
if proxyProvider:
393-
proxyProvider = self._escapeString(proxyProvider)["Value"]
394387
except KeyError:
395-
return S_ERROR("Invalid DN or group or proxy provider")
388+
return S_ERROR("Invalid DN")
396389
errMsgs = []
397390
req = f"DELETE FROM `ProxyDB_CleanProxies` WHERE UserDN={userDN}"
398391
result = self._update(req)
@@ -552,7 +545,7 @@ def __getProxyFromProxyProviders(self, userDN, userGroup, requiredLifeTime):
552545
result = chain.generateProxyToString(remainingSecs, diracGroup=userGroup)
553546
if result["OK"]:
554547
return S_OK((result["Value"], remainingSecs))
555-
errMsgs.append(f"\"{proxyProvider}\": {result['Message']}")
548+
errMsgs.append(f'"{proxyProvider}": {result["Message"]}')
556549

557550
return S_ERROR("Cannot generate proxy%s" % (errMsgs and ": " + ", ".join(errMsgs) or ""))
558551

@@ -592,8 +585,8 @@ def getProxy(self, userDN, userGroup, requiredLifeTime=None):
592585

593586
# Proxy is invalid for some reason, let's delete it
594587
if not chain.isValidProxy()["OK"]:
595-
self.deleteProxy(userDN, userGroup)
596-
return S_ERROR(DErrno.EPROXYFIND, f"{userDN}@{userGroup} has no proxy registered")
588+
self.deleteProxy(userDN)
589+
return S_ERROR(DErrno.EPROXYFIND, f"{userDN} has no proxy registered")
597590
return S_OK((chain, timeLeft))
598591

599592
def __getVOMSAttribute(self, userGroup, requiredVOMSAttribute=False):
@@ -824,27 +817,23 @@ def getProxiesContent(self, selDict, sortList, start=0, limit=0):
824817
totalRecords = len(data)
825818
return S_OK({"ParameterNames": fields, "Records": data, "TotalRecords": totalRecords})
826819

827-
def logAction(self, action, issuerDN, issuerGroup, targetDN, targetGroup):
820+
def logAction(self, action, issuerDN, targetDN):
828821
"""Add an action to the log
829822
830823
:param str action: proxy action
831824
:param str issuerDN: user DN of issuer
832-
:param str issuerGroup: DIRAC group of issuer
833825
:param str targetDN: user DN of target
834-
:param str targetGroup: DIRAC group of target
835826
836827
:return: S_ERROR()
837828
"""
838829
try:
839830
sAction = self._escapeString(action)["Value"]
840831
sIssuerDN = self._escapeString(issuerDN)["Value"]
841-
sIssuerGroup = self._escapeString(issuerGroup)["Value"]
842832
sTargetDN = self._escapeString(targetDN)["Value"]
843-
sTargetGroup = self._escapeString(targetGroup)["Value"]
844833
except KeyError:
845834
return S_ERROR("Can't escape from death")
846-
cmd = "INSERT INTO `ProxyDB_Log` ( Action, IssuerDN, IssuerGroup, TargetDN, TargetGroup, Timestamp ) VALUES "
847-
cmd += f"( {sAction}, {sIssuerDN}, {sIssuerGroup}, {sTargetDN}, {sTargetGroup}, UTC_TIMESTAMP() )"
835+
cmd = "INSERT INTO `ProxyDB_Log` ( Action, IssuerDN, 'Group', TargetDN, 'TargetGroup', Timestamp ) VALUES "
836+
cmd += f"( {sAction}, {sIssuerDN}, {sTargetDN}, UTC_TIMESTAMP() )"
848837
retVal = self._update(cmd)
849838
if not retVal["OK"]:
850839
self.log.error("Can't add a proxy action log: ", retVal["Message"])

src/DIRAC/FrameworkSystem/Service/ProxyManagerHandler.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def export_completeDelegationUpload(self, requestId, pemChain):
102102
:return: S_OK(dict)/S_ERROR() -- dict contain proxies
103103
"""
104104
credDict = self.getRemoteCredentials()
105-
userId = f'{credDict["username"]}:{credDict["group"]}'
105+
userId = f"{credDict['username']}:{credDict['group']}"
106106
retVal = self.__proxyDB.completeDelegation(requestId, credDict["DN"], pemChain)
107107
if not retVal["OK"]:
108108
gLogger.error("Upload proxy failed", f"id: {requestId} user: {userId} message: {retVal['Message']}")
@@ -240,7 +240,7 @@ def __getVOMSProxy(self, userDN, userGroup, requestPem, requiredLifetime, vomsAt
240240
requiredLifetime = int(min(secsLeft, requiredLifetime * self.__maxExtraLifeFactor))
241241
return chain.generateChainFromRequestString(requestPem, lifetime=requiredLifetime, requireLimited=forceLimited)
242242

243-
types_deleteProxyBundle = [(list, tuple)]
243+
types_deleteProxyBundle = [list]
244244

245245
def export_deleteProxyBundle(self, idList):
246246
"""delete a list of id's
@@ -252,9 +252,7 @@ def export_deleteProxyBundle(self, idList):
252252
errorInDelete = []
253253
deleted = 0
254254
for _id in idList:
255-
if len(_id) != 2:
256-
errorInDelete.append(f"{str(_id)} doesn't have two fields")
257-
retVal = self.export_deleteProxy(_id[0], _id[1])
255+
retVal = self.export_deleteProxy(_id)
258256
if not retVal["OK"]:
259257
errorInDelete.append(f"{str(_id)} : {retVal['Message']}")
260258
else:
@@ -265,22 +263,21 @@ def export_deleteProxyBundle(self, idList):
265263

266264
types_deleteProxy = [(list, tuple)]
267265

268-
def export_deleteProxy(self, userDN, userGroup):
266+
def export_deleteProxy(self, userDN):
269267
"""Delete a proxy from the DB
270268
271269
:param str userDN: user DN
272-
:param str userGroup: DIRAC group
273270
274271
:return: S_OK()/S_ERROR()
275272
"""
276273
credDict = self.getRemoteCredentials()
277274
if Properties.PROXY_MANAGEMENT not in credDict["properties"]:
278275
if userDN != credDict["DN"]:
279276
return S_ERROR("You aren't allowed!")
280-
retVal = self.__proxyDB.deleteProxy(userDN, userGroup)
277+
retVal = self.__proxyDB.deleteProxy(userDN)
281278
if not retVal["OK"]:
282279
return retVal
283-
self.__proxyDB.logAction("delete proxy", credDict["DN"], credDict["group"], userDN, userGroup)
280+
self.__proxyDB.logAction("delete proxy", credDict["DN"], userDN)
284281
return S_OK()
285282

286283
types_getContents = [dict, (list, tuple), int, int]

src/DIRAC/FrameworkSystem/scripts/dirac_proxy_destroy.py

Lines changed: 7 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@
55
Example:
66
$ dirac-proxy-destroy -a
77
"""
8+
89
import os
910

1011
import DIRAC
1112
from DIRAC import S_OK, gLogger
1213
from DIRAC.ConfigurationSystem.Client.Helpers import Registry
13-
from DIRAC.Core.Base.Client import Client
1414
from DIRAC.Core.Base.Script import Script
1515
from DIRAC.Core.Security import Locations, ProxyInfo
1616
from DIRAC.FrameworkSystem.Client.ProxyManagerClient import gProxyManager
@@ -59,22 +59,6 @@ def registerCLISwitches(self):
5959
Script.registerSwitch("v:", "vo=", "Delete uploaded proxy for vo name given", self.addVO)
6060

6161

62-
def getProxyGroups():
63-
"""
64-
Returns a set of all remote proxy groups stored on the dirac server for the user invoking the command.
65-
"""
66-
proxies = gProxyManager.getUserProxiesInfo()
67-
if not proxies["OK"]:
68-
raise RuntimeError("Could not retrieve uploaded proxy info.")
69-
70-
user_groups = set()
71-
for dn in proxies["Value"]:
72-
dn_groups = set(proxies["Value"][dn].keys())
73-
user_groups.update(dn_groups)
74-
75-
return user_groups
76-
77-
7862
def mapVoToGroups(voname):
7963
"""
8064
Returns all groups available for a given VO as a set.
@@ -87,18 +71,17 @@ def mapVoToGroups(voname):
8771
return set(vo_dict["Value"])
8872

8973

90-
def deleteRemoteProxy(userdn, vogroup):
74+
def deleteRemoteProxy(userdn):
9175
"""
9276
Deletes proxy for a vogroup for the user envoking this function.
9377
Returns a list of all deleted proxies (if any).
9478
"""
95-
rpcClient = Client(url="Framework/ProxyManager")
96-
retVal = rpcClient.deleteProxyBundle([(userdn, vogroup)])
79+
retVal = gProxyManager.deleteProxyBundle([(userdn)])
9780

9881
if retVal["OK"]:
99-
gLogger.notice(f"Deleted proxy for {vogroup}.")
82+
gLogger.notice("Deleted proxy.")
10083
else:
101-
gLogger.error(f"Failed to delete proxy for {vogroup}.")
84+
gLogger.error("Failed to delete proxy.")
10285

10386

10487
def deleteLocalProxy(proxyLoc):
@@ -143,25 +126,15 @@ def run():
143126
userDN = result["Value"]["identity"]
144127

145128
if options.delete_all:
146-
# delete remote proxies
147-
remote_groups = getProxyGroups()
148-
if not remote_groups:
149-
gLogger.notice("No remote proxies found.")
150-
for vo_group in remote_groups:
151-
deleteRemoteProxy(userDN, vo_group)
129+
deleteRemoteProxy(userDN)
152130
# delete local proxy
153131
deleteLocalProxy(proxyLoc)
154132
elif options.vos:
155133
vo_groups = set()
156134
for voname in options.vos:
157135
vo_groups.update(mapVoToGroups(voname))
158136
# filter set of all groups to only contain groups for which there is a user proxy
159-
user_groups = getProxyGroups()
160-
vo_groups.intersection_update(user_groups)
161-
if not vo_groups:
162-
gLogger.notice("You have no proxies registered for any of the specified VOs.")
163-
for group in vo_groups:
164-
deleteRemoteProxy(userDN, group)
137+
deleteRemoteProxy(userDN)
165138
else:
166139
deleteLocalProxy(proxyLoc)
167140

tests/Integration/Framework/Test_ProxyDB.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
""" This is a test of the ProxyDB
2-
It supposes that the DB is present and installed in DIRAC
1+
"""This is a test of the ProxyDB
2+
It supposes that the DB is present and installed in DIRAC
33
"""
4+
45
# pylint: disable=invalid-name,wrong-import-position,protected-access
56
import os
67
import re
@@ -39,8 +40,8 @@
3940
DIRAC_CA
4041
{{
4142
ProviderType = DIRACCA
42-
CertFile = {os.path.join(certsPath, 'ca/ca.cert.pem')}
43-
KeyFile = {os.path.join(certsPath, 'ca/ca.key.pem')}
43+
CertFile = {os.path.join(certsPath, "ca/ca.cert.pem")}
44+
KeyFile = {os.path.join(certsPath, "ca/ca.key.pem")}
4445
Supplied = C, O, OU, CN
4546
Optional = emailAddress
4647
DNOrder = C, O, OU, CN, emailAddress
@@ -391,7 +392,7 @@ def test_purgeExpiredProxies(self):
391392
def test_getRemoveProxy(self):
392393
"""Testing get, store proxy"""
393394
gLogger.info("\n* Check that DB is clean..")
394-
result = db.getProxiesContent({"UserName": ["user_ca", "user", "user_1" "user_2", "user_3"]}, {})
395+
result = db.getProxiesContent({"UserName": ["user_ca", "user", "user_1user_2", "user_3"]}, {})
395396
self.assertTrue(result["OK"], "\n" + result.get("Message", "Error message is absent."))
396397
self.assertTrue(bool(int(result["Value"]["TotalRecords"]) == 0), "In DB present proxies.")
397398

@@ -441,9 +442,7 @@ def test_getRemoveProxy(self):
441442
)
442443

443444
gLogger.info("* Check that DB is clean..")
444-
result = db.deleteProxy(
445-
"/C=DN/O=DIRACCA/OU=None/CN=user_ca/emailAddress=user_ca@diracgrid.org", proxyProvider="DIRAC_CA"
446-
)
445+
result = db.deleteProxy("/C=DN/O=DIRACCA/OU=None/CN=user_ca/emailAddress=user_ca@diracgrid.org")
447446
self.assertTrue(result["OK"], "\n" + result.get("Message", "Error message is absent."))
448447
result = db.getProxiesContent({"UserName": ["user_ca", "user", "user_1", "user_2", "user_3"]}, {})
449448
self.assertTrue(result["OK"], "\n" + result.get("Message", "Error message is absent."))
@@ -523,7 +522,7 @@ def test_getRemoveProxy(self):
523522
gLogger.info(f"Msg: {result['Message']}")
524523

525524
gLogger.info("* Check that DB is clean..")
526-
result = db.deleteProxy("/C=CC/O=DN/O=DIRAC/CN=user", proxyProvider="Certificate")
525+
result = db.deleteProxy("/C=CC/O=DN/O=DIRAC/CN=user")
527526
self.assertTrue(result["OK"], "\n" + result.get("Message", "Error message is absent."))
528527
result = db.getProxiesContent({"UserName": ["user_ca", "user", "user_2", "user_3"]}, {})
529528
self.assertTrue(result["OK"], "\n" + result.get("Message", "Error message is absent."))

0 commit comments

Comments
 (0)