fix exploit that allowed an authorities to issue certs for objects that dont belong...
[sfa.git] / sfa / util / xrn.py
1 #----------------------------------------------------------------------\r
2 # Copyright (c) 2008 Board of Trustees, Princeton University\r
3 #\r
4 # Permission is hereby granted, free of charge, to any person obtaining\r
5 # a copy of this software and/or hardware specification (the "Work") to\r
6 # deal in the Work without restriction, including without limitation the\r
7 # rights to use, copy, modify, merge, publish, distribute, sublicense,\r
8 # and/or sell copies of the Work, and to permit persons to whom the Work\r
9 # is furnished to do so, subject to the following conditions:\r
10 #\r
11 # The above copyright notice and this permission notice shall be\r
12 # included in all copies or substantial portions of the Work.\r
13 #\r
14 # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS \r
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \r
16 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \r
17 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \r
18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \r
19 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \r
20 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS \r
21 # IN THE WORK.\r
22 #----------------------------------------------------------------------\r
23 \r
24 import re\r
25 \r
26 from sfa.util.faults import *\r
27 \r
28 # for convenience and smoother translation - we should get rid of these functions eventually \r
29 def get_leaf(hrn): return Xrn(hrn).get_leaf()\r
30 def get_authority(hrn): return Xrn(hrn).get_authority_hrn()\r
31 def urn_to_hrn(urn): xrn=Xrn(urn); return (xrn.hrn, xrn.type)\r
32 def hrn_to_urn(hrn,type): return Xrn(hrn, type=type).urn\r
33 def hrn_authfor_hrn(parenthrn, hrn): return Xrn.hrn_is_auth_for_hrn(parenthrn, hrn)\r
34 \r
35 class Xrn:\r
36 \r
37     ########## basic tools on HRNs\r
38     # split a HRN-like string into pieces\r
39     # this is like split('.') except for escaped (backslashed) dots\r
40     # e.g. hrn_split ('a\.b.c.d') -> [ 'a\.b','c','d']\r
41     @staticmethod\r
42     def hrn_split(hrn):\r
43         return [ x.replace('--sep--','\\.') for x in hrn.replace('\\.','--sep--').split('.') ]\r
44 \r
45     # e.g. hrn_leaf ('a\.b.c.d') -> 'd'\r
46     @staticmethod\r
47     def hrn_leaf(hrn): return Xrn.hrn_split(hrn)[-1]\r
48 \r
49     # e.g. hrn_auth_list ('a\.b.c.d') -> ['a\.b', 'c']\r
50     @staticmethod\r
51     def hrn_auth_list(hrn): return Xrn.hrn_split(hrn)[0:-1]\r
52     \r
53     # e.g. hrn_auth ('a\.b.c.d') -> 'a\.b.c'\r
54     @staticmethod\r
55     def hrn_auth(hrn): return '.'.join(Xrn.hrn_auth_list(hrn))\r
56     \r
57     # e.g. escape ('a.b') -> 'a\.b'\r
58     @staticmethod\r
59     def escape(token): return re.sub(r'([^\\])\.', r'\1\.', token)\r
60 \r
61     # e.g. unescape ('a\.b') -> 'a.b'\r
62     @staticmethod\r
63     def unescape(token): return token.replace('\\.','.')\r
64 \r
65     # Return the HRN authority chain from top to bottom.\r
66     # e.g. hrn_auth_chain('a\.b.c.d') -> ['a\.b', 'a\.b.c']\r
67     @staticmethod\r
68     def hrn_auth_chain(hrn):\r
69         parts = Xrn.hrn_auth_list(hrn)\r
70         chain = []\r
71         for i in range(len(parts)):\r
72             chain.append('.'.join(parts[:i+1]))\r
73         # Include the HRN itself?\r
74         #chain.append(hrn)\r
75         return chain\r
76 \r
77     # Is the given HRN a true authority over the namespace of the other\r
78     # child HRN?\r
79     # A better alternative than childHRN.startswith(parentHRN)\r
80     # e.g. hrn_is_auth_for_hrn('a\.b', 'a\.b.c.d') -> True,\r
81     # but hrn_is_auth_for_hrn('a', 'a\.b.c.d') -> False\r
82     # Also hrn_is_uauth_for_hrn('a\.b.c.d', 'a\.b.c.d') -> True\r
83     @staticmethod\r
84     def hrn_is_auth_for_hrn(parenthrn, hrn):\r
85         if parenthrn == hrn:\r
86             return True\r
87         for auth in Xrn.hrn_auth_chain(hrn):\r
88             if parenthrn == auth:\r
89                 return True\r
90         return False\r
91 \r
92     URN_PREFIX = "urn:publicid:IDN"\r
93 \r
94     ########## basic tools on URNs\r
95     @staticmethod\r
96     def urn_full (urn):\r
97         if urn.startswith(Xrn.URN_PREFIX): return urn\r
98         else: return Xrn.URN_PREFIX+URN\r
99     @staticmethod\r
100     def urn_meaningful (urn):\r
101         if urn.startswith(Xrn.URN_PREFIX): return urn[len(Xrn.URN_PREFIX):]\r
102         else: return urn\r
103     @staticmethod\r
104     def urn_split (urn):\r
105         return Xrn.urn_meaningful(urn).split('+')\r
106 \r
107     ####################\r
108     # the local fields that are kept consistent\r
109     # self.urn\r
110     # self.hrn\r
111     # self.type\r
112     # self.path\r
113     # provide either urn, or (hrn + type)\r
114     def __init__ (self, xrn, type=None):\r
115         if not xrn: xrn = ""\r
116         # user has specified xrn : guess if urn or hrn\r
117         if xrn.startswith(Xrn.URN_PREFIX):\r
118             self.hrn=None\r
119             self.urn=xrn\r
120             self.urn_to_hrn()\r
121         else:\r
122             self.urn=None\r
123             self.hrn=xrn\r
124             self.type=type\r
125             self.hrn_to_urn()\r
126 # happens all the time ..\r
127 #        if not type:\r
128 #            debug_logger.debug("type-less Xrn's are not safe")\r
129 \r
130     def get_urn(self): return self.urn\r
131     def get_hrn(self): return self.hrn\r
132     def get_type(self): return self.type\r
133     def get_hrn_type(self): return (self.hrn, self.type)\r
134 \r
135     def _normalize(self):\r
136         if self.hrn is None: raise SfaAPIError, "Xrn._normalize"\r
137         if not hasattr(self,'leaf'): \r
138             self.leaf=Xrn.hrn_split(self.hrn)[-1]\r
139         # self.authority keeps a list\r
140         if not hasattr(self,'authority'): \r
141             self.authority=Xrn.hrn_auth_list(self.hrn)\r
142 \r
143     def get_leaf(self):\r
144         self._normalize()\r
145         return self.leaf\r
146 \r
147     def get_authority_hrn(self): \r
148         self._normalize()\r
149         return '.'.join( self.authority )\r
150     \r
151     def get_authority_urn(self): \r
152         self._normalize()\r
153         return ':'.join( [Xrn.unescape(x) for x in self.authority] )\r
154     \r
155     def urn_to_hrn(self):\r
156         """\r
157         compute tuple (hrn, type) from urn\r
158         """\r
159         \r
160 #        if not self.urn or not self.urn.startswith(Xrn.URN_PREFIX):\r
161         if not self.urn.startswith(Xrn.URN_PREFIX):\r
162             raise SfaAPIError, "Xrn.urn_to_hrn"\r
163 \r
164         parts = Xrn.urn_split(self.urn)\r
165         type=parts.pop(2)\r
166         # Remove the authority name (e.g. '.sa')\r
167         if type == 'authority':\r
168             name = parts.pop()\r
169             # Drop the sa. This is a bad hack, but its either this\r
170             # or completely change how record types are generated/stored   \r
171             if name != 'sa':\r
172                 type = type + "+" + name\r
173 \r
174         # convert parts (list) into hrn (str) by doing the following\r
175         # 1. remove blank parts\r
176         # 2. escape dots inside parts\r
177         # 3. replace ':' with '.' inside parts\r
178         # 3. join parts using '.' \r
179         hrn = '.'.join([Xrn.escape(part).replace(':','.') for part in parts if part]) \r
180 \r
181         self.hrn=str(hrn)\r
182         self.type=str(type)\r
183     \r
184     def hrn_to_urn(self):\r
185         """\r
186         compute urn from (hrn, type)\r
187         """\r
188 \r
189 #        if not self.hrn or self.hrn.startswith(Xrn.URN_PREFIX):\r
190         if self.hrn.startswith(Xrn.URN_PREFIX):\r
191             raise SfaAPIError, "Xrn.hrn_to_urn, hrn=%s"%self.hrn\r
192 \r
193         if self.type and self.type.startswith('authority'):\r
194             self.authority = Xrn.hrn_split(self.hrn)\r
195             type_parts = self.type.split("+")\r
196             self.type = type_parts[0]\r
197             name = 'sa'\r
198             if len(type_parts) > 1:\r
199                 name = type_parts[1]\r
200         else:\r
201             self.authority = Xrn.hrn_auth_list(self.hrn)\r
202             name = Xrn.hrn_leaf(self.hrn)\r
203 \r
204         authority_string = self.get_authority_urn()\r
205 \r
206         if self.type == None:\r
207             urn = "+".join(['',authority_string,Xrn.unescape(name)])\r
208         else:\r
209             urn = "+".join(['',authority_string,self.type,Xrn.unescape(name)])\r
210         \r
211         self.urn = Xrn.URN_PREFIX + urn\r
212 \r
213     def dump_string(self):\r
214         result="-------------------- XRN\n"\r
215         result += "URN=%s\n"%self.urn\r
216         result += "HRN=%s\n"%self.hrn\r
217         result += "TYPE=%s\n"%self.type\r
218         result += "LEAF=%s\n"%self.get_leaf()\r
219         result += "AUTH(hrn format)=%s\n"%self.get_authority_hrn()\r
220         result += "AUTH(urn format)=%s\n"%self.get_authority_urn()\r
221         return result\r
222         \r