autopep8
authorparmentelat <thierry.parmentelat@inria.fr>
Thu, 13 Dec 2018 15:14:27 +0000 (16:14 +0100)
committerparmentelat <thierry.parmentelat@inria.fr>
Thu, 13 Dec 2018 15:14:27 +0000 (16:14 +0100)
PLC/Auth.py
PLC/Persons.py

index f18c731..afde8c1 100644 (file)
@@ -24,6 +24,7 @@ from PLC.Peers import Peer, Peers
 from PLC.Keys import Keys
 from PLC.Boot import notify_owners
 
+
 class Auth(Parameter):
     """
     Base class for all API authentication methods, as well as a class
@@ -31,9 +32,10 @@ class Auth(Parameter):
     methods.
     """
 
-    def __init__(self, auth = None):
+    def __init__(self, auth=None):
         if auth is None:
-            auth = {'AuthMethod': Parameter(str, "Authentication method to use", optional = False)}
+            auth = {'AuthMethod': Parameter(str, "Authentication method to use",
+                                            optional=False)}
         Parameter.__init__(self, auth, "API authentication structure")
 
     def check(self, method, auth, *args):
@@ -52,6 +54,7 @@ class Auth(Parameter):
         # Re-check using the specified authentication method
         method.type_check("auth", auth, expected, (auth,) + args)
 
+
 class GPGAuth(Auth):
     """
     Proposed PlanetLab federation authentication structure.
@@ -59,34 +62,40 @@ class GPGAuth(Auth):
 
     def __init__(self):
         Auth.__init__(self, {
-            'AuthMethod': Parameter(str, "Authentication method to use, always 'gpg'", optional = False),
-            'name': Parameter(str, "Peer or user name", optional = False),
-            'signature': Parameter(str, "Message signature", optional = False)
-            })
+            'AuthMethod': Parameter(str, "Authentication method to use, always 'gpg'", optional=False),
+            'name': Parameter(str, "Peer or user name", optional=False),
+            'signature': Parameter(str, "Message signature", optional=False)
+        })
 
     def check(self, method, auth, *args):
         try:
             peers = Peers(method.api, [auth['name']])
             if peers:
                 if 'peer' not in method.roles:
-                    raise PLCAuthenticationFailure("GPGAuth: Not allowed to call method, missing 'peer' role")
+                    raise PLCAuthenticationFailure(
+                        "GPGAuth: Not allowed to call method, missing 'peer' role")
 
                 method.caller = peer = peers[0]
-                gpg_keys = [ peer['key'] ]
+                gpg_keys = [peer['key']]
             else:
-                persons = Persons(method.api, {'email': auth['name'], 'enabled': True, 'peer_id': None})
+                persons = Persons(
+                    method.api, {'email': auth['name'], 'enabled': True, 'peer_id': None})
                 if not persons:
-                    raise PLCAuthenticationFailure("GPGAuth: No such user '%s'" % auth['name'])
+                    raise PLCAuthenticationFailure(
+                        "GPGAuth: No such user '%s'" % auth['name'])
 
                 method.caller = person = persons[0]
                 if not set(person['roles']).intersection(method.roles):
-                    raise PLCAuthenticationFailure("GPGAuth: Not allowed to call method, missing role")
+                    raise PLCAuthenticationFailure(
+                        "GPGAuth: Not allowed to call method, missing role")
 
-                keys = Keys(method.api, {'key_id': person['key_ids'], 'key_type': "gpg", 'peer_id': None})
-                gpg_keys = [ key['key'] for key in keys ]
+                keys = Keys(
+                    method.api, {'key_id': person['key_ids'], 'key_type': "gpg", 'peer_id': None})
+                gpg_keys = [key['key'] for key in keys]
 
             if not gpg_keys:
-                raise PLCAuthenticationFailure("GPGAuth: No GPG key on record for peer or user '%s'"%auth['name'])
+                raise PLCAuthenticationFailure(
+                    "GPGAuth: No GPG key on record for peer or user '%s'" % auth['name'])
 
             for gpg_key in gpg_keys:
                 try:
@@ -102,6 +111,7 @@ class GPGAuth(Auth):
             # XXX Send e-mail
             raise fault
 
+
 class SessionAuth(Auth):
     """
     Secondary authentication method. After authenticating with a
@@ -111,9 +121,9 @@ class SessionAuth(Auth):
 
     def __init__(self):
         Auth.__init__(self, {
-            'AuthMethod': Parameter(str, "Authentication method to use, always 'session'", optional = False),
-            'session': Parameter(str, "Session key", optional = False)
-            })
+            'AuthMethod': Parameter(str, "Authentication method to use, always 'session'", optional=False),
+            'session': Parameter(str, "Session key", optional=False)
+        })
 
     def check(self, method, auth, *args):
         # Method.type_check() should have checked that all of the
@@ -121,14 +131,15 @@ class SessionAuth(Auth):
         assert 'session' in auth
 
         # Get session record
-        sessions = Sessions(method.api, [auth['session']], expires = None)
+        sessions = Sessions(method.api, [auth['session']], expires=None)
         if not sessions:
             raise PLCAuthenticationFailure("SessionAuth: No such session")
         session = sessions[0]
 
         try:
             if session['node_id'] is not None:
-                nodes = Nodes(method.api, {'node_id': session['node_id'], 'peer_id': None})
+                nodes = Nodes(
+                    method.api, {'node_id': session['node_id'], 'peer_id': None})
                 if not nodes:
                     raise PLCAuthenticationFailure("SessionAuth: No such node")
                 node = nodes[0]
@@ -136,21 +147,27 @@ class SessionAuth(Auth):
                 if 'node' not in method.roles:
                     # using PermissionDenied rather than AuthenticationFailure here because
                     # if that fails we don't want to delete the session..
-                    raise PLCPermissionDenied("SessionAuth: Not allowed to call method %s, missing 'node' role"%method.name)
+                    raise PLCPermissionDenied(
+                        "SessionAuth: Not allowed to call method %s, missing 'node' role" % method.name)
 
                 method.caller = node
 
             elif session['person_id'] is not None and session['expires'] > time.time():
-                persons = Persons(method.api, {'person_id': session['person_id'], 'enabled': True, 'peer_id': None})
+                persons = Persons(method.api, {
+                                  'person_id': session['person_id'], 'enabled': True, 'peer_id': None})
                 if not persons:
-                    raise PLCAuthenticationFailure("SessionAuth: No such enabled account")
+                    raise PLCAuthenticationFailure(
+                        "SessionAuth: No such enabled account")
                 person = persons[0]
 
                 if not set(person['roles']).intersection(method.roles):
-                    method_message="method %s has roles [%s]"%(method.name,','.join(method.roles))
-                    person_message="caller %s has roles [%s]"%(person['email'],','.join(person['roles']))
+                    method_message = "method %s has roles [%s]" % (
+                        method.name, ','.join(method.roles))
+                    person_message = "caller %s has roles [%s]" % (
+                        person['email'], ','.join(person['roles']))
                     # not PLCAuthenticationFailure b/c that would end the session..
-                    raise PLCPermissionDenied("SessionAuth: missing role, %s -- %s"%(method_message,person_message))
+                    raise PLCPermissionDenied(
+                        "SessionAuth: missing role, %s -- %s" % (method_message, person_message))
 
                 method.caller = person
 
@@ -161,6 +178,7 @@ class SessionAuth(Auth):
             session.delete()
             raise fault
 
+
 class BootAuth(Auth):
     """
     PlanetLab version 3.x node authentication structure. Used by the
@@ -176,10 +194,10 @@ class BootAuth(Auth):
 
     def __init__(self):
         Auth.__init__(self, {
-            'AuthMethod': Parameter(str, "Authentication method to use, always 'hmac'", optional = False),
-            'node_id': Parameter(int, "Node identifier", optional = False),
-            'value': Parameter(str, "HMAC of node key and method call", optional = False)
-            })
+            'AuthMethod': Parameter(str, "Authentication method to use, always 'hmac'", optional=False),
+            'node_id': Parameter(int, "Node identifier", optional=False),
+            'value': Parameter(str, "HMAC of node key and method call", optional=False)
+        })
 
     def canonicalize(self, args):
         values = []
@@ -206,10 +224,12 @@ class BootAuth(Auth):
         assert 'node_id' in auth
 
         if 'node' not in method.roles:
-            raise PLCAuthenticationFailure("BootAuth: Not allowed to call method, missing 'node' role")
+            raise PLCAuthenticationFailure(
+                "BootAuth: Not allowed to call method, missing 'node' role")
 
         try:
-            nodes = Nodes(method.api, {'node_id': auth['node_id'], 'peer_id': None})
+            nodes = Nodes(
+                method.api, {'node_id': auth['node_id'], 'peer_id': None})
             if not nodes:
                 raise PLCAuthenticationFailure("BootAuth: No such node")
             node = nodes[0]
@@ -231,15 +251,18 @@ class BootAuth(Auth):
             digest = hmac.new(str(key), msg.encode('utf-8'), sha).hexdigest()
 
             if digest != auth['value']:
-                raise PLCAuthenticationFailure("BootAuth: Call could not be authenticated")
+                raise PLCAuthenticationFailure(
+                    "BootAuth: Call could not be authenticated")
 
             method.caller = node
 
         except PLCAuthenticationFailure as fault:
             if nodes:
-                notify_owners(method, node, 'authfail', include_pis = True, include_techs = True, fault = fault)
+                notify_owners(method, node, 'authfail',
+                              include_pis=True, include_techs=True, fault=fault)
             raise fault
 
+
 class AnonymousAuth(Auth):
     """
     PlanetLab version 3.x anonymous authentication structure.
@@ -248,14 +271,16 @@ class AnonymousAuth(Auth):
     def __init__(self):
         Auth.__init__(self, {
             'AuthMethod': Parameter(str, "Authentication method to use, always 'anonymous'", False),
-            })
+        })
 
     def check(self, method, auth, *args):
         if 'anonymous' not in method.roles:
-            raise PLCAuthenticationFailure("AnonymousAuth: method cannot be called anonymously")
+            raise PLCAuthenticationFailure(
+                "AnonymousAuth: method cannot be called anonymously")
 
         method.caller = None
 
+
 class PasswordAuth(Auth):
     """
     PlanetLab version 3.x password authentication structure.
@@ -263,10 +288,10 @@ class PasswordAuth(Auth):
 
     def __init__(self):
         Auth.__init__(self, {
-            'AuthMethod': Parameter(str, "Authentication method to use, always 'password' or 'capability'", optional = False),
-            'Username': Parameter(str, "PlanetLab username, typically an e-mail address", optional = False),
-            'AuthString': Parameter(str, "Authentication string, typically a password", optional = False),
-            })
+            'AuthMethod': Parameter(str, "Authentication method to use, always 'password' or 'capability'", optional=False),
+            'Username': Parameter(str, "PlanetLab username, typically an e-mail address", optional=False),
+            'AuthString': Parameter(str, "Authentication string, typically a password", optional=False),
+        })
 
     def check(self, method, auth, *args):
         # Method.type_check() should have checked that all of the
@@ -274,7 +299,8 @@ class PasswordAuth(Auth):
         assert 'Username' in auth
 
         # Get record (must be enabled)
-        persons = Persons(method.api, {'email': auth['Username'].lower(), 'enabled': True, 'peer_id': None})
+        persons = Persons(method.api, {
+                          'email': auth['Username'].lower(), 'enabled': True, 'peer_id': None})
         if len(persons) != 1:
             raise PLCAuthenticationFailure("PasswordAuth: No such account")
 
@@ -287,13 +313,15 @@ class PasswordAuth(Auth):
             # only be used on particular machines (those in a list).
             sources = method.api.config.PLC_API_MAINTENANCE_SOURCES.split()
             if method.source is not None and method.source[0] not in sources:
-                raise PLCAuthenticationFailure("PasswordAuth: Not allowed to login to maintenance account")
+                raise PLCAuthenticationFailure(
+                    "PasswordAuth: Not allowed to login to maintenance account")
 
             # Not sure why this is not stored in the DB
             password = method.api.config.PLC_API_MAINTENANCE_PASSWORD
 
             if auth['AuthString'] != password:
-                raise PLCAuthenticationFailure("PasswordAuth: Maintenance account password verification failed")
+                raise PLCAuthenticationFailure(
+                    "PasswordAuth: Maintenance account password verification failed")
         else:
             # Compare encrypted plaintext against encrypted password stored in the DB
             plaintext = auth['AuthString'].encode(method.api.encoding)
@@ -302,15 +330,20 @@ class PasswordAuth(Auth):
             # Protect against blank passwords in the DB
             if password is None or password[:12] == "" or \
                crypt.crypt(plaintext, password[:12]) != password:
-                raise PLCAuthenticationFailure("PasswordAuth: Password verification failed")
+                raise PLCAuthenticationFailure(
+                    "PasswordAuth: Password verification failed")
 
         if not set(person['roles']).intersection(method.roles):
-            method_message="method %s has roles [%s]"%(method.name,','.join(method.roles))
-            person_message="caller %s has roles [%s]"%(person['email'],','.join(person['roles']))
-            raise PLCAuthenticationFailure("PasswordAuth: missing role, %s -- %s"%(method_message,person_message))
+            method_message = "method %s has roles [%s]" % (
+                method.name, ','.join(method.roles))
+            person_message = "caller %s has roles [%s]" % (
+                person['email'], ','.join(person['roles']))
+            raise PLCAuthenticationFailure(
+                "PasswordAuth: missing role, %s -- %s" % (method_message, person_message))
 
         method.caller = person
 
+
 auth_methods = {'session': SessionAuth,
                 'password': PasswordAuth,
                 'capability': PasswordAuth,
@@ -329,5 +362,6 @@ for extension in extensions:
         continue
     if not extension.endswith(".py"):
         continue
-    exec(compile(open("%s/%s" % (path, extension)).read(), "%s/%s" % (path, extension), 'exec'))
+    exec(compile(open("%s/%s" % (path, extension)).read(),
+                 "%s/%s" % (path, extension), 'exec'))
 del extensions
index dc971b3..d24597a 100644 (file)
@@ -377,11 +377,11 @@ class Persons(Table):
 
         view = "view_persons"
         for tagname in self.tag_columns:
-            view= "%s left join %s using (%s)"%(view,Person.tagvalue_view_name(tagname),
+            view= "%s left join %s using (%s)"%(view, Person.tagvalue_view_name(tagname),
                                                 Person.primary_key)
 
         sql = "SELECT %s FROM %s WHERE deleted IS False" % \
-            (", ".join(list(self.columns.keys())+list(self.tag_columns.keys())),view)
+            (", ".join(list(self.columns.keys())+list(self.tag_columns.keys())), view)
 
         if person_filter is not None:
             if isinstance(person_filter, (list, tuple, set)):
@@ -391,14 +391,14 @@ class Persons(Table):
                 person_filter = Filter(Person.fields, {'person_id': ints, 'email': strs})
                 sql += " AND (%s) %s" % person_filter.sql(api, "OR")
             elif isinstance(person_filter, dict):
-                allowed_fields=dict(list(Person.fields.items())+list(Person.tags.items()))
+                allowed_fields = dict(list(Person.fields.items())+list(Person.tags.items()))
                 person_filter = Filter(allowed_fields, person_filter)
                 sql += " AND (%s) %s" % person_filter.sql(api, "AND")
             elif isinstance (person_filter, str):
-                person_filter = Filter(Person.fields, {'email':person_filter})
+                person_filter = Filter(Person.fields, {'email': person_filter})
                 sql += " AND (%s) %s" % person_filter.sql(api, "AND")
             elif isinstance (person_filter, int):
-                person_filter = Filter(Person.fields, {'person_id':person_filter})
+                person_filter = Filter(Person.fields, {'person_id': person_filter})
                 sql += " AND (%s) %s" % person_filter.sql(api, "AND")
             else:
                 raise PLCInvalidArgument("Wrong person filter %r"%person_filter)