secrets_new: début de modularité

This commit is contained in:
Daniel STAN 2014-12-04 21:03:16 +01:00
parent 602a5bb8a6
commit 7fbd3ad275

View file

@ -4,6 +4,7 @@
# ---------- # ----------
# #
# Copyright (C) 2007 Jeremie Dimino <dimino@crans.org> # Copyright (C) 2007 Jeremie Dimino <dimino@crans.org>
# Copyright (C) 2014 Daniel STAN <daniel.stan@crans.org>
# #
# This file is free software; you can redistribute it and/or modify # This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
@ -29,6 +30,8 @@ import logging
import logging.handlers import logging.handlers
import getpass import getpass
SECRET_PATH = '/etc/crans/secrets'
# Initialisation d'un logger pour faire des stats etc # Initialisation d'un logger pour faire des stats etc
# pour l'instant, on centralise tout sur thot en mode debug # pour l'instant, on centralise tout sur thot en mode debug
logger = logging.getLogger('secrets_new') logger = logging.getLogger('secrets_new')
@ -41,24 +44,62 @@ except AttributeError:
handler.formatter = formatter handler.formatter = formatter
logger.addHandler(handler) logger.addHandler(handler)
def get(secret): class SecretNotFound(Exception):
pass
class SecretForbidden(Exception):
pass
# Définitions de fonctions renvoyant un secret, si existant, en utilisant
# **UNE** méthode d'accès
def python_loader(name):
"""Charger depuis le fichier python la variable au ``name`` correspondant"""
try:
sys.path.insert(0, SECRET_PATH)
import secrets as module
sys.path.pop(0)
try:
return getattr(module, name)
except AttributeError:
raise SecretNotFound()
except ImportError:
raise SecretForbidden()
def single_file_loader(name):
"""Charger depuis un fichier isolé appelé ``name``"""
path = os.path.join(SECRET_PATH, name)
if not os.path.isfile(path):
raise SecretNotFound()
try:
with open(path, 'r') as source:
result = source.read().strip()
return result
except IOError:
raise SecretForbidden()
def try_file_loader(name):
"""Charge un fichier, mais sans échec si pas de droit de lecture"""
try:
return single_file_loader(name)
except SecretForbidden:
raise SecretNotFound()
def get(name):
""" Récupère un secret. """ """ Récupère un secret. """
prog = os.path.basename(getattr(sys, 'argv', ['undefined'])[0]) prog = os.path.basename(getattr(sys, 'argv', ['undefined'])[0])
logger.debug('%s (in %s) asked for %s' % (getpass.getuser(), prog, secret)) logger.debug('%s (in %s) asked for %s' % (getpass.getuser(), prog, name))
try:
f = open("/etc/crans/secrets/" + secret) loaders = [python_loader, single_file_loader]
result = f.read().strip() notfound_error = None
f.close()
return result for loader in loaders:
except:
try: try:
sys.path.insert(0, '/etc/crans/secrets') return loader(name)
import secrets as module except SecretNotFound as exc:
sys.path.pop(0) notfound_error = notfound_error or exc
return getattr(module, secret) except SecretForbidden:
except: logger.critical('...and that failed (Forbidden).')
logger.critical('...and that failed.') raise
if os.getenv('DEBUG', 0):
raise logger.critical('...and that failed (not found).')
else: raise notfound_error
raise Exception("Impossible d'acceder au secret %s!" % secret)