Debian Codegraph @

src/globus_sdk/local_endpoint/personal/owner_info.py

raw
1 from __future__ import annotations
2
3 import base64
4 import shlex
5 import uuid
6
7
8 class _B32DecodeError(ValueError):
9 """custom exception type"""
10
11
12 def _b32decode(v: str) -> str:
13 # should start with "u_"
14 if not v.startswith("u_"):
15 raise _B32DecodeError("should start with 'u_'")
16 v = v[2:]
17 # wrong length
18 if len(v) != 26:
19 raise _B32DecodeError("wrong length")
20
21 # append padding and uppercase so that b32decode will work
22 v = v.upper() + (6 * "=")
23
24 # try to decode
25 try:
26 return str(uuid.UUID(bytes=base64.b32decode(v)))
27 # if it fails, then it can't be a b32-encoded identity
28 except ValueError as err:
29 raise _B32DecodeError("decode and load as UUID failed") from err
30
31
32 def _parse_dn_username(s: str) -> tuple[str, bool]:
33 try:
34 user, is_id = _b32decode(s), True
35 except _B32DecodeError:
36 user, is_id = f"{s}@globusid.org", False
37 return (user, is_id)
38
39
40 class GlobusConnectPersonalOwnerInfo:
41 """
42 Information about the owner of the local Globus Connect Personal endpoint.
43
44 Users should never create these objects directly, but instead rely upon
45 :meth:`LocalGlobusConnectPersonal.get_owner_info()`.
46
47 The info object contains ether ``id`` or ``username``.
48 Parsing an info object from local data cannot guarantee that the ``id`` or
49 ``username`` value will be found. Whichever one is present will be set and the
50 other attribute will be ``None``.
51
52 :ivar id: The Globus Auth ID of the endpoint owner
53 :vartype id: str or None
54 :ivar username: The Globus Auth Username of the endpoint owner
55 :vartype username: str or None
56 :param config_dn: A DN value from GCP configuration, which will be parsed into
57 username or ID
58 """
59
60 _GRIDMAP_DN_START = '"/C=US/O=Globus Consortium/OU=Globus Connect User/CN='
61
62 username: str | None
63 id: str | None
64
65 def __init__(self, *, config_dn: str) -> None:
66 lineinfo = shlex.split(config_dn)
67 if len(lineinfo) != 2:
68 raise ValueError("Malformed DN: not right length")
69 dn, _local_username = lineinfo
70 username_or_id = dn.split("=", 4)[-1]
71
72 user, is_id = _parse_dn_username(username_or_id)
73
74 if is_id:
75 self.username = None
76 self.id = user
77 else:
78 self.username = user
79 self.id = None
80
81 def __str__(self) -> str:
82 return (
83 "GlobusConnectPersonalOwnerInfo("
84 + (
85 f"username={self.username}"
86 if self.username is not None
87 else f"id={self.id}"
88 )
89 + ")"
90 )
91
92 # private methods for SDK usage only
93 @classmethod
94 def _from_file(cls, filename: str) -> GlobusConnectPersonalOwnerInfo:
95 with open(filename, encoding="utf-8") as fp:
96 for line in fp:
97 if line.startswith(cls._GRIDMAP_DN_START):
98 return cls(config_dn=line.strip())
99 raise ValueError("Could not find GCP DN in data stream")