Skip to content

Commit e29d843

Browse files
chrisburrfstagni
authored andcommitted
feat: Enable re-use of DiracX token from proxy
1 parent 407a3af commit e29d843

File tree

2 files changed

+13
-9
lines changed

2 files changed

+13
-9
lines changed

src/DIRAC/Core/Security/DiracX.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@
1010

1111
import base64
1212
import functools
13+
import hashlib
1314
import importlib
1415
import json
1516
import re
1617
import textwrap
1718
from collections.abc import Iterator
1819
from contextlib import contextmanager
1920
from pathlib import Path
20-
from tempfile import NamedTemporaryFile
21+
from tempfile import NamedTemporaryFile, gettempdir
2122
from typing import Any
2223

2324
try:
@@ -30,6 +31,7 @@
3031
from diracx.core.utils import serialize_credentials
3132

3233
from DIRAC import gConfig, gLogger
34+
from DIRAC.Core.Utilities.File import secureOpenForWrite
3335

3436
from DIRAC.ConfigurationSystem.Client.Helpers import Registry
3537
from DIRAC.Core.Security.Locations import getDefaultProxyLocation
@@ -98,14 +100,16 @@ def DiracXClient() -> Iterator[SyncDiracClient]:
98100
if not diracxToken:
99101
raise ValueError(f"No diracx token in the proxy file {proxyLocation}")
100102

101-
with NamedTemporaryFile(mode="wt") as token_file:
102-
token_file.write(json.dumps(diracxToken))
103-
token_file.flush()
104-
token_file.seek(0)
103+
hash = hashlib.sha256(diracxToken["refresh_token"].split(".")[1].encode())
104+
token_file = Path(gettempdir()) / f"dx_{hash.hexdigest()}"
105+
if not token_file.exists():
106+
token_file.parent.mkdir(parents=True, exist_ok=True)
107+
with secureOpenForWrite(token_file) as (fd, _):
108+
fd.write(json.dumps(diracxToken))
105109

106-
pref = DiracxPreferences(url=diracxUrl, credentials_path=token_file.name)
107-
with SyncDiracClient(diracx_preferences=pref) as api:
108-
yield api
110+
pref = DiracxPreferences(url=diracxUrl, credentials_path=token_file)
111+
with SyncDiracClient(diracx_preferences=pref) as api:
112+
yield api
109113

110114

111115
def addRPCStub(meth):

src/DIRAC/Core/Utilities/File.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ def secureOpenForWrite(filename=None, *, text=True):
273273
)
274274
else:
275275
fd, filename = tempfile.mkstemp(text=text)
276-
with open(fd, "w" if text else "wb", encoding="ascii" if text else None) as fd:
276+
with open(fd, "w" if text else "wb", encoding="utf-8" if text else None) as fd:
277277
yield fd, filename
278278

279279

0 commit comments

Comments
 (0)