Coverage for python/lsst/ctrl/bps/panda/panda_auth_utils.py: 21%
42 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-10-10 01:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-10-10 01:39 -0700
1# This file is part of ctrl_bps_panda.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28"""Functions for each panda_auth subcommand."""
30__all__ = [
31 "panda_auth_clean",
32 "panda_auth_expiration",
33 "panda_auth_setup",
34 "panda_auth_status",
35 "panda_auth_update",
36]
39import logging
40import os
42import idds.common.utils as idds_utils
43import pandaclient.idds_api
44from pandaclient.openidc_utils import OpenIdConnect_Utils
46_LOG = logging.getLogger(__name__)
49def panda_auth_clean():
50 """Clean up token and token cache files."""
51 open_id = panda_auth_setup()
52 open_id.cleanup()
55def panda_auth_expiration():
56 """Get number of seconds until token expires.
58 Returns
59 -------
60 expiration : `int`
61 Number of seconds until token expires.
62 """
63 expiration = 0
64 ret = panda_auth_status()
65 if ret:
66 expiration = ret[-1]["exp"]
67 return expiration
70def panda_auth_setup():
71 """Initialize auth object used by various auth functions.
73 Returns
74 -------
75 open_id : `pandaclient.openidc_utils.OpenIdConnect_Utils`
76 Auth object which can interact with auth token.
77 """
78 for key in [
79 "PANDA_AUTH",
80 "PANDA_VERIFY_HOST",
81 "PANDA_AUTH_VO",
82 "PANDA_URL_SSL",
83 "PANDA_URL",
84 ]:
85 if key not in os.environ:
86 raise OSError(f"Missing environment variable {key}")
88 # OpenIdConnect_Utils have a verbose flag that filters
89 # some debugging messages. If user chose debug, just
90 # turn on all of the messages.
91 verbose = False
92 if _LOG.isEnabledFor(logging.DEBUG):
93 verbose = True
95 open_id = OpenIdConnect_Utils(None, log_stream=_LOG, verbose=verbose)
96 return open_id
99def panda_auth_status():
100 """Gather information about a token if it exists.
102 Returns
103 -------
104 status : `dict`
105 Status information about a token if it exists.
106 Includes filename and expiration epoch.
107 """
108 status = None
109 open_id = panda_auth_setup()
110 ret = open_id.check_token()
111 if ret and ret[0]:
112 # get_token_path will return the path even if a token doesn't
113 # currently exist. So check for token first via check_token, then
114 # add path.
115 status = {"filename": open_id.get_token_path()}
116 status.update(ret[-1])
117 return status
120def panda_auth_update(idds_server=None, reset=False):
121 """Get new auth token if needed or reset is True.
123 Parameters
124 ----------
125 idds_server : `str`, optional
126 URL for the iDDS server. Defaults to None which means that the
127 underlying functions use any value in the panda relay service.
128 reset : `bool`, optional
129 Whether to first clean up any previous token. Defaults to False.
130 """
131 if reset:
132 panda_auth_clean()
134 # Create client manager
135 # (There is a function in OpenIdConnect_Utils, but it takes several
136 # parameters. Letting the client manager do it is currently easiest
137 # way to match what happens when the workflow is actually submitted.)
138 cm = pandaclient.idds_api.get_api(
139 idds_utils.json_dumps, idds_host=idds_server, compress=True, manager=True, verbose=False
140 )
142 # Must call some function to actually check auth
143 # https://panda-wms.readthedocs.io/en/latest/client/notebooks/jupyter_setup.html#Get-an-OIDC-ID-token
144 ret = cm.get_status(request_id=0, with_detail=False)
145 _LOG.debug("get_status results: %s", ret)
147 # Check success
148 # https://panda-wms.readthedocs.io/en/latest/client/rest_idds.html
149 if ret[0] == 0 and ret[1][0]:
150 # The success keys from get_status currently do not catch if invalid
151 # idds server given. So for now, check result string for keywords.
152 if "request_id" not in ret[1][-1] or "status" not in ret[1][-1]:
153 raise RuntimeError(f"Error contacting PanDA service: {ret}")