Skip to content

Commit e4a032d

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

File tree

4 files changed

+41
-115
lines changed

4 files changed

+41
-115
lines changed

src/DIRAC/FrameworkSystem/DB/ProxyDB.py

Lines changed: 18 additions & 29 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")
846835
cmd = "INSERT INTO `ProxyDB_Log` ( Action, IssuerDN, IssuerGroup, TargetDN, TargetGroup, Timestamp ) VALUES "
847-
cmd += f"( {sAction}, {sIssuerDN}, {sIssuerGroup}, {sTargetDN}, {sTargetGroup}, UTC_TIMESTAMP() )"
836+
cmd += f"( {sAction}, {sIssuerDN}, 'IssuerGroup' {sTargetDN}, 'TargetGroup', 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: 7 additions & 10 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:
@@ -263,24 +261,23 @@ def export_deleteProxyBundle(self, idList):
263261
return S_ERROR(f"Could not delete some proxies: {','.join(errorInDelete)}")
264262
return S_OK(deleted)
265263

266-
types_deleteProxy = [(list, tuple)]
264+
types_deleteProxy = [str]
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: 8 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@
55
Example:
66
$ dirac-proxy-destroy -a
77
"""
8+
89
import os
910

1011
import DIRAC
1112
from DIRAC import S_OK, gLogger
12-
from DIRAC.ConfigurationSystem.Client.Helpers import Registry
13-
from DIRAC.Core.Base.Client import Client
1413
from DIRAC.Core.Base.Script import Script
1514
from DIRAC.Core.Security import Locations, ProxyInfo
1615
from DIRAC.FrameworkSystem.Client.ProxyManagerClient import gProxyManager
@@ -25,16 +24,8 @@ def __init__(self):
2524
"""
2625
creates a Params class with default values
2726
"""
28-
self.vos = []
2927
self.delete_all = False
3028

31-
def addVO(self, voname):
32-
"""
33-
adds a VO to be deleted from remote proxies
34-
"""
35-
self.vos.append(voname)
36-
return S_OK()
37-
3829
def setDeleteAll(self, _):
3930
"""
4031
deletes local and remote proxies
@@ -46,7 +37,7 @@ def needsValidProxy(self):
4637
"""
4738
returns true if any remote operations are required
4839
"""
49-
return self.vos or self.delete_all
40+
return self.delete_all
5041

5142
# note the magic : and =
5243
def registerCLISwitches(self):
@@ -56,49 +47,19 @@ def registerCLISwitches(self):
5647
Script.registerSwitch(
5748
"a", "all", "Delete the local and all uploaded proxies (the nuclear option)", self.setDeleteAll
5849
)
59-
Script.registerSwitch("v:", "vo=", "Delete uploaded proxy for vo name given", self.addVO)
60-
61-
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)
7450

75-
return user_groups
7651

77-
78-
def mapVoToGroups(voname):
79-
"""
80-
Returns all groups available for a given VO as a set.
81-
"""
82-
83-
vo_dict = Registry.getGroupsForVO(voname)
84-
if not vo_dict["OK"]:
85-
raise RuntimeError(f"Could not retrieve groups for vo {voname}.")
86-
87-
return set(vo_dict["Value"])
88-
89-
90-
def deleteRemoteProxy(userdn, vogroup):
52+
def deleteRemoteProxy(userdn):
9153
"""
9254
Deletes proxy for a vogroup for the user envoking this function.
9355
Returns a list of all deleted proxies (if any).
9456
"""
95-
rpcClient = Client(url="Framework/ProxyManager")
96-
retVal = rpcClient.deleteProxyBundle([(userdn, vogroup)])
57+
retVal = gProxyManager.deleteProxyBundle([(userdn)])
9758

9859
if retVal["OK"]:
99-
gLogger.notice(f"Deleted proxy for {vogroup}.")
60+
gLogger.notice("Deleted proxy.")
10061
else:
101-
gLogger.error(f"Failed to delete proxy for {vogroup}.")
62+
gLogger.error("Failed to delete proxy.")
10263

10364

10465
def deleteLocalProxy(proxyLoc):
@@ -123,7 +84,7 @@ def run():
12384

12485
Script.parseCommandLine(ignoreErrors=True)
12586

126-
if options.delete_all and options.vos:
87+
if options.delete_all:
12788
gLogger.error("-a and -v options are mutually exclusive. Please pick one or the other.")
12889
return 1
12990

@@ -142,27 +103,8 @@ def run():
142103

143104
userDN = result["Value"]["identity"]
144105

106+
deleteRemoteProxy(userDN)
145107
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)
152-
# delete local proxy
153-
deleteLocalProxy(proxyLoc)
154-
elif options.vos:
155-
vo_groups = set()
156-
for voname in options.vos:
157-
vo_groups.update(mapVoToGroups(voname))
158-
# 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)
165-
else:
166108
deleteLocalProxy(proxyLoc)
167109

168110
return 0

tests/Integration/Framework/Test_ProxyDB.py

Lines changed: 8 additions & 10 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
@@ -19,7 +20,6 @@
1920

2021
DIRAC.initialize(require_auth=False, host_credentials=True) # Initialize configuration
2122

22-
import DIRAC
2323
from DIRAC import gLogger, gConfig, S_OK, S_ERROR
2424
from DIRAC.Core.Security.X509Chain import X509Chain # pylint: disable=import-error
2525
from DIRAC.FrameworkSystem.DB.ProxyDB import ProxyDB
@@ -39,8 +39,8 @@
3939
DIRAC_CA
4040
{{
4141
ProviderType = DIRACCA
42-
CertFile = {os.path.join(certsPath, 'ca/ca.cert.pem')}
43-
KeyFile = {os.path.join(certsPath, 'ca/ca.key.pem')}
42+
CertFile = {os.path.join(certsPath, "ca/ca.cert.pem")}
43+
KeyFile = {os.path.join(certsPath, "ca/ca.key.pem")}
4444
Supplied = C, O, OU, CN
4545
Optional = emailAddress
4646
DNOrder = C, O, OU, CN, emailAddress
@@ -391,7 +391,7 @@ def test_purgeExpiredProxies(self):
391391
def test_getRemoveProxy(self):
392392
"""Testing get, store proxy"""
393393
gLogger.info("\n* Check that DB is clean..")
394-
result = db.getProxiesContent({"UserName": ["user_ca", "user", "user_1" "user_2", "user_3"]}, {})
394+
result = db.getProxiesContent({"UserName": ["user_ca", "user", "user_1", "user_2", "user_3"]}, {})
395395
self.assertTrue(result["OK"], "\n" + result.get("Message", "Error message is absent."))
396396
self.assertTrue(bool(int(result["Value"]["TotalRecords"]) == 0), "In DB present proxies.")
397397

@@ -441,9 +441,7 @@ def test_getRemoveProxy(self):
441441
)
442442

443443
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-
)
444+
result = db.deleteProxy("/C=DN/O=DIRACCA/OU=None/CN=user_ca/emailAddress=user_ca@diracgrid.org")
447445
self.assertTrue(result["OK"], "\n" + result.get("Message", "Error message is absent."))
448446
result = db.getProxiesContent({"UserName": ["user_ca", "user", "user_1", "user_2", "user_3"]}, {})
449447
self.assertTrue(result["OK"], "\n" + result.get("Message", "Error message is absent."))
@@ -523,7 +521,7 @@ def test_getRemoveProxy(self):
523521
gLogger.info(f"Msg: {result['Message']}")
524522

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

0 commit comments

Comments
 (0)