mirror of
https://github.com/YunoHost/moulinette.git
synced 2024-09-03 20:06:31 +02:00
Merge pull request #270 from YunoHost/rework-authenticator-system
Rework and externalize the authenticator system
This commit is contained in:
commit
5d0a23e827
40 changed files with 499 additions and 6158 deletions
1
debian/control
vendored
1
debian/control
vendored
|
@ -9,7 +9,6 @@ Homepage: https://github.com/YunoHost/moulinette
|
|||
Package: moulinette
|
||||
Architecture: all
|
||||
Depends: ${misc:Depends}, ${python3:Depends},
|
||||
python3-ldap,
|
||||
python3-yaml,
|
||||
python3-bottle (>= 0.12),
|
||||
python3-gevent-websocket,
|
||||
|
|
|
@ -52,4 +52,4 @@
|
|||
"invalid_token": "令牌无效-请进行身份验证",
|
||||
"ldap_server_is_down_restart_it": "LDAP服务已下线,正在尝试重启服务……",
|
||||
"session_expired": "会话已过期。请重新进行身份验证。"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
{
|
||||
"argument_required": "Argument '{argument}' is required",
|
||||
"authentication_required": "Authentication required",
|
||||
"authentication_required_long": "Authentication is required to perform this action",
|
||||
"colon": "{}: ",
|
||||
"confirm": "Confirm {prompt}",
|
||||
"deprecated_command": "'{prog} {command}' is deprecated and will be removed in the future",
|
||||
|
@ -15,8 +14,6 @@
|
|||
"invalid_password": "Invalid password",
|
||||
"invalid_token": "Invalid token - please authenticate",
|
||||
"invalid_usage": "Invalid usage, pass --help to see help",
|
||||
"ldap_attribute_already_exists": "Attribute '{attribute}' already exists with value '{value}'",
|
||||
"ldap_server_down": "Unable to reach LDAP server",
|
||||
"logged_in": "Logged in",
|
||||
"logged_out": "Logged out",
|
||||
"not_logged_in": "You are not logged in",
|
||||
|
@ -51,6 +48,5 @@
|
|||
"download_bad_status_code": "{url} returned status code {code}",
|
||||
"warn_the_user_about_waiting_lock": "Another YunoHost command is running right now, we are waiting for it to finish before running this one",
|
||||
"warn_the_user_about_waiting_lock_again": "Still waiting...",
|
||||
"warn_the_user_that_lock_is_acquired": "The other command just completed, now starting this command",
|
||||
"ldap_server_is_down_restart_it": "The LDAP service is down, attempt to restart it..."
|
||||
"warn_the_user_that_lock_is_acquired": "The other command just completed, now starting this command"
|
||||
}
|
||||
|
|
|
@ -52,4 +52,4 @@
|
|||
"invalid_token": "Token non valido: autenticare",
|
||||
"session_expired": "La sessione è terminata. Sei pregato di autenticarti nuovamente.",
|
||||
"ldap_server_is_down_restart_it": "Il servizio LDAP è terminato, provo a riavviarlo..."
|
||||
}
|
||||
}
|
||||
|
|
|
@ -50,4 +50,4 @@
|
|||
"file_not_exist": "Dosya mevcut değil: '{path}'",
|
||||
"deprecated_command_alias": "'{prog} {old}' kullanımdan kaldırıldı ve gelecekte kaldırılacak, bunun yerine '{prog} {new}' kullanın",
|
||||
"deprecated_command": "'{prog} {command}' kullanımdan kaldırıldı ve gelecekte kaldırılacak"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from os import environ
|
||||
from moulinette.core import (
|
||||
MoulinetteError,
|
||||
MoulinetteSignals,
|
||||
Moulinette18n,
|
||||
)
|
||||
from moulinette.globals import init_moulinette_env
|
||||
|
@ -31,17 +31,34 @@ __all__ = [
|
|||
"api",
|
||||
"cli",
|
||||
"m18n",
|
||||
"msignals",
|
||||
"env",
|
||||
"init_interface",
|
||||
"MoulinetteError",
|
||||
"Moulinette"
|
||||
]
|
||||
|
||||
|
||||
msignals = MoulinetteSignals()
|
||||
msettings = dict()
|
||||
m18n = Moulinette18n()
|
||||
|
||||
class classproperty(object):
|
||||
def __init__(self, f):
|
||||
self.f = f
|
||||
def __get__(self, obj, owner):
|
||||
return self.f(owner)
|
||||
|
||||
class Moulinette():
|
||||
|
||||
_interface = None
|
||||
|
||||
def prompt(*args, **kwargs):
|
||||
return Moulinette.interface.prompt(*args, **kwargs)
|
||||
|
||||
|
||||
def display(*args, **kwargs):
|
||||
return Moulinette.interface.display(*args, **kwargs)
|
||||
|
||||
@classproperty
|
||||
def interface(cls):
|
||||
return cls._interface
|
||||
|
||||
|
||||
# Package functions
|
||||
|
||||
|
@ -116,17 +133,10 @@ def cli(args, top_parser, output_as=None, timeout=None):
|
|||
|
||||
try:
|
||||
load_only_category = args[0] if args and not args[0].startswith("-") else None
|
||||
Cli(top_parser=top_parser, load_only_category=load_only_category).run(
|
||||
args, output_as=output_as, timeout=timeout
|
||||
)
|
||||
Cli(top_parser=top_parser, load_only_category=load_only_category).run(args, output_as=output_as, timeout=timeout)
|
||||
except MoulinetteError as e:
|
||||
import logging
|
||||
|
||||
logging.getLogger("moulinette").error(e.strerror)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def env():
|
||||
"""Initialise moulinette specific configuration."""
|
||||
return init_moulinette_env()
|
||||
|
|
|
@ -11,16 +11,16 @@ from time import time
|
|||
from collections import OrderedDict
|
||||
from importlib import import_module
|
||||
|
||||
from moulinette import m18n, msignals
|
||||
from moulinette.cache import open_cachefile
|
||||
from moulinette import m18n, Moulinette
|
||||
from moulinette.globals import init_moulinette_env
|
||||
from moulinette.cache import open_cachefile
|
||||
from moulinette.core import (
|
||||
MoulinetteError,
|
||||
MoulinetteLock,
|
||||
MoulinetteAuthenticationError,
|
||||
MoulinetteValidationError,
|
||||
)
|
||||
from moulinette.interfaces import BaseActionsMapParser, GLOBAL_SECTION, TO_RETURN_PROP
|
||||
from moulinette.interfaces import BaseActionsMapParser, TO_RETURN_PROP
|
||||
from moulinette.utils.log import start_action_logging
|
||||
|
||||
logger = logging.getLogger("moulinette.actionsmap")
|
||||
|
@ -42,7 +42,6 @@ class _ExtraParameter(object):
|
|||
"""
|
||||
|
||||
def __init__(self, iface):
|
||||
# TODO: Add conn argument which contains authentification object
|
||||
self.iface = iface
|
||||
|
||||
# Required variables
|
||||
|
@ -98,7 +97,7 @@ class CommentParameter(_ExtraParameter):
|
|||
def __call__(self, message, arg_name, arg_value):
|
||||
if arg_value is None:
|
||||
return
|
||||
return msignals.display(m18n.n(message))
|
||||
return Moulinette.display(m18n.n(message))
|
||||
|
||||
@classmethod
|
||||
def validate(klass, value, arg_name):
|
||||
|
@ -135,7 +134,7 @@ class AskParameter(_ExtraParameter):
|
|||
|
||||
try:
|
||||
# Ask for the argument value
|
||||
return msignals.prompt(m18n.n(message))
|
||||
return Moulinette.prompt(m18n.n(message))
|
||||
except NotImplementedError:
|
||||
return arg_value
|
||||
|
||||
|
@ -173,7 +172,7 @@ class PasswordParameter(AskParameter):
|
|||
|
||||
try:
|
||||
# Ask for the password
|
||||
return msignals.prompt(m18n.n(message), True, True)
|
||||
return Moulinette.prompt(m18n.n(message), True, True)
|
||||
except NotImplementedError:
|
||||
return arg_value
|
||||
|
||||
|
@ -284,7 +283,7 @@ class ExtraArgumentParser(object):
|
|||
def __init__(self, iface):
|
||||
self.iface = iface
|
||||
self.extra = OrderedDict()
|
||||
self._extra_params = {GLOBAL_SECTION: {}}
|
||||
self._extra_params = {"_global": {}}
|
||||
|
||||
# Append available extra parameters for the current interface
|
||||
for klass in extraparameters_list:
|
||||
|
@ -326,7 +325,7 @@ class ExtraArgumentParser(object):
|
|||
Add extra parameters to apply on an action argument
|
||||
|
||||
Keyword arguments:
|
||||
- tid -- The tuple identifier of the action or GLOBAL_SECTION
|
||||
- tid -- The tuple identifier of the action or _global
|
||||
for global extra parameters
|
||||
- arg_name -- The argument name
|
||||
- parameters -- A dict of extra parameters with their values
|
||||
|
@ -349,7 +348,7 @@ class ExtraArgumentParser(object):
|
|||
- args -- A dict of argument name associated to their value
|
||||
|
||||
"""
|
||||
extra_args = OrderedDict(self._extra_params.get(GLOBAL_SECTION, {}))
|
||||
extra_args = OrderedDict(self._extra_params.get("_global", {}))
|
||||
extra_args.update(self._extra_params.get(tid, {}))
|
||||
|
||||
# Iterate over action arguments with extra parameters
|
||||
|
@ -472,39 +471,35 @@ class ActionsMap(object):
|
|||
self.extraparser = ExtraArgumentParser(top_parser.interface)
|
||||
self.parser = self._construct_parser(actionsmaps, top_parser)
|
||||
|
||||
def get_authenticator_for_profile(self, auth_profile):
|
||||
def get_authenticator(self, auth_method):
|
||||
|
||||
# Fetch the configuration for the authenticator module as defined in the actionmap
|
||||
try:
|
||||
auth_conf = self.parser.global_conf["authenticator"][auth_profile]
|
||||
except KeyError:
|
||||
raise ValueError("Unknown authenticator profile '%s'" % auth_profile)
|
||||
if auth_method == "default":
|
||||
auth_method = self.default_authentication
|
||||
|
||||
# Load and initialize the authenticator module
|
||||
auth_module = "%s.authenticators.%s" % (self.main_namespace, auth_method)
|
||||
logger.debug(f"Loading auth module {auth_module}")
|
||||
try:
|
||||
mod = import_module("moulinette.authenticators.%s" % auth_conf["vendor"])
|
||||
except ImportError:
|
||||
error_message = (
|
||||
"unable to load authenticator vendor module 'moulinette.authenticators.%s'"
|
||||
% auth_conf["vendor"]
|
||||
mod = import_module(auth_module)
|
||||
except ImportError as e:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
raise MoulinetteError(
|
||||
f"unable to load authenticator {auth_module} : {e}", raw_msg=True
|
||||
)
|
||||
logger.exception(error_message)
|
||||
raise MoulinetteError(error_message, raw_msg=True)
|
||||
else:
|
||||
return mod.Authenticator(**auth_conf)
|
||||
return mod.Authenticator()
|
||||
|
||||
def check_authentication_if_required(self, args, **kwargs):
|
||||
def check_authentication_if_required(self, *args, **kwargs):
|
||||
|
||||
auth_profile = self.parser.auth_required(args, **kwargs)
|
||||
auth_method = self.parser.auth_method(*args, **kwargs)
|
||||
|
||||
if not auth_profile:
|
||||
if auth_method is None:
|
||||
return
|
||||
|
||||
authenticator = self.get_authenticator_for_profile(auth_profile)
|
||||
auth = msignals.authenticate(authenticator)
|
||||
|
||||
if not auth.is_authenticated:
|
||||
raise MoulinetteAuthenticationError("authentication_required_long")
|
||||
authenticator = self.get_authenticator(auth_method)
|
||||
Moulinette.interface.authenticate(authenticator)
|
||||
|
||||
def process(self, args, timeout=None, **kwargs):
|
||||
"""
|
||||
|
@ -688,6 +683,8 @@ class ActionsMap(object):
|
|||
logger.debug("building parser...")
|
||||
start = time()
|
||||
|
||||
interface_type = top_parser.interface
|
||||
|
||||
# If loading from cache, extra were already checked when cache was
|
||||
# loaded ? Not sure about this ... old code is a bit mysterious...
|
||||
validate_extra = not self.from_cache
|
||||
|
@ -701,25 +698,31 @@ class ActionsMap(object):
|
|||
# Retrieve global parameters
|
||||
_global = actionsmap.pop("_global", {})
|
||||
|
||||
# Set the global configuration to use for the parser.
|
||||
top_parser.set_global_conf(_global["configuration"])
|
||||
if _global:
|
||||
if getattr(self, "main_namespace", None) is not None:
|
||||
raise MoulinetteError(
|
||||
"It is not possible to have several namespaces with a _global section"
|
||||
)
|
||||
else:
|
||||
self.main_namespace = namespace
|
||||
self.name = _global["name"]
|
||||
self.default_authentication = _global["authentication"][
|
||||
interface_type
|
||||
]
|
||||
|
||||
if top_parser.has_global_parser():
|
||||
top_parser.add_global_arguments(_global["arguments"])
|
||||
|
||||
if not hasattr(self, "main_namespace"):
|
||||
raise MoulinetteError("Did not found the main namespace", raw_msg=True)
|
||||
|
||||
for namespace, actionsmap in actionsmaps.items():
|
||||
# category_name is stuff like "user", "domain", "hooks"...
|
||||
# category_values is the values of this category (like actions)
|
||||
for category_name, category_values in actionsmap.items():
|
||||
|
||||
if "actions" in category_values:
|
||||
actions = category_values.pop("actions")
|
||||
else:
|
||||
actions = {}
|
||||
|
||||
if "subcategories" in category_values:
|
||||
subcategories = category_values.pop("subcategories")
|
||||
else:
|
||||
subcategories = {}
|
||||
actions = category_values.pop("actions", {})
|
||||
subcategories = category_values.pop("subcategories", {})
|
||||
|
||||
# Get category parser
|
||||
category_parser = top_parser.add_category_parser(
|
||||
|
@ -730,6 +733,7 @@ class ActionsMap(object):
|
|||
# action_options are the values
|
||||
for action_name, action_options in actions.items():
|
||||
arguments = action_options.pop("arguments", {})
|
||||
authentication = action_options.pop("authentication", {})
|
||||
tid = (namespace, category_name, action_name)
|
||||
|
||||
# Get action parser
|
||||
|
@ -749,8 +753,9 @@ class ActionsMap(object):
|
|||
validate_extra=validate_extra,
|
||||
)
|
||||
|
||||
if "configuration" in action_options:
|
||||
category_parser.set_conf(tid, action_options["configuration"])
|
||||
action_parser.authentication = self.default_authentication
|
||||
if interface_type in authentication:
|
||||
action_parser.authentication = authentication[interface_type]
|
||||
|
||||
# subcategory_name is like "cert" in "domain cert status"
|
||||
# subcategory_values is the values of this subcategory (like actions)
|
||||
|
@ -767,6 +772,7 @@ class ActionsMap(object):
|
|||
# action_options are the values
|
||||
for action_name, action_options in actions.items():
|
||||
arguments = action_options.pop("arguments", {})
|
||||
authentication = action_options.pop("authentication", {})
|
||||
tid = (namespace, category_name, subcategory_name, action_name)
|
||||
|
||||
try:
|
||||
|
@ -790,10 +796,11 @@ class ActionsMap(object):
|
|||
validate_extra=validate_extra,
|
||||
)
|
||||
|
||||
if "configuration" in action_options:
|
||||
category_parser.set_conf(
|
||||
tid, action_options["configuration"]
|
||||
)
|
||||
action_parser.authentication = self.default_authentication
|
||||
if interface_type in authentication:
|
||||
action_parser.authentication = authentication[
|
||||
interface_type
|
||||
]
|
||||
|
||||
logger.debug("building parser took %.3fs", time() - start)
|
||||
return top_parser
|
||||
|
|
46
moulinette/authentication.py
Normal file
46
moulinette/authentication.py
Normal file
|
@ -0,0 +1,46 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import logging
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
from moulinette.utils.text import random_ascii
|
||||
from moulinette.core import MoulinetteError, MoulinetteAuthenticationError
|
||||
|
||||
logger = logging.getLogger("moulinette.authenticator")
|
||||
|
||||
|
||||
# Base Class -----------------------------------------------------------
|
||||
|
||||
|
||||
class BaseAuthenticator(object):
|
||||
|
||||
"""Authenticator base representation
|
||||
|
||||
Each authenticators must implement an Authenticator class derived
|
||||
from this class which must overrides virtual properties and methods.
|
||||
It is used to authenticate and manage session. It implements base
|
||||
methods to authenticate with credentials or a session token.
|
||||
|
||||
Authenticators configurations are identified by a profile name which
|
||||
must be given on instantiation - with the corresponding vendor
|
||||
configuration of the authenticator.
|
||||
|
||||
"""
|
||||
|
||||
# Virtual methods
|
||||
# Each authenticator classes must implement these methods.
|
||||
|
||||
def authenticate_credentials(self, credentials, store_session=False):
|
||||
|
||||
try:
|
||||
# Attempt to authenticate
|
||||
auth_info = self._authenticate_credentials(credentials) or {}
|
||||
except MoulinetteError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception(f"authentication {self.name} failed because '{e}'")
|
||||
raise MoulinetteAuthenticationError("unable_authenticate")
|
||||
|
||||
return auth_info
|
|
@ -1,226 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import logging
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
from moulinette.cache import open_cachefile, get_cachedir, cachefile_exists
|
||||
from moulinette.core import MoulinetteError, MoulinetteAuthenticationError
|
||||
|
||||
logger = logging.getLogger("moulinette.authenticator")
|
||||
|
||||
|
||||
# Base Class -----------------------------------------------------------
|
||||
|
||||
|
||||
class BaseAuthenticator(object):
|
||||
|
||||
"""Authenticator base representation
|
||||
|
||||
Each authenticators must implement an Authenticator class derived
|
||||
from this class which must overrides virtual properties and methods.
|
||||
It is used to authenticate and manage session. It implements base
|
||||
methods to authenticate with a password or a session token.
|
||||
|
||||
Authenticators configurations are identified by a profile name which
|
||||
must be given on instantiation - with the corresponding vendor
|
||||
configuration of the authenticator.
|
||||
|
||||
Keyword arguments:
|
||||
- name -- The authenticator profile name
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, name, vendor, parameters, extra):
|
||||
self._name = name
|
||||
self.vendor = vendor
|
||||
self.is_authenticated = False
|
||||
self.extra = extra
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the authenticator instance"""
|
||||
return self._name
|
||||
|
||||
# Virtual properties
|
||||
# Each authenticator classes must implement these properties.
|
||||
|
||||
"""The vendor name of the authenticator"""
|
||||
vendor = None
|
||||
|
||||
# Virtual methods
|
||||
# Each authenticator classes must implement these methods.
|
||||
|
||||
def authenticate(self, password=None):
|
||||
"""Attempt to authenticate
|
||||
|
||||
Attempt to authenticate with given password. It should raise an
|
||||
AuthenticationError exception if authentication fails.
|
||||
|
||||
Keyword arguments:
|
||||
- password -- A clear text password
|
||||
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
"derived class '%s' must override this method" % self.__class__.__name__
|
||||
)
|
||||
|
||||
# Authentication methods
|
||||
|
||||
def __call__(self, password=None, token=None):
|
||||
"""Attempt to authenticate
|
||||
|
||||
Attempt to authenticate either with password or with session
|
||||
token if 'password' is None. If the authentication succeed, the
|
||||
instance is returned and the session is registered for the token
|
||||
if 'token' and 'password' are given.
|
||||
The token is composed by the session identifier and a session
|
||||
hash (the "true token") - to use for encryption - as a 2-tuple.
|
||||
|
||||
Keyword arguments:
|
||||
- password -- A clear text password
|
||||
- token -- The session token in the form of (id, hash)
|
||||
|
||||
Returns:
|
||||
The authenticated instance
|
||||
|
||||
"""
|
||||
if self.is_authenticated:
|
||||
return self
|
||||
|
||||
#
|
||||
# Authenticate using the password
|
||||
#
|
||||
if password:
|
||||
try:
|
||||
# Attempt to authenticate
|
||||
self.authenticate(password)
|
||||
except MoulinetteError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
"authentication (name: '%s', vendor: '%s') fails because '%s'",
|
||||
self.name,
|
||||
self.vendor,
|
||||
e,
|
||||
)
|
||||
raise MoulinetteAuthenticationError("unable_authenticate")
|
||||
|
||||
self.is_authenticated = True
|
||||
|
||||
# Store session for later using the provided (new) token if any
|
||||
if token:
|
||||
try:
|
||||
s_id, s_token = token
|
||||
self._store_session(s_id, s_token)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
logger.exception("unable to store session because %s", e)
|
||||
else:
|
||||
logger.debug("session has been stored")
|
||||
|
||||
#
|
||||
# Authenticate using the token provided
|
||||
#
|
||||
elif token:
|
||||
try:
|
||||
s_id, s_token = token
|
||||
# Attempt to authenticate
|
||||
self._authenticate_session(s_id, s_token)
|
||||
except MoulinetteError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception(
|
||||
"authentication (name: '%s', vendor: '%s') fails because '%s'",
|
||||
self.name,
|
||||
self.vendor,
|
||||
e,
|
||||
)
|
||||
raise MoulinetteAuthenticationError("unable_authenticate")
|
||||
else:
|
||||
self.is_authenticated = True
|
||||
|
||||
#
|
||||
# No credentials given, can't authenticate
|
||||
#
|
||||
else:
|
||||
raise MoulinetteAuthenticationError("unable_authenticate")
|
||||
|
||||
return self
|
||||
|
||||
# Private methods
|
||||
|
||||
def _open_sessionfile(self, session_id, mode="r"):
|
||||
"""Open a session file for this instance in given mode"""
|
||||
return open_cachefile(
|
||||
"%s.asc" % session_id, mode, subdir="session/%s" % self.name
|
||||
)
|
||||
|
||||
def _session_exists(self, session_id):
|
||||
"""Check a session exists"""
|
||||
return cachefile_exists("%s.asc" % session_id, subdir="session/%s" % self.name)
|
||||
|
||||
def _store_session(self, session_id, session_token):
|
||||
"""Store a session to be able to use it later to reauthenticate"""
|
||||
|
||||
# We store a hash of the session_id and the session_token (the token is assumed to be secret)
|
||||
to_hash = "{id}:{token}".format(id=session_id, token=session_token).encode()
|
||||
hash_ = hashlib.sha256(to_hash).hexdigest()
|
||||
with self._open_sessionfile(session_id, "w") as f:
|
||||
f.write(hash_)
|
||||
|
||||
def _authenticate_session(self, session_id, session_token):
|
||||
"""Checks session and token against the stored session token"""
|
||||
if not self._session_exists(session_id):
|
||||
raise MoulinetteAuthenticationError("session_expired")
|
||||
try:
|
||||
# FIXME : shouldn't we also add a check that this session file
|
||||
# is not too old ? e.g. not older than 24 hours ? idk...
|
||||
|
||||
with self._open_sessionfile(session_id, "r") as f:
|
||||
stored_hash = f.read()
|
||||
except IOError as e:
|
||||
logger.debug("unable to retrieve session", exc_info=1)
|
||||
raise MoulinetteAuthenticationError("unable_retrieve_session", exception=e)
|
||||
else:
|
||||
#
|
||||
# session_id (or just id) : This is unique id for the current session from the user. Not too important
|
||||
# if this info gets stolen somehow. It is stored in the client's side (browser) using regular cookies.
|
||||
#
|
||||
# session_token (or just token) : This is a secret info, like some sort of ephemeral password,
|
||||
# used to authenticate the session without the user having to retype the password all the time...
|
||||
# - It is generated on our side during the initial auth of the user (which happens with the actual admin password)
|
||||
# - It is stored on the client's side (browser) using (signed) cookies.
|
||||
# - We also store it on our side in the form of a hash of {id}:{token} (c.f. _store_session).
|
||||
# We could simply store the raw token, but hashing it is an additonal low-cost security layer
|
||||
# in case this info gets exposed for some reason (e.g. bad file perms for reasons...)
|
||||
#
|
||||
# When the user comes back, we fetch the session_id and session_token from its cookies. Then we
|
||||
# re-hash the {id}:{token} and compare it to the previously stored hash for this session_id ...
|
||||
# It it matches, then the user is authenticated. Otherwise, the token is invalid.
|
||||
#
|
||||
to_hash = "{id}:{token}".format(id=session_id, token=session_token).encode()
|
||||
hash_ = hashlib.sha256(to_hash).hexdigest()
|
||||
|
||||
if not hmac.compare_digest(hash_, stored_hash):
|
||||
raise MoulinetteAuthenticationError("invalid_token")
|
||||
else:
|
||||
return
|
||||
|
||||
def _clean_session(self, session_id):
|
||||
"""Clean a session cache
|
||||
|
||||
Remove cache for the session 'session_id' and for this authenticator profile
|
||||
|
||||
Keyword arguments:
|
||||
- session_id -- The session id to clean
|
||||
"""
|
||||
sessiondir = get_cachedir("session")
|
||||
|
||||
try:
|
||||
os.remove(os.path.join(sessiondir, self.name, "%s.asc" % session_id))
|
||||
except OSError:
|
||||
pass
|
|
@ -1,28 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
from moulinette.core import MoulinetteError
|
||||
from moulinette.authenticators import BaseAuthenticator
|
||||
|
||||
logger = logging.getLogger("moulinette.authenticator.dummy")
|
||||
|
||||
# Dummy authenticator implementation
|
||||
|
||||
|
||||
class Authenticator(BaseAuthenticator):
|
||||
|
||||
"""Dummy authenticator used for tests"""
|
||||
|
||||
vendor = "dummy"
|
||||
|
||||
def __init__(self, name, vendor, parameters, extra):
|
||||
logger.debug("initialize authenticator dummy")
|
||||
|
||||
super(Authenticator, self).__init__(name, vendor, parameters, extra)
|
||||
|
||||
def authenticate(self, password=None):
|
||||
|
||||
if not password == self.name:
|
||||
raise MoulinetteError("invalid_password")
|
||||
|
||||
return self
|
|
@ -1,315 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# TODO: Use Python3 to remove this fix!
|
||||
from __future__ import absolute_import
|
||||
import os
|
||||
import logging
|
||||
import ldap
|
||||
import ldap.sasl
|
||||
import time
|
||||
import ldap.modlist as modlist
|
||||
|
||||
from moulinette import m18n
|
||||
from moulinette.core import (
|
||||
MoulinetteError,
|
||||
MoulinetteAuthenticationError,
|
||||
MoulinetteLdapIsDownError,
|
||||
)
|
||||
from moulinette.authenticators import BaseAuthenticator
|
||||
|
||||
logger = logging.getLogger("moulinette.authenticator.ldap")
|
||||
|
||||
# LDAP Class Implementation --------------------------------------------
|
||||
|
||||
|
||||
class Authenticator(BaseAuthenticator):
|
||||
|
||||
"""LDAP Authenticator
|
||||
|
||||
Initialize a LDAP connexion for the given arguments. It attempts to
|
||||
authenticate a user if 'user_rdn' is given - by associating user_rdn
|
||||
and base_dn - and provides extra methods to manage opened connexion.
|
||||
|
||||
Keyword arguments:
|
||||
- uri -- The LDAP server URI
|
||||
- base_dn -- The base dn
|
||||
- user_rdn -- The user rdn to authenticate
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, name, vendor, parameters, extra):
|
||||
self.uri = parameters["uri"]
|
||||
self.basedn = parameters["base_dn"]
|
||||
self.userdn = parameters["user_rdn"]
|
||||
self.extra = extra
|
||||
self.sasldn = "cn=external,cn=auth"
|
||||
self.adminuser = "admin"
|
||||
self.admindn = "cn=%s,dc=yunohost,dc=org" % self.adminuser
|
||||
self.admindn = "cn=%s,dc=yunohost,dc=org" % self.adminuser
|
||||
logger.debug(
|
||||
"initialize authenticator '%s' with: uri='%s', "
|
||||
"base_dn='%s', user_rdn='%s'",
|
||||
name,
|
||||
self._get_uri(),
|
||||
self.basedn,
|
||||
self.userdn,
|
||||
)
|
||||
super(Authenticator, self).__init__(name, vendor, parameters, extra)
|
||||
|
||||
if self.userdn and self.sasldn in self.userdn:
|
||||
self.authenticate(None)
|
||||
else:
|
||||
self.con = None
|
||||
|
||||
def __del__(self):
|
||||
"""Disconnect and free ressources"""
|
||||
if hasattr(self, "con") and self.con:
|
||||
self.con.unbind_s()
|
||||
|
||||
# Implement virtual properties
|
||||
|
||||
vendor = "ldap"
|
||||
|
||||
# Implement virtual methods
|
||||
|
||||
def authenticate(self, password=None):
|
||||
def _reconnect():
|
||||
con = ldap.ldapobject.ReconnectLDAPObject(
|
||||
self._get_uri(), retry_max=10, retry_delay=0.5
|
||||
)
|
||||
if self.userdn:
|
||||
if self.sasldn in self.userdn:
|
||||
con.sasl_non_interactive_bind_s("EXTERNAL")
|
||||
else:
|
||||
con.simple_bind_s(self.userdn, password)
|
||||
else:
|
||||
con.simple_bind_s()
|
||||
|
||||
return con
|
||||
|
||||
try:
|
||||
con = _reconnect()
|
||||
except ldap.INVALID_CREDENTIALS:
|
||||
raise MoulinetteAuthenticationError("invalid_password")
|
||||
except ldap.SERVER_DOWN:
|
||||
# ldap is down, attempt to restart it before really failing
|
||||
logger.warning(m18n.g("ldap_server_is_down_restart_it"))
|
||||
os.system("systemctl restart slapd")
|
||||
time.sleep(10) # waits 10 secondes so we are sure that slapd has restarted
|
||||
|
||||
try:
|
||||
con = _reconnect()
|
||||
except ldap.SERVER_DOWN:
|
||||
raise MoulinetteLdapIsDownError("ldap_server_down")
|
||||
|
||||
# Check that we are indeed logged in with the right identity
|
||||
try:
|
||||
# whoami_s return dn:..., then delete these 3 characters
|
||||
who = con.whoami_s()[3:]
|
||||
except Exception as e:
|
||||
logger.warning("Error during ldap authentication process: %s", e)
|
||||
raise
|
||||
else:
|
||||
# FIXME: During SASL bind whoami from the test server return the admindn while userdn is returned normally :
|
||||
if not (who == self.admindn or who == self.userdn):
|
||||
raise MoulinetteError("Not logged in with the expected userdn ?!")
|
||||
else:
|
||||
self.con = con
|
||||
|
||||
# Additional LDAP methods
|
||||
# TODO: Review these methods
|
||||
|
||||
def search(self, base=None, filter="(objectClass=*)", attrs=["dn"]):
|
||||
"""Search in LDAP base
|
||||
|
||||
Perform an LDAP search operation with given arguments and return
|
||||
results as a list.
|
||||
|
||||
Keyword arguments:
|
||||
- base -- The dn to search into
|
||||
- filter -- A string representation of the filter to apply
|
||||
- attrs -- A list of attributes to fetch
|
||||
|
||||
Returns:
|
||||
A list of all results
|
||||
|
||||
"""
|
||||
if not base:
|
||||
base = self.basedn
|
||||
|
||||
try:
|
||||
result = self.con.search_s(base, ldap.SCOPE_SUBTREE, filter, attrs)
|
||||
except Exception as e:
|
||||
raise MoulinetteError(
|
||||
"error during LDAP search operation with: base='%s', "
|
||||
"filter='%s', attrs=%s and exception %s" % (base, filter, attrs, e),
|
||||
raw_msg=True,
|
||||
)
|
||||
|
||||
result_list = []
|
||||
if not attrs or "dn" not in attrs:
|
||||
result_list = [entry for dn, entry in result]
|
||||
else:
|
||||
for dn, entry in result:
|
||||
entry["dn"] = [dn]
|
||||
result_list.append(entry)
|
||||
|
||||
def decode(value):
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode("utf-8")
|
||||
return value
|
||||
|
||||
# result_list is for example :
|
||||
# [{'virtualdomain': [b'test.com']}, {'virtualdomain': [b'yolo.test']},
|
||||
for stuff in result_list:
|
||||
if isinstance(stuff, dict):
|
||||
for key, values in stuff.items():
|
||||
stuff[key] = [decode(v) for v in values]
|
||||
|
||||
return result_list
|
||||
|
||||
def add(self, rdn, attr_dict):
|
||||
"""
|
||||
Add LDAP entry
|
||||
|
||||
Keyword arguments:
|
||||
rdn -- DN without domain
|
||||
attr_dict -- Dictionnary of attributes/values to add
|
||||
|
||||
Returns:
|
||||
Boolean | MoulinetteError
|
||||
|
||||
"""
|
||||
dn = rdn + "," + self.basedn
|
||||
ldif = modlist.addModlist(attr_dict)
|
||||
for i, (k, v) in enumerate(ldif):
|
||||
if isinstance(v, list):
|
||||
v = [a.encode("utf-8") for a in v]
|
||||
elif isinstance(v, str):
|
||||
v = [v.encode("utf-8")]
|
||||
ldif[i] = (k, v)
|
||||
|
||||
try:
|
||||
self.con.add_s(dn, ldif)
|
||||
except Exception as e:
|
||||
raise MoulinetteError(
|
||||
"error during LDAP add operation with: rdn='%s', "
|
||||
"attr_dict=%s and exception %s" % (rdn, attr_dict, e),
|
||||
raw_msg=True,
|
||||
)
|
||||
else:
|
||||
return True
|
||||
|
||||
def remove(self, rdn):
|
||||
"""
|
||||
Remove LDAP entry
|
||||
|
||||
Keyword arguments:
|
||||
rdn -- DN without domain
|
||||
|
||||
Returns:
|
||||
Boolean | MoulinetteError
|
||||
|
||||
"""
|
||||
dn = rdn + "," + self.basedn
|
||||
try:
|
||||
self.con.delete_s(dn)
|
||||
except Exception as e:
|
||||
raise MoulinetteError(
|
||||
"error during LDAP delete operation with: rdn='%s' and exception %s"
|
||||
% (rdn, e),
|
||||
raw_msg=True,
|
||||
)
|
||||
else:
|
||||
return True
|
||||
|
||||
def update(self, rdn, attr_dict, new_rdn=False):
|
||||
"""
|
||||
Modify LDAP entry
|
||||
|
||||
Keyword arguments:
|
||||
rdn -- DN without domain
|
||||
attr_dict -- Dictionnary of attributes/values to add
|
||||
new_rdn -- New RDN for modification
|
||||
|
||||
Returns:
|
||||
Boolean | MoulinetteError
|
||||
|
||||
"""
|
||||
dn = rdn + "," + self.basedn
|
||||
actual_entry = self.search(base=dn, attrs=None)
|
||||
ldif = modlist.modifyModlist(actual_entry[0], attr_dict, ignore_oldexistent=1)
|
||||
|
||||
if ldif == []:
|
||||
logger.debug("Nothing to update in LDAP")
|
||||
return True
|
||||
|
||||
try:
|
||||
if new_rdn:
|
||||
self.con.rename_s(dn, new_rdn)
|
||||
new_base = dn.split(",", 1)[1]
|
||||
dn = new_rdn + "," + new_base
|
||||
|
||||
for i, (a, k, vs) in enumerate(ldif):
|
||||
if isinstance(vs, list):
|
||||
vs = [v.encode("utf-8") for v in vs]
|
||||
elif isinstance(vs, str):
|
||||
vs = [vs.encode("utf-8")]
|
||||
ldif[i] = (a, k, vs)
|
||||
|
||||
self.con.modify_ext_s(dn, ldif)
|
||||
except Exception as e:
|
||||
raise MoulinetteError(
|
||||
"error during LDAP update operation with: rdn='%s', "
|
||||
"attr_dict=%s, new_rdn=%s and exception: %s"
|
||||
% (rdn, attr_dict, new_rdn, e),
|
||||
raw_msg=True,
|
||||
)
|
||||
else:
|
||||
return True
|
||||
|
||||
def validate_uniqueness(self, value_dict):
|
||||
"""
|
||||
Check uniqueness of values
|
||||
|
||||
Keyword arguments:
|
||||
value_dict -- Dictionnary of attributes/values to check
|
||||
|
||||
Returns:
|
||||
Boolean | MoulinetteError
|
||||
|
||||
"""
|
||||
attr_found = self.get_conflict(value_dict)
|
||||
if attr_found:
|
||||
logger.info(
|
||||
"attribute '%s' with value '%s' is not unique",
|
||||
attr_found[0],
|
||||
attr_found[1],
|
||||
)
|
||||
raise MoulinetteError(
|
||||
"ldap_attribute_already_exists",
|
||||
attribute=attr_found[0],
|
||||
value=attr_found[1],
|
||||
)
|
||||
return True
|
||||
|
||||
def get_conflict(self, value_dict, base_dn=None):
|
||||
"""
|
||||
Check uniqueness of values
|
||||
|
||||
Keyword arguments:
|
||||
value_dict -- Dictionnary of attributes/values to check
|
||||
|
||||
Returns:
|
||||
None | tuple with Fist conflict attribute name and value
|
||||
|
||||
"""
|
||||
for attr, value in value_dict.items():
|
||||
if not self.search(base=base_dn, filter=attr + "=" + value):
|
||||
continue
|
||||
else:
|
||||
return (attr, value)
|
||||
return None
|
||||
|
||||
def _get_uri(self):
|
||||
return self.uri
|
|
@ -42,10 +42,3 @@ def open_cachefile(filename, mode="r", subdir=""):
|
|||
cache_dir = get_cachedir(subdir, make_dir=True if mode[0] == "w" else False)
|
||||
file_path = os.path.join(cache_dir, filename)
|
||||
return open(file_path, mode)
|
||||
|
||||
|
||||
def cachefile_exists(filename, subdir=""):
|
||||
|
||||
cache_dir = get_cachedir(subdir, make_dir=False)
|
||||
file_path = os.path.join(cache_dir, filename)
|
||||
return os.path.exists(file_path)
|
||||
|
|
|
@ -270,113 +270,6 @@ class Moulinette18n(object):
|
|||
return self._namespaces[self._current_namespace].key_exists(key)
|
||||
|
||||
|
||||
class MoulinetteSignals(object):
|
||||
|
||||
"""Signals connector for the moulinette
|
||||
|
||||
Allow to easily connect signals from the moulinette to handlers. A
|
||||
signal is emitted by calling the relevant method which call the
|
||||
handler.
|
||||
For the moment, a return value can be requested by a signal to its
|
||||
connected handler - make them not real-signals.
|
||||
|
||||
Keyword arguments:
|
||||
- kwargs -- A dict of {signal: handler} to connect
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
# Initialize handlers
|
||||
for s in self.signals:
|
||||
self.clear_handler(s)
|
||||
|
||||
# Iterate over signals to connect
|
||||
for s, h in kwargs.items():
|
||||
self.set_handler(s, h)
|
||||
|
||||
def set_handler(self, signal, handler):
|
||||
"""Set the handler for a signal"""
|
||||
if signal not in self.signals:
|
||||
logger.error("unknown signal '%s'", signal)
|
||||
return
|
||||
setattr(self, "_%s" % signal, handler)
|
||||
|
||||
def clear_handler(self, signal):
|
||||
"""Clear the handler of a signal"""
|
||||
if signal not in self.signals:
|
||||
logger.error("unknown signal '%s'", signal)
|
||||
return
|
||||
setattr(self, "_%s" % signal, self._notimplemented)
|
||||
|
||||
# Signals definitions
|
||||
|
||||
"""The list of available signals"""
|
||||
signals = {"authenticate", "prompt", "display"}
|
||||
|
||||
def authenticate(self, authenticator):
|
||||
"""Process the authentication
|
||||
|
||||
Attempt to authenticate to the given authenticator and return
|
||||
it.
|
||||
It is called when authentication is needed (e.g. to process an
|
||||
action).
|
||||
|
||||
Keyword arguments:
|
||||
- authenticator -- The authenticator object to use
|
||||
|
||||
Returns:
|
||||
The authenticator object
|
||||
|
||||
"""
|
||||
if authenticator.is_authenticated:
|
||||
return authenticator
|
||||
return self._authenticate(authenticator)
|
||||
|
||||
def prompt(self, message, is_password=False, confirm=False, color="blue"):
|
||||
"""Prompt for a value
|
||||
|
||||
Prompt the interface for a parameter value which is a password
|
||||
if 'is_password' and must be confirmed if 'confirm'.
|
||||
Is is called when a parameter value is needed and when the
|
||||
current interface should allow user interaction (e.g. to parse
|
||||
extra parameter 'ask' in the cli).
|
||||
|
||||
Keyword arguments:
|
||||
- message -- The message to display
|
||||
- is_password -- True if the parameter is a password
|
||||
- confirm -- True if the value must be confirmed
|
||||
- color -- Color to use for the prompt ...
|
||||
|
||||
Returns:
|
||||
The collected value
|
||||
|
||||
"""
|
||||
return self._prompt(message, is_password, confirm, color=color)
|
||||
|
||||
def display(self, message, style="info"): # i18n: info
|
||||
"""Display a message
|
||||
|
||||
Display a message with a given style to the user.
|
||||
It is called when a message should be printed to the user if the
|
||||
current interface allows user interaction (e.g. print a success
|
||||
message to the user).
|
||||
|
||||
Keyword arguments:
|
||||
- message -- The message to display
|
||||
- style -- The type of the message. Possible values are:
|
||||
info, success, warning
|
||||
|
||||
"""
|
||||
try:
|
||||
self._display(message, style)
|
||||
except NotImplementedError:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _notimplemented(*args, **kwargs):
|
||||
raise NotImplementedError("this signal is not handled")
|
||||
|
||||
|
||||
# Moulinette core classes ----------------------------------------------
|
||||
|
||||
|
||||
|
@ -408,10 +301,6 @@ class MoulinetteAuthenticationError(MoulinetteError):
|
|||
http_code = 401
|
||||
|
||||
|
||||
class MoulinetteLdapIsDownError(MoulinetteError):
|
||||
"""Used when ldap is down"""
|
||||
|
||||
|
||||
class MoulinetteLock(object):
|
||||
|
||||
"""Locker for a moulinette instance
|
||||
|
|
|
@ -6,12 +6,12 @@ import argparse
|
|||
import copy
|
||||
from collections import deque, OrderedDict
|
||||
|
||||
from moulinette import msettings, m18n
|
||||
from moulinette import Moulinette, m18n
|
||||
from moulinette.core import MoulinetteError
|
||||
|
||||
logger = logging.getLogger("moulinette.interface")
|
||||
|
||||
GLOBAL_SECTION = "_global"
|
||||
# FIXME : are these even used for anything useful ...
|
||||
TO_RETURN_PROP = "_to_return"
|
||||
CALLBACKS_PROP = "_callbacks"
|
||||
|
||||
|
@ -35,15 +35,8 @@ class BaseActionsMapParser(object):
|
|||
"""
|
||||
|
||||
def __init__(self, parent=None, **kwargs):
|
||||
if parent:
|
||||
self._o = parent
|
||||
else:
|
||||
if not parent:
|
||||
logger.debug("initializing base actions map parser for %s", self.interface)
|
||||
msettings["interface"] = self.interface
|
||||
|
||||
self._o = self
|
||||
self._global_conf = {}
|
||||
self._conf = {}
|
||||
|
||||
# Virtual properties
|
||||
# Each parser classes must implement these properties.
|
||||
|
@ -121,7 +114,7 @@ class BaseActionsMapParser(object):
|
|||
"derived class '%s' must override this method" % self.__class__.__name__
|
||||
)
|
||||
|
||||
def auth_required(self, args, **kwargs):
|
||||
def auth_method(self, *args, **kwargs):
|
||||
"""Check if authentication is required to run the requested action
|
||||
|
||||
Keyword arguments:
|
||||
|
@ -163,7 +156,7 @@ class BaseActionsMapParser(object):
|
|||
):
|
||||
raise MoulinetteError("invalid_usage")
|
||||
elif not tid:
|
||||
tid = GLOBAL_SECTION
|
||||
tid = "_global"
|
||||
|
||||
# Prepare namespace
|
||||
if namespace is None:
|
||||
|
@ -172,151 +165,6 @@ class BaseActionsMapParser(object):
|
|||
|
||||
return namespace
|
||||
|
||||
# Configuration access
|
||||
|
||||
@property
|
||||
def global_conf(self):
|
||||
"""Return the global configuration of the parser"""
|
||||
return self._o._global_conf
|
||||
|
||||
def set_global_conf(self, configuration):
|
||||
"""Set global configuration
|
||||
|
||||
Set the global configuration to use for the parser.
|
||||
|
||||
Keyword arguments:
|
||||
- configuration -- The global configuration
|
||||
|
||||
"""
|
||||
self._o._global_conf.update(self._validate_conf(configuration, True))
|
||||
|
||||
def get_conf(self, action, name):
|
||||
"""Get the value of an action configuration
|
||||
|
||||
Return the formated value of configuration 'name' for the action
|
||||
identified by 'action'. If the configuration for the action is
|
||||
not set, the default one is returned.
|
||||
|
||||
Keyword arguments:
|
||||
- action -- An action identifier
|
||||
- name -- The configuration name
|
||||
|
||||
"""
|
||||
try:
|
||||
return self._o._conf[action][name]
|
||||
except KeyError:
|
||||
return self.global_conf[name]
|
||||
|
||||
def set_conf(self, action, configuration):
|
||||
"""Set configuration for an action
|
||||
|
||||
Set the configuration to use for a given action identified by
|
||||
'action' which is specific to the parser.
|
||||
|
||||
Keyword arguments:
|
||||
- action -- The action identifier
|
||||
- configuration -- The configuration for the action
|
||||
|
||||
"""
|
||||
self._o._conf[action] = self._validate_conf(configuration)
|
||||
|
||||
def _validate_conf(self, configuration, is_global=False):
|
||||
"""Validate configuration for the parser
|
||||
|
||||
Return the validated configuration for the interface's actions
|
||||
map parser.
|
||||
|
||||
Keyword arguments:
|
||||
- configuration -- The configuration to pre-format
|
||||
|
||||
"""
|
||||
# TODO: Create a class with a validator method for each configuration
|
||||
conf = {}
|
||||
|
||||
# -- 'authenficate'
|
||||
try:
|
||||
ifaces = configuration["authenticate"]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
if ifaces == "all":
|
||||
conf["authenticate"] = ifaces
|
||||
elif ifaces is False:
|
||||
conf["authenticate"] = False
|
||||
elif isinstance(ifaces, list):
|
||||
if "all" in ifaces:
|
||||
conf["authenticate"] = "all"
|
||||
else:
|
||||
# Store only if authentication is needed
|
||||
conf["authenticate"] = True if self.interface in ifaces else False
|
||||
else:
|
||||
error_message = (
|
||||
"expecting 'all', 'False' or a list for "
|
||||
"configuration 'authenticate', got %r" % ifaces,
|
||||
)
|
||||
logger.error(error_message)
|
||||
raise MoulinetteError(error_message, raw_msg=True)
|
||||
|
||||
# -- 'authenticator'
|
||||
auth = configuration.get("authenticator", "default")
|
||||
if not is_global and isinstance(auth, str):
|
||||
# Store needed authenticator profile
|
||||
if auth not in self.global_conf["authenticator"]:
|
||||
error_message = (
|
||||
"requesting profile '%s' which is undefined in "
|
||||
"global configuration of 'authenticator'" % auth,
|
||||
)
|
||||
logger.error(error_message)
|
||||
raise MoulinetteError(error_message, raw_msg=True)
|
||||
else:
|
||||
conf["authenticator"] = auth
|
||||
elif is_global and isinstance(auth, dict):
|
||||
if len(auth) == 0:
|
||||
logger.warning(
|
||||
"no profile defined in global configuration " "for 'authenticator'"
|
||||
)
|
||||
else:
|
||||
auths = {}
|
||||
for auth_name, auth_conf in auth.items():
|
||||
auths[auth_name] = {
|
||||
"name": auth_name,
|
||||
"vendor": auth_conf.get("vendor"),
|
||||
"parameters": auth_conf.get("parameters", {}),
|
||||
"extra": {"help": auth_conf.get("help", None)},
|
||||
}
|
||||
conf["authenticator"] = auths
|
||||
else:
|
||||
error_message = (
|
||||
"expecting a dict of profile(s) or a profile name "
|
||||
"for configuration 'authenticator', got %r",
|
||||
auth,
|
||||
)
|
||||
logger.error(error_message)
|
||||
raise MoulinetteError(error_message, raw_msg=True)
|
||||
|
||||
return conf
|
||||
|
||||
|
||||
class BaseInterface(object):
|
||||
|
||||
"""Moulinette's base Interface
|
||||
|
||||
Each interfaces must implement an Interface class derived from this
|
||||
class which must overrides virtual properties and methods.
|
||||
It is used to provide a user interface for an actions map.
|
||||
|
||||
Keyword arguments:
|
||||
- actionsmap -- The ActionsMap instance to connect to
|
||||
|
||||
"""
|
||||
|
||||
# TODO: Add common interface methods and try to standardize default ones
|
||||
|
||||
def __init__(self, actionsmap):
|
||||
raise NotImplementedError(
|
||||
"derived class '%s' must override this method" % self.__class__.__name__
|
||||
)
|
||||
|
||||
|
||||
# Argument parser ------------------------------------------------------
|
||||
|
||||
|
|
|
@ -6,6 +6,7 @@ import logging
|
|||
import argparse
|
||||
from json import dumps as json_encode
|
||||
from tempfile import mkdtemp
|
||||
from shutil import rmtree
|
||||
|
||||
from gevent import sleep
|
||||
from gevent.queue import Queue
|
||||
|
@ -14,14 +15,11 @@ from geventwebsocket import WebSocketError
|
|||
from bottle import request, response, Bottle, HTTPResponse, FileUpload
|
||||
from bottle import abort
|
||||
|
||||
from shutil import rmtree
|
||||
|
||||
from moulinette import msignals, m18n, env
|
||||
from moulinette import m18n, Moulinette
|
||||
from moulinette.actionsmap import ActionsMap
|
||||
from moulinette.core import MoulinetteError, MoulinetteValidationError
|
||||
from moulinette.interfaces import (
|
||||
BaseActionsMapParser,
|
||||
BaseInterface,
|
||||
ExtendedArgumentParser,
|
||||
)
|
||||
from moulinette.utils import log
|
||||
|
@ -67,7 +65,7 @@ def filter_csrf(callback):
|
|||
|
||||
class LogQueues(dict):
|
||||
|
||||
"""Map of session id to queue."""
|
||||
"""Map of session ids to queue."""
|
||||
|
||||
pass
|
||||
|
||||
|
@ -84,9 +82,10 @@ class APIQueueHandler(logging.Handler):
|
|||
self.queues = LogQueues()
|
||||
|
||||
def emit(self, record):
|
||||
s_id = Session.get_infos()["id"]
|
||||
sid = request.get_cookie("session.id")
|
||||
try:
|
||||
queue = self.queues[sid]
|
||||
queue = self.queues[s_id]
|
||||
except KeyError:
|
||||
# Session is not initialized, abandon.
|
||||
return
|
||||
|
@ -231,6 +230,34 @@ class _HTTPArgumentParser(object):
|
|||
raise MoulinetteValidationError(message, raw_msg=True)
|
||||
|
||||
|
||||
class Session():
|
||||
|
||||
secret = random_ascii()
|
||||
actionsmap_name = None # This is later set to the actionsmap name
|
||||
|
||||
def set_infos(infos):
|
||||
|
||||
assert isinstance(infos, dict)
|
||||
|
||||
response.set_cookie(f"session.{Session.actionsmap_name}", infos, secure=True, secret=Session.secret)
|
||||
|
||||
def get_infos():
|
||||
|
||||
try:
|
||||
infos = request.get_cookie(f"session.{Session.actionsmap_name}", secret=Session.secret, default={})
|
||||
except Exception:
|
||||
infos = {}
|
||||
|
||||
if "id" not in infos:
|
||||
infos["id"] = random_ascii()
|
||||
|
||||
return infos
|
||||
|
||||
def delete_infos():
|
||||
|
||||
response.set_cookie(f"session.{Session.actionsmap_name}", "", max_age=-1)
|
||||
|
||||
|
||||
class _ActionsMapPlugin(object):
|
||||
|
||||
"""Actions map Bottle Plugin
|
||||
|
@ -247,14 +274,10 @@ class _ActionsMapPlugin(object):
|
|||
api = 2
|
||||
|
||||
def __init__(self, actionsmap, log_queues={}):
|
||||
# Connect signals to handlers
|
||||
msignals.set_handler("authenticate", self._do_authenticate)
|
||||
msignals.set_handler("display", self._do_display)
|
||||
|
||||
self.actionsmap = actionsmap
|
||||
self.log_queues = log_queues
|
||||
# TODO: Save and load secrets?
|
||||
self.secrets = {}
|
||||
Session.actionsmap_name = actionsmap.name
|
||||
|
||||
def setup(self, app):
|
||||
"""Setup plugin on the application
|
||||
|
@ -265,28 +288,6 @@ class _ActionsMapPlugin(object):
|
|||
- app -- The application instance
|
||||
|
||||
"""
|
||||
# Login wrapper
|
||||
def _login(callback):
|
||||
def wrapper():
|
||||
kwargs = {}
|
||||
try:
|
||||
kwargs["password"] = request.POST.password
|
||||
except KeyError:
|
||||
raise HTTPResponse("Missing password parameter", 400)
|
||||
|
||||
kwargs["profile"] = request.POST.get("profile", "default")
|
||||
return callback(**kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
# Logout wrapper
|
||||
def _logout(callback):
|
||||
def wrapper():
|
||||
kwargs = {}
|
||||
kwargs["profile"] = request.POST.get("profile", "default")
|
||||
return callback(**kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
# Append authentication routes
|
||||
app.route(
|
||||
|
@ -295,7 +296,6 @@ class _ActionsMapPlugin(object):
|
|||
method="POST",
|
||||
callback=self.login,
|
||||
skip=["actionsmap"],
|
||||
apply=_login,
|
||||
)
|
||||
app.route(
|
||||
"/logout",
|
||||
|
@ -303,7 +303,6 @@ class _ActionsMapPlugin(object):
|
|||
method="GET",
|
||||
callback=self.logout,
|
||||
skip=["actionsmap"],
|
||||
apply=_logout,
|
||||
)
|
||||
|
||||
# Append messages route
|
||||
|
@ -368,101 +367,69 @@ class _ActionsMapPlugin(object):
|
|||
|
||||
# Routes callbacks
|
||||
|
||||
def login(self, password, profile):
|
||||
"""Log in to an authenticator profile
|
||||
def login(self):
|
||||
"""Log in to an authenticator
|
||||
|
||||
Attempt to authenticate to a given authenticator profile and
|
||||
Attempt to authenticate to the default authenticator and
|
||||
register it with the current session - a new one will be created
|
||||
if needed.
|
||||
|
||||
Keyword arguments:
|
||||
- password -- A clear text password
|
||||
- profile -- The authenticator profile name to log in
|
||||
|
||||
"""
|
||||
# Retrieve session values
|
||||
try:
|
||||
s_id = request.get_cookie("session.id") or random_ascii()
|
||||
except:
|
||||
# Super rare case where there are super weird cookie / cache issue
|
||||
# Previous line throws a CookieError that creates a 500 error ...
|
||||
# So let's catch it and just use a fresh ID then...
|
||||
s_id = random_ascii()
|
||||
|
||||
credentials = request.POST.credentials
|
||||
# Apparently even if the key doesn't exists, request.POST.foobar just returns empty string...
|
||||
if not credentials:
|
||||
raise HTTPResponse("Missing credentials parameter", 400)
|
||||
|
||||
profile = request.POST.profile
|
||||
if not profile:
|
||||
profile = self.actionsmap.default_authentication
|
||||
|
||||
authenticator = self.actionsmap.get_authenticator(profile)
|
||||
|
||||
try:
|
||||
s_secret = self.secrets[s_id]
|
||||
except KeyError:
|
||||
s_tokens = {}
|
||||
else:
|
||||
try:
|
||||
s_tokens = request.get_cookie("session.tokens", secret=s_secret) or {}
|
||||
except:
|
||||
# Same as for session.id a few lines before
|
||||
s_tokens = {}
|
||||
s_new_token = random_ascii()
|
||||
|
||||
try:
|
||||
# Attempt to authenticate
|
||||
authenticator = self.actionsmap.get_authenticator_for_profile(profile)
|
||||
authenticator(password, token=(s_id, s_new_token))
|
||||
auth_info = authenticator.authenticate_credentials(credentials, store_session=True)
|
||||
session_infos = Session.get_infos()
|
||||
session_infos[profile] = auth_info
|
||||
except MoulinetteError as e:
|
||||
if len(s_tokens) > 0:
|
||||
try:
|
||||
self.logout(profile)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
self.logout()
|
||||
except Exception:
|
||||
pass
|
||||
# FIXME : replace with MoulinetteAuthenticationError !?
|
||||
raise HTTPResponse(e.strerror, 401)
|
||||
else:
|
||||
# Update dicts with new values
|
||||
s_tokens[profile] = s_new_token
|
||||
self.secrets[s_id] = s_secret = random_ascii()
|
||||
|
||||
response.set_cookie("session.id", s_id, secure=True)
|
||||
response.set_cookie(
|
||||
"session.tokens", s_tokens, secure=True, secret=s_secret
|
||||
)
|
||||
Session.set_infos(session_infos)
|
||||
return m18n.g("logged_in")
|
||||
|
||||
def logout(self, profile):
|
||||
"""Log out from an authenticator profile
|
||||
# This is called before each time a route is going to be processed
|
||||
def authenticate(self, authenticator):
|
||||
|
||||
Attempt to unregister a given profile - or all by default - from
|
||||
the current session.
|
||||
|
||||
Keyword arguments:
|
||||
- profile -- The authenticator profile name to log out
|
||||
|
||||
"""
|
||||
s_id = request.get_cookie("session.id")
|
||||
# We check that there's a (signed) session.hash available
|
||||
# for additional security ?
|
||||
# (An attacker could not craft such signed hashed ? (FIXME : need to make sure of this))
|
||||
try:
|
||||
s_secret = self.secrets[s_id]
|
||||
session_infos = Session.get_infos()[authenticator.name]
|
||||
except KeyError:
|
||||
msg = m18n.g("authentication_required")
|
||||
raise HTTPResponse(msg, 401)
|
||||
|
||||
return session_infos
|
||||
|
||||
def logout(self):
|
||||
try:
|
||||
Session.get_infos()
|
||||
except KeyError:
|
||||
s_secret = {}
|
||||
if profile not in request.get_cookie(
|
||||
"session.tokens", secret=s_secret, default={}
|
||||
):
|
||||
raise HTTPResponse(m18n.g("not_logged_in"), 401)
|
||||
else:
|
||||
del self.secrets[s_id]
|
||||
authenticator = self.actionsmap.get_authenticator_for_profile(profile)
|
||||
authenticator._clean_session(s_id)
|
||||
# TODO: Clean the session for profile only
|
||||
# Delete cookie and clean the session
|
||||
response.set_cookie("session.tokens", "", max_age=-1)
|
||||
return m18n.g("logged_out")
|
||||
Session.delete_infos()
|
||||
return m18n.g("logged_out")
|
||||
|
||||
def messages(self):
|
||||
"""Listen to the messages WebSocket stream
|
||||
|
||||
Retrieve the WebSocket stream and send to it each messages displayed by
|
||||
the core.MoulinetteSignals.display signal. They are JSON encoded as a
|
||||
dict { style: message }.
|
||||
|
||||
the display method. They are JSON encoded as a dict { style: message }.
|
||||
"""
|
||||
s_id = request.get_cookie("session.id")
|
||||
s_id = Session.get_infos()["id"]
|
||||
try:
|
||||
queue = self.log_queues[s_id]
|
||||
except KeyError:
|
||||
|
@ -505,6 +472,7 @@ class _ActionsMapPlugin(object):
|
|||
- arguments -- A dict of arguments for the route
|
||||
|
||||
"""
|
||||
|
||||
try:
|
||||
ret = self.actionsmap.process(arguments, timeout=30, route=_route)
|
||||
except MoulinetteError as e:
|
||||
|
@ -530,39 +498,16 @@ class _ActionsMapPlugin(object):
|
|||
|
||||
# Close opened WebSocket by putting StopIteration in the queue
|
||||
try:
|
||||
queue = self.log_queues[request.get_cookie("session.id")]
|
||||
s_id = Session.get_infos()["id"]
|
||||
queue = self.log_queues[s_id]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
queue.put(StopIteration)
|
||||
|
||||
# Signals handlers
|
||||
def display(self, message, style="info"):
|
||||
|
||||
def _do_authenticate(self, authenticator):
|
||||
"""Process the authentication
|
||||
|
||||
Handle the core.MoulinetteSignals.authenticate signal.
|
||||
|
||||
"""
|
||||
s_id = request.get_cookie("session.id")
|
||||
try:
|
||||
s_secret = self.secrets[s_id]
|
||||
s_token = request.get_cookie("session.tokens", secret=s_secret, default={})[
|
||||
authenticator.name
|
||||
]
|
||||
except KeyError:
|
||||
msg = m18n.g("authentication_required")
|
||||
raise HTTPResponse(msg, 401)
|
||||
else:
|
||||
return authenticator(token=(s_id, s_token))
|
||||
|
||||
def _do_display(self, message, style):
|
||||
"""Display a message
|
||||
|
||||
Handle the core.MoulinetteSignals.display signal.
|
||||
|
||||
"""
|
||||
s_id = request.get_cookie("session.id")
|
||||
s_id = Sesson.get_infos()["id"]
|
||||
try:
|
||||
queue = self.log_queues[s_id]
|
||||
except KeyError:
|
||||
|
@ -575,6 +520,8 @@ class _ActionsMapPlugin(object):
|
|||
# populate the new message in the queue
|
||||
sleep(0)
|
||||
|
||||
def prompt(self, *args, **kwargs):
|
||||
raise NotImplementedError("Prompt is not implemented for this interface")
|
||||
|
||||
# HTTP Responses -------------------------------------------------------
|
||||
|
||||
|
@ -696,31 +643,17 @@ class ActionsMapParser(BaseActionsMapParser):
|
|||
# Return the created parser
|
||||
return parser
|
||||
|
||||
def auth_required(self, args, **kwargs):
|
||||
def auth_method(self, _, route):
|
||||
|
||||
try:
|
||||
# Retrieve the tid for the route
|
||||
tid, _ = self._parsers[kwargs.get("route")]
|
||||
_, parser = self._parsers[route]
|
||||
except KeyError as e:
|
||||
error_message = "no argument parser found for route '%s': %s" % (
|
||||
kwargs.get("route"),
|
||||
e,
|
||||
)
|
||||
error_message = "no argument parser found for route '%s': %s" % (route, e)
|
||||
logger.error(error_message)
|
||||
raise MoulinetteValidationError(error_message, raw_msg=True)
|
||||
|
||||
if self.get_conf(tid, "authenticate"):
|
||||
authenticator = self.get_conf(tid, "authenticator")
|
||||
|
||||
# If several authenticator, use the default one
|
||||
if isinstance(authenticator, dict):
|
||||
if "default" in authenticator:
|
||||
authenticator = "default"
|
||||
else:
|
||||
# TODO which one should we use?
|
||||
pass
|
||||
return authenticator
|
||||
else:
|
||||
return False
|
||||
return parser.authentication
|
||||
|
||||
def parse_args(self, args, route, **kwargs):
|
||||
"""Parse arguments
|
||||
|
@ -766,7 +699,7 @@ class ActionsMapParser(BaseActionsMapParser):
|
|||
return key
|
||||
|
||||
|
||||
class Interface(BaseInterface):
|
||||
class Interface:
|
||||
|
||||
"""Application Programming Interface for the moulinette
|
||||
|
||||
|
@ -781,15 +714,16 @@ class Interface(BaseInterface):
|
|||
|
||||
"""
|
||||
|
||||
def __init__(self, routes={}, log_queues=None):
|
||||
type = "api"
|
||||
|
||||
def __init__(self, routes={}):
|
||||
|
||||
actionsmap = ActionsMap(ActionsMapParser())
|
||||
|
||||
# Attempt to retrieve log queues from an APIQueueHandler
|
||||
if log_queues is None:
|
||||
handler = log.getHandlersByClass(APIQueueHandler, limit=1)
|
||||
if handler:
|
||||
log_queues = handler.queues
|
||||
handler = log.getHandlersByClass(APIQueueHandler, limit=1)
|
||||
if handler:
|
||||
log_queues = handler.queues
|
||||
|
||||
# TODO: Return OK to 'OPTIONS' xhr requests (l173)
|
||||
app = Bottle(autojson=True)
|
||||
|
@ -818,11 +752,12 @@ class Interface(BaseInterface):
|
|||
app.install(filter_csrf)
|
||||
app.install(apiheader)
|
||||
app.install(api18n)
|
||||
app.install(_ActionsMapPlugin(actionsmap, log_queues))
|
||||
actionsmapplugin = _ActionsMapPlugin(actionsmap, log_queues)
|
||||
app.install(actionsmapplugin)
|
||||
|
||||
# Append default routes
|
||||
# app.route(['/api', '/api/<category:re:[a-z]+>'], method='GET',
|
||||
# callback=self.doc, skip=['actionsmap'])
|
||||
self.authenticate = actionsmapplugin.authenticate
|
||||
self.display = actionsmapplugin.display
|
||||
self.prompt = actionsmapplugin.prompt
|
||||
|
||||
# Append additional routes
|
||||
# TODO: Add optional authentication to those routes?
|
||||
|
@ -831,6 +766,8 @@ class Interface(BaseInterface):
|
|||
|
||||
self._app = app
|
||||
|
||||
Moulinette._interface = self
|
||||
|
||||
def run(self, host="localhost", port=80):
|
||||
"""Run the moulinette
|
||||
|
||||
|
@ -842,6 +779,7 @@ class Interface(BaseInterface):
|
|||
- port -- Server port to bind to
|
||||
|
||||
"""
|
||||
|
||||
logger.debug(
|
||||
"starting the server instance in %s:%d",
|
||||
host,
|
||||
|
@ -864,25 +802,3 @@ class Interface(BaseInterface):
|
|||
if e.args[0] == errno.EADDRINUSE:
|
||||
raise MoulinetteError("server_already_running")
|
||||
raise MoulinetteError(error_message)
|
||||
|
||||
# Routes handlers
|
||||
|
||||
def doc(self, category=None):
|
||||
"""
|
||||
Get API documentation for a category (all by default)
|
||||
|
||||
Keyword argument:
|
||||
category -- Name of the category
|
||||
|
||||
"""
|
||||
DATA_DIR = env()["DATA_DIR"]
|
||||
|
||||
if category is None:
|
||||
with open("%s/../doc/resources.json" % DATA_DIR) as f:
|
||||
return f.read()
|
||||
|
||||
try:
|
||||
with open("%s/../doc/%s.json" % (DATA_DIR, category)) as f:
|
||||
return f.read()
|
||||
except IOError:
|
||||
return None
|
||||
|
|
|
@ -11,12 +11,11 @@ from datetime import date, datetime
|
|||
|
||||
import argcomplete
|
||||
|
||||
from moulinette import msignals, m18n
|
||||
from moulinette import m18n, Moulinette
|
||||
from moulinette.actionsmap import ActionsMap
|
||||
from moulinette.core import MoulinetteError, MoulinetteValidationError
|
||||
from moulinette.interfaces import (
|
||||
BaseActionsMapParser,
|
||||
BaseInterface,
|
||||
ExtendedArgumentParser,
|
||||
)
|
||||
from moulinette.utils import log
|
||||
|
@ -356,7 +355,7 @@ class ActionsMapParser(BaseActionsMapParser):
|
|||
type_="subcategory",
|
||||
description=subcategory_help,
|
||||
help=subcategory_help,
|
||||
**kwargs
|
||||
**kwargs,
|
||||
)
|
||||
return self.__class__(self, parser, {"title": "actions", "required": True})
|
||||
|
||||
|
@ -367,7 +366,7 @@ class ActionsMapParser(BaseActionsMapParser):
|
|||
action_help=None,
|
||||
deprecated=False,
|
||||
deprecated_alias=[],
|
||||
**kwargs
|
||||
**kwargs,
|
||||
):
|
||||
"""Add a parser for an action
|
||||
|
||||
|
@ -398,7 +397,7 @@ class ActionsMapParser(BaseActionsMapParser):
|
|||
|
||||
self.global_parser.add_argument(*names, **argument_options)
|
||||
|
||||
def auth_required(self, args, **kwargs):
|
||||
def auth_method(self, args):
|
||||
# FIXME? idk .. this try/except is duplicated from parse_args below
|
||||
# Just to be able to obtain the tid
|
||||
try:
|
||||
|
@ -414,19 +413,23 @@ class ActionsMapParser(BaseActionsMapParser):
|
|||
raise MoulinetteValidationError(error_message, raw_msg=True)
|
||||
|
||||
tid = getattr(ret, "_tid", None)
|
||||
if self.get_conf(tid, "authenticate"):
|
||||
authenticator = self.get_conf(tid, "authenticator")
|
||||
|
||||
# If several authenticator, use the default one
|
||||
if isinstance(authenticator, dict):
|
||||
if "default" in authenticator:
|
||||
authenticator = "default"
|
||||
else:
|
||||
# TODO which one should we use?
|
||||
pass
|
||||
return authenticator
|
||||
else:
|
||||
return False
|
||||
# Ugh that's for yunohost --version ...
|
||||
if tid is None:
|
||||
return None
|
||||
|
||||
# We go down in the subparser tree until we find the leaf
|
||||
# corresponding to the tid with a defined authentication
|
||||
# (yeah it's a mess because the datastructure is a mess..)
|
||||
_p = self._subparsers
|
||||
for word in tid[1:]:
|
||||
_p = _p.choices[word]
|
||||
if hasattr(_p, "authentication"):
|
||||
return _p.authentication
|
||||
else:
|
||||
_p = _p._actions[1]
|
||||
|
||||
raise MoulinetteError(f"Authentication undefined for {tid} ?", raw_msg=True)
|
||||
|
||||
def parse_args(self, args, **kwargs):
|
||||
try:
|
||||
|
@ -446,7 +449,7 @@ class ActionsMapParser(BaseActionsMapParser):
|
|||
return ret
|
||||
|
||||
|
||||
class Interface(BaseInterface):
|
||||
class Interface:
|
||||
|
||||
"""Command-line Interface for the moulinette
|
||||
|
||||
|
@ -458,22 +461,20 @@ class Interface(BaseInterface):
|
|||
|
||||
"""
|
||||
|
||||
type = "cli"
|
||||
|
||||
def __init__(self, top_parser=None, load_only_category=None):
|
||||
|
||||
# Set user locale
|
||||
m18n.set_locale(get_locale())
|
||||
|
||||
# Connect signals to handlers
|
||||
msignals.set_handler("display", self._do_display)
|
||||
if os.isatty(1):
|
||||
msignals.set_handler("authenticate", self._do_authenticate)
|
||||
msignals.set_handler("prompt", self._do_prompt)
|
||||
|
||||
self.actionsmap = ActionsMap(
|
||||
ActionsMapParser(top_parser=top_parser),
|
||||
load_only_category=load_only_category,
|
||||
)
|
||||
|
||||
Moulinette._interface = self
|
||||
|
||||
def run(self, args, output_as=None, timeout=None):
|
||||
"""Run the moulinette
|
||||
|
||||
|
@ -489,15 +490,13 @@ class Interface(BaseInterface):
|
|||
- timeout -- Number of seconds before this command will timeout because it can't acquire the lock (meaning that another command is currently running), by default there is no timeout and the command will wait until it can get the lock
|
||||
|
||||
"""
|
||||
|
||||
if output_as and output_as not in ["json", "plain", "none"]:
|
||||
raise MoulinetteValidationError("invalid_usage")
|
||||
|
||||
# auto-complete
|
||||
argcomplete.autocomplete(self.actionsmap.parser._parser)
|
||||
|
||||
# Set handler for authentication
|
||||
msignals.set_handler("authenticate", self._do_authenticate)
|
||||
|
||||
try:
|
||||
ret = self.actionsmap.process(args, timeout=timeout)
|
||||
except (KeyboardInterrupt, EOFError):
|
||||
|
@ -520,32 +519,26 @@ class Interface(BaseInterface):
|
|||
else:
|
||||
print(ret)
|
||||
|
||||
# Signals handlers
|
||||
|
||||
def _do_authenticate(self, authenticator):
|
||||
"""Process the authentication
|
||||
|
||||
Handle the core.MoulinetteSignals.authenticate signal.
|
||||
|
||||
"""
|
||||
def authenticate(self, authenticator):
|
||||
# Hmpf we have no-use case in yunohost anymore where we need to auth
|
||||
# because everything is run as root ...
|
||||
# I guess we could imagine some yunohost-independant use-case where
|
||||
# moulinette is used to create a CLI for non-root user that needs to
|
||||
# auth somehow but hmpf -.-
|
||||
help = authenticator.extra.get("help")
|
||||
msg = m18n.n(help) if help else m18n.g("password")
|
||||
return authenticator(password=self._do_prompt(msg, True, False, color="yellow"))
|
||||
msg = m18n.g("password")
|
||||
credentials = self.prompt(msg, True, False, color="yellow")
|
||||
return authenticator.authenticate_credentials(credentials=credentials)
|
||||
|
||||
def _do_prompt(self, message, is_password, confirm, color="blue"):
|
||||
def prompt(self, message, is_password=False, confirm=False, color="blue"):
|
||||
"""Prompt for a value
|
||||
|
||||
Handle the core.MoulinetteSignals.prompt signal.
|
||||
|
||||
Keyword arguments:
|
||||
- color -- The color to use for prompting message
|
||||
|
||||
"""
|
||||
|
||||
if not os.isatty(1):
|
||||
raise MoulinetteError("Not a tty, can't do interactive prompts", raw_msg=True)
|
||||
|
||||
if is_password:
|
||||
prompt = lambda m: getpass.getpass(colorize(m18n.g("colon", m), color))
|
||||
else:
|
||||
|
@ -559,11 +552,9 @@ class Interface(BaseInterface):
|
|||
|
||||
return value
|
||||
|
||||
def _do_display(self, message, style):
|
||||
def display(self, message, style="info"):
|
||||
"""Display a message
|
||||
|
||||
Handle the core.MoulinetteSignals.display signal.
|
||||
|
||||
"""
|
||||
if style == "success":
|
||||
print("{} {}".format(colorize(m18n.g("success"), "green"), message))
|
||||
|
|
|
@ -107,41 +107,6 @@ def read_toml(file_path):
|
|||
return loaded_toml
|
||||
|
||||
|
||||
def read_ldif(file_path, filtred_entries=[]):
|
||||
"""
|
||||
Safely read a LDIF file and create struct in the same style than
|
||||
what return the auth objet with the seach method
|
||||
The main difference with the auth object is that this function return a 2-tuples
|
||||
with the "dn" and the LDAP entry.
|
||||
|
||||
Keyword argument:
|
||||
file_path -- Path to the ldif file
|
||||
filtred_entries -- The entries to don't include in the result
|
||||
"""
|
||||
from ldif import LDIFRecordList
|
||||
|
||||
class LDIFPar(LDIFRecordList):
|
||||
def handle(self, dn, entry):
|
||||
for e in filtred_entries:
|
||||
if e in entry:
|
||||
entry.pop(e)
|
||||
self.all_records.append((dn, entry))
|
||||
|
||||
# Open file and read content
|
||||
try:
|
||||
with open(file_path, "r") as f:
|
||||
parser = LDIFPar(f)
|
||||
parser.parse()
|
||||
except IOError as e:
|
||||
raise MoulinetteError("cannot_open_file", file=file_path, error=str(e))
|
||||
except Exception as e:
|
||||
raise MoulinetteError(
|
||||
"unknown_error_reading_file", file=file_path, error=str(e)
|
||||
)
|
||||
|
||||
return parser.all_records
|
||||
|
||||
|
||||
def write_to_file(file_path, data, file_mode="w"):
|
||||
"""
|
||||
Write a single string or a list of string to a text file.
|
||||
|
|
3
setup.py
3
setup.py
|
@ -3,7 +3,7 @@
|
|||
import os
|
||||
import sys
|
||||
from setuptools import setup, find_packages
|
||||
from moulinette.globals import init_moulinette_env
|
||||
from moulinette import init_moulinette_env
|
||||
|
||||
|
||||
LOCALES_DIR = init_moulinette_env()["LOCALES_DIR"]
|
||||
|
@ -23,7 +23,6 @@ install_deps = [
|
|||
"pytz",
|
||||
"pyyaml",
|
||||
"toml",
|
||||
"python-ldap",
|
||||
"gevent-websocket",
|
||||
"bottle",
|
||||
]
|
||||
|
|
|
@ -3,23 +3,10 @@
|
|||
# Global parameters #
|
||||
#############################
|
||||
_global:
|
||||
configuration:
|
||||
authenticate:
|
||||
- all
|
||||
authenticator:
|
||||
default:
|
||||
vendor: dummy
|
||||
help: Dummy Password
|
||||
yoloswag:
|
||||
vendor: dummy
|
||||
help: Dummy Yoloswag Password
|
||||
ldap:
|
||||
vendor: ldap
|
||||
help: admin_password
|
||||
parameters:
|
||||
uri: ldap://localhost:8080
|
||||
base_dn: dc=yunohost,dc=org
|
||||
user_rdn: cn=admin,dc=yunohost,dc=org
|
||||
name: moulitest
|
||||
authentication:
|
||||
api: dummy
|
||||
cli: dummy
|
||||
arguments:
|
||||
-v:
|
||||
full: --version
|
||||
|
@ -43,37 +30,30 @@ testauth:
|
|||
actions:
|
||||
none:
|
||||
api: GET /test-auth/none
|
||||
configuration:
|
||||
authenticate: false
|
||||
authentication:
|
||||
api: null
|
||||
cli: null
|
||||
|
||||
default:
|
||||
api: GET /test-auth/default
|
||||
|
||||
only-api:
|
||||
api: GET /test-auth/only-api
|
||||
configuration:
|
||||
authenticate:
|
||||
- api
|
||||
authentication:
|
||||
api: dummy
|
||||
cli: null
|
||||
|
||||
only-cli:
|
||||
api: GET /test-auth/only-cli
|
||||
configuration:
|
||||
authenticate:
|
||||
- cli
|
||||
authentication:
|
||||
api: null
|
||||
cli: dummy
|
||||
|
||||
other-profile:
|
||||
api: GET /test-auth/other-profile
|
||||
configuration:
|
||||
authenticate:
|
||||
- all
|
||||
authenticator: yoloswag
|
||||
|
||||
ldap:
|
||||
api: GET /test-auth/ldap
|
||||
configuration:
|
||||
authenticate:
|
||||
- all
|
||||
authenticator: ldap
|
||||
authentication:
|
||||
api: yoloswag
|
||||
cli: yoloswag
|
||||
|
||||
with_arg:
|
||||
api: GET /test-auth/with_arg/<super_arg>
|
||||
|
@ -103,21 +83,21 @@ testauth:
|
|||
actions:
|
||||
none:
|
||||
api: GET /test-auth/subcat/none
|
||||
configuration:
|
||||
authenticate: false
|
||||
authentication:
|
||||
api: null
|
||||
cli: null
|
||||
|
||||
default:
|
||||
api: GET /test-auth/subcat/default
|
||||
|
||||
post:
|
||||
api: POST /test-auth/subcat/post
|
||||
configuration:
|
||||
authenticate:
|
||||
- all
|
||||
authenticator: default
|
||||
|
||||
authentication:
|
||||
api: dummy
|
||||
cli: dummy
|
||||
|
||||
other-profile:
|
||||
api: GET /test-auth/subcat/other-profile
|
||||
configuration:
|
||||
authenticator: yoloswag
|
||||
authentication:
|
||||
api: yoloswag
|
||||
cli: yoloswag
|
||||
|
|
|
@ -7,8 +7,6 @@ import os
|
|||
import shutil
|
||||
import pytest
|
||||
|
||||
from .src.ldap_server import LDAPServer
|
||||
|
||||
|
||||
def patch_init(moulinette):
|
||||
"""Configure moulinette to use the YunoHost namespace."""
|
||||
|
@ -182,25 +180,6 @@ def test_toml(tmp_path):
|
|||
return test_file
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_ldif(tmp_path):
|
||||
test_file = tmp_path / "test.txt"
|
||||
from ldif import LDIFWriter
|
||||
|
||||
writer = LDIFWriter(open(str(test_file), "w"))
|
||||
|
||||
writer.unparse(
|
||||
"mail=alice@example.com",
|
||||
{
|
||||
"cn": ["Alice Alison".encode("utf-8")],
|
||||
"mail": ["alice@example.com".encode("utf-8")],
|
||||
"objectclass": ["top".encode("utf-8"), "person".encode("utf-8")],
|
||||
},
|
||||
)
|
||||
|
||||
return test_file
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user():
|
||||
return os.getlogin()
|
||||
|
@ -209,11 +188,3 @@ def user():
|
|||
@pytest.fixture
|
||||
def test_url():
|
||||
return "https://some.test.url/yolo.txt"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ldap_server():
|
||||
server = LDAPServer()
|
||||
server.start()
|
||||
yield server
|
||||
server.stop()
|
||||
|
|
|
@ -1,84 +0,0 @@
|
|||
parents:
|
||||
ou=users:
|
||||
ou: users
|
||||
objectClass:
|
||||
- organizationalUnit
|
||||
- top
|
||||
|
||||
ou=domains:
|
||||
ou: domains
|
||||
objectClass:
|
||||
- organizationalUnit
|
||||
- top
|
||||
|
||||
ou=apps:
|
||||
ou: apps
|
||||
objectClass:
|
||||
- organizationalUnit
|
||||
- top
|
||||
|
||||
ou=permission:
|
||||
ou: permission
|
||||
objectClass:
|
||||
- organizationalUnit
|
||||
- top
|
||||
|
||||
ou=groups:
|
||||
ou: groups
|
||||
objectClass:
|
||||
- organizationalUnit
|
||||
- top
|
||||
|
||||
ou=sudo:
|
||||
ou: sudo
|
||||
objectClass:
|
||||
- organizationalUnit
|
||||
- top
|
||||
|
||||
children:
|
||||
cn=admin,ou=sudo:
|
||||
cn: admin
|
||||
sudoUser: admin
|
||||
sudoHost: ALL
|
||||
sudoCommand: ALL
|
||||
sudoOption: "!authenticate"
|
||||
objectClass:
|
||||
- sudoRole
|
||||
- top
|
||||
cn=admins,ou=groups:
|
||||
cn: admins
|
||||
gidNumber: "4001"
|
||||
memberUid: admin
|
||||
objectClass:
|
||||
- posixGroup
|
||||
- top
|
||||
cn=all_users,ou=groups:
|
||||
cn: all_users
|
||||
gidNumber: "4002"
|
||||
objectClass:
|
||||
- posixGroup
|
||||
- groupOfNamesYnh
|
||||
cn=visitors,ou=groups:
|
||||
cn: visitors
|
||||
gidNumber: "4003"
|
||||
objectClass:
|
||||
- posixGroup
|
||||
- groupOfNamesYnh
|
||||
|
||||
depends_children:
|
||||
cn=mail.main,ou=permission:
|
||||
cn: mail.main
|
||||
gidNumber: "5001"
|
||||
objectClass:
|
||||
- posixGroup
|
||||
- permissionYnh
|
||||
groupPermission:
|
||||
- "cn=all_users,ou=groups,dc=yunohost,dc=org"
|
||||
cn=xmpp.main,ou=permission:
|
||||
cn: xmpp.main
|
||||
gidNumber: "5002"
|
||||
objectClass:
|
||||
- posixGroup
|
||||
- permissionYnh
|
||||
groupPermission:
|
||||
- "cn=all_users,ou=groups,dc=yunohost,dc=org"
|
|
@ -1,610 +0,0 @@
|
|||
# OpenLDAP Core schema
|
||||
# $OpenLDAP$
|
||||
## This work is part of OpenLDAP Software <http://www.openldap.org/>.
|
||||
##
|
||||
## Copyright 1998-2019 The OpenLDAP Foundation.
|
||||
## All rights reserved.
|
||||
##
|
||||
## Redistribution and use in source and binary forms, with or without
|
||||
## modification, are permitted only as authorized by the OpenLDAP
|
||||
## Public License.
|
||||
##
|
||||
## A copy of this license is available in the file LICENSE in the
|
||||
## top-level directory of the distribution or, alternatively, at
|
||||
## <http://www.OpenLDAP.org/license.html>.
|
||||
#
|
||||
## Portions Copyright (C) The Internet Society (1997-2006).
|
||||
## All Rights Reserved.
|
||||
##
|
||||
## This document and translations of it may be copied and furnished to
|
||||
## others, and derivative works that comment on or otherwise explain it
|
||||
## or assist in its implementation may be prepared, copied, published
|
||||
## and distributed, in whole or in part, without restriction of any
|
||||
## kind, provided that the above copyright notice and this paragraph are
|
||||
## included on all such copies and derivative works. However, this
|
||||
## document itself may not be modified in any way, such as by removing
|
||||
## the copyright notice or references to the Internet Society or other
|
||||
## Internet organizations, except as needed for the purpose of
|
||||
## developing Internet standards in which case the procedures for
|
||||
## copyrights defined in the Internet Standards process must be
|
||||
## followed, or as required to translate it into languages other than
|
||||
## English.
|
||||
##
|
||||
## The limited permissions granted above are perpetual and will not be
|
||||
## revoked by the Internet Society or its successors or assigns.
|
||||
##
|
||||
## This document and the information contained herein is provided on an
|
||||
## "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
|
||||
## TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
|
||||
## BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
|
||||
## HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
|
||||
## MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
|
||||
|
||||
#
|
||||
#
|
||||
# Includes LDAPv3 schema items from:
|
||||
# RFC 2252/2256 (LDAPv3)
|
||||
#
|
||||
# Select standard track schema items:
|
||||
# RFC 1274 (uid/dc)
|
||||
# RFC 2079 (URI)
|
||||
# RFC 2247 (dc/dcObject)
|
||||
# RFC 2587 (PKI)
|
||||
# RFC 2589 (Dynamic Directory Services)
|
||||
# RFC 4524 (associatedDomain)
|
||||
#
|
||||
# Select informational schema items:
|
||||
# RFC 2377 (uidObject)
|
||||
|
||||
#
|
||||
# Standard attribute types from RFC 2256
|
||||
#
|
||||
|
||||
# system schema
|
||||
#attributetype ( 2.5.4.0 NAME 'objectClass'
|
||||
# DESC 'RFC2256: object classes of the entity'
|
||||
# EQUALITY objectIdentifierMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.38 )
|
||||
|
||||
# system schema
|
||||
#attributetype ( 2.5.4.1 NAME ( 'aliasedObjectName' 'aliasedEntryName' )
|
||||
# DESC 'RFC2256: name of aliased object'
|
||||
# EQUALITY distinguishedNameMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 2.5.4.2 NAME 'knowledgeInformation'
|
||||
DESC 'RFC2256: knowledge information'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} )
|
||||
|
||||
# system schema
|
||||
#attributetype ( 2.5.4.3 NAME ( 'cn' 'commonName' )
|
||||
# DESC 'RFC2256: common name(s) for which the entity is known by'
|
||||
# SUP name )
|
||||
|
||||
attributetype ( 2.5.4.4 NAME ( 'sn' 'surname' )
|
||||
DESC 'RFC2256: last (family) name(s) for which the entity is known by'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.5 NAME 'serialNumber'
|
||||
DESC 'RFC2256: serial number of the entity'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.44{64} )
|
||||
|
||||
# RFC 4519 definition ('countryName' in X.500 and RFC2256)
|
||||
attributetype ( 2.5.4.6 NAME ( 'c' 'countryName' )
|
||||
DESC 'RFC4519: two-letter ISO-3166 country code'
|
||||
SUP name
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.11
|
||||
SINGLE-VALUE )
|
||||
|
||||
#attributetype ( 2.5.4.6 NAME ( 'c' 'countryName' )
|
||||
# DESC 'RFC2256: ISO-3166 country 2-letter code'
|
||||
# SUP name SINGLE-VALUE )
|
||||
|
||||
attributetype ( 2.5.4.7 NAME ( 'l' 'localityName' )
|
||||
DESC 'RFC2256: locality which this object resides in'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.8 NAME ( 'st' 'stateOrProvinceName' )
|
||||
DESC 'RFC2256: state or province which this object resides in'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.9 NAME ( 'street' 'streetAddress' )
|
||||
DESC 'RFC2256: street address of this object'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )
|
||||
|
||||
attributetype ( 2.5.4.10 NAME ( 'o' 'organizationName' )
|
||||
DESC 'RFC2256: organization this object belongs to'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.11 NAME ( 'ou' 'organizationalUnitName' )
|
||||
DESC 'RFC2256: organizational unit this object belongs to'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.12 NAME 'title'
|
||||
DESC 'RFC2256: title associated with the entity'
|
||||
SUP name )
|
||||
|
||||
# system schema
|
||||
#attributetype ( 2.5.4.13 NAME 'description'
|
||||
# DESC 'RFC2256: descriptive information'
|
||||
# EQUALITY caseIgnoreMatch
|
||||
# SUBSTR caseIgnoreSubstringsMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
|
||||
|
||||
# Deprecated by enhancedSearchGuide
|
||||
attributetype ( 2.5.4.14 NAME 'searchGuide'
|
||||
DESC 'RFC2256: search guide, deprecated by enhancedSearchGuide'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.25 )
|
||||
|
||||
attributetype ( 2.5.4.15 NAME 'businessCategory'
|
||||
DESC 'RFC2256: business category'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )
|
||||
|
||||
attributetype ( 2.5.4.16 NAME 'postalAddress'
|
||||
DESC 'RFC2256: postal address'
|
||||
EQUALITY caseIgnoreListMatch
|
||||
SUBSTR caseIgnoreListSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.41 )
|
||||
|
||||
attributetype ( 2.5.4.17 NAME 'postalCode'
|
||||
DESC 'RFC2256: postal code'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{40} )
|
||||
|
||||
attributetype ( 2.5.4.18 NAME 'postOfficeBox'
|
||||
DESC 'RFC2256: Post Office Box'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{40} )
|
||||
|
||||
attributetype ( 2.5.4.19 NAME 'physicalDeliveryOfficeName'
|
||||
DESC 'RFC2256: Physical Delivery Office Name'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )
|
||||
|
||||
attributetype ( 2.5.4.20 NAME 'telephoneNumber'
|
||||
DESC 'RFC2256: Telephone Number'
|
||||
EQUALITY telephoneNumberMatch
|
||||
SUBSTR telephoneNumberSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.50{32} )
|
||||
|
||||
attributetype ( 2.5.4.21 NAME 'telexNumber'
|
||||
DESC 'RFC2256: Telex Number'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.52 )
|
||||
|
||||
attributetype ( 2.5.4.22 NAME 'teletexTerminalIdentifier'
|
||||
DESC 'RFC2256: Teletex Terminal Identifier'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.51 )
|
||||
|
||||
attributetype ( 2.5.4.23 NAME ( 'facsimileTelephoneNumber' 'fax' )
|
||||
DESC 'RFC2256: Facsimile (Fax) Telephone Number'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.22 )
|
||||
|
||||
attributetype ( 2.5.4.24 NAME 'x121Address'
|
||||
DESC 'RFC2256: X.121 Address'
|
||||
EQUALITY numericStringMatch
|
||||
SUBSTR numericStringSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.36{15} )
|
||||
|
||||
attributetype ( 2.5.4.25 NAME 'internationaliSDNNumber'
|
||||
DESC 'RFC2256: international ISDN number'
|
||||
EQUALITY numericStringMatch
|
||||
SUBSTR numericStringSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.36{16} )
|
||||
|
||||
attributetype ( 2.5.4.26 NAME 'registeredAddress'
|
||||
DESC 'RFC2256: registered postal address'
|
||||
SUP postalAddress
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.41 )
|
||||
|
||||
attributetype ( 2.5.4.27 NAME 'destinationIndicator'
|
||||
DESC 'RFC2256: destination indicator'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.44{128} )
|
||||
|
||||
attributetype ( 2.5.4.28 NAME 'preferredDeliveryMethod'
|
||||
DESC 'RFC2256: preferred delivery method'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.14
|
||||
SINGLE-VALUE )
|
||||
|
||||
attributetype ( 2.5.4.29 NAME 'presentationAddress'
|
||||
DESC 'RFC2256: presentation address'
|
||||
EQUALITY presentationAddressMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.43
|
||||
SINGLE-VALUE )
|
||||
|
||||
attributetype ( 2.5.4.30 NAME 'supportedApplicationContext'
|
||||
DESC 'RFC2256: supported application context'
|
||||
EQUALITY objectIdentifierMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.38 )
|
||||
|
||||
attributetype ( 2.5.4.31 NAME 'member'
|
||||
DESC 'RFC2256: member of a group'
|
||||
SUP distinguishedName )
|
||||
|
||||
attributetype ( 2.5.4.32 NAME 'owner'
|
||||
DESC 'RFC2256: owner (of the object)'
|
||||
SUP distinguishedName )
|
||||
|
||||
attributetype ( 2.5.4.33 NAME 'roleOccupant'
|
||||
DESC 'RFC2256: occupant of role'
|
||||
SUP distinguishedName )
|
||||
|
||||
# system schema
|
||||
#attributetype ( 2.5.4.34 NAME 'seeAlso'
|
||||
# DESC 'RFC2256: DN of related object'
|
||||
# SUP distinguishedName )
|
||||
|
||||
# system schema
|
||||
#attributetype ( 2.5.4.35 NAME 'userPassword'
|
||||
# DESC 'RFC2256/2307: password of user'
|
||||
# EQUALITY octetStringMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.40{128} )
|
||||
|
||||
# Must be transferred using ;binary
|
||||
# with certificateExactMatch rule (per X.509)
|
||||
attributetype ( 2.5.4.36 NAME 'userCertificate'
|
||||
DESC 'RFC2256: X.509 user certificate, use ;binary'
|
||||
EQUALITY certificateExactMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.8 )
|
||||
|
||||
# Must be transferred using ;binary
|
||||
# with certificateExactMatch rule (per X.509)
|
||||
attributetype ( 2.5.4.37 NAME 'cACertificate'
|
||||
DESC 'RFC2256: X.509 CA certificate, use ;binary'
|
||||
EQUALITY certificateExactMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.8 )
|
||||
|
||||
# Must be transferred using ;binary
|
||||
attributetype ( 2.5.4.38 NAME 'authorityRevocationList'
|
||||
DESC 'RFC2256: X.509 authority revocation list, use ;binary'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 )
|
||||
|
||||
# Must be transferred using ;binary
|
||||
attributetype ( 2.5.4.39 NAME 'certificateRevocationList'
|
||||
DESC 'RFC2256: X.509 certificate revocation list, use ;binary'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 )
|
||||
|
||||
# Must be stored and requested in the binary form
|
||||
attributetype ( 2.5.4.40 NAME 'crossCertificatePair'
|
||||
DESC 'RFC2256: X.509 cross certificate pair, use ;binary'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.10 )
|
||||
|
||||
# system schema
|
||||
#attributetype ( 2.5.4.41 NAME 'name'
|
||||
# EQUALITY caseIgnoreMatch
|
||||
# SUBSTR caseIgnoreSubstringsMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} )
|
||||
|
||||
attributetype ( 2.5.4.42 NAME ( 'givenName' 'gn' )
|
||||
DESC 'RFC2256: first name(s) for which the entity is known by'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.43 NAME 'initials'
|
||||
DESC 'RFC2256: initials of some or all of names, but not the surname(s).'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.44 NAME 'generationQualifier'
|
||||
DESC 'RFC2256: name qualifier indicating a generation'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.45 NAME 'x500UniqueIdentifier'
|
||||
DESC 'RFC2256: X.500 unique identifier'
|
||||
EQUALITY bitStringMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.6 )
|
||||
|
||||
attributetype ( 2.5.4.46 NAME 'dnQualifier'
|
||||
DESC 'RFC2256: DN qualifier'
|
||||
EQUALITY caseIgnoreMatch
|
||||
ORDERING caseIgnoreOrderingMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.44 )
|
||||
|
||||
attributetype ( 2.5.4.47 NAME 'enhancedSearchGuide'
|
||||
DESC 'RFC2256: enhanced search guide'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.21 )
|
||||
|
||||
attributetype ( 2.5.4.48 NAME 'protocolInformation'
|
||||
DESC 'RFC2256: protocol information'
|
||||
EQUALITY protocolInformationMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.42 )
|
||||
|
||||
# system schema
|
||||
#attributetype ( 2.5.4.49 NAME 'distinguishedName'
|
||||
# EQUALITY distinguishedNameMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 )
|
||||
|
||||
attributetype ( 2.5.4.50 NAME 'uniqueMember'
|
||||
DESC 'RFC2256: unique member of a group'
|
||||
EQUALITY uniqueMemberMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.34 )
|
||||
|
||||
attributetype ( 2.5.4.51 NAME 'houseIdentifier'
|
||||
DESC 'RFC2256: house identifier'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{32768} )
|
||||
|
||||
# Must be transferred using ;binary
|
||||
attributetype ( 2.5.4.52 NAME 'supportedAlgorithms'
|
||||
DESC 'RFC2256: supported algorithms'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.49 )
|
||||
|
||||
# Must be transferred using ;binary
|
||||
attributetype ( 2.5.4.53 NAME 'deltaRevocationList'
|
||||
DESC 'RFC2256: delta revocation list; use ;binary'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.9 )
|
||||
|
||||
attributetype ( 2.5.4.54 NAME 'dmdName'
|
||||
DESC 'RFC2256: name of DMD'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 2.5.4.65 NAME 'pseudonym'
|
||||
DESC 'X.520(4th): pseudonym for the object'
|
||||
SUP name )
|
||||
|
||||
# Standard object classes from RFC2256
|
||||
|
||||
# system schema
|
||||
#objectclass ( 2.5.6.0 NAME 'top'
|
||||
# DESC 'RFC2256: top of the superclass chain'
|
||||
# ABSTRACT
|
||||
# MUST objectClass )
|
||||
|
||||
# system schema
|
||||
#objectclass ( 2.5.6.1 NAME 'alias'
|
||||
# DESC 'RFC2256: an alias'
|
||||
# SUP top STRUCTURAL
|
||||
# MUST aliasedObjectName )
|
||||
|
||||
objectclass ( 2.5.6.2 NAME 'country'
|
||||
DESC 'RFC2256: a country'
|
||||
SUP top STRUCTURAL
|
||||
MUST c
|
||||
MAY ( searchGuide $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.3 NAME 'locality'
|
||||
DESC 'RFC2256: a locality'
|
||||
SUP top STRUCTURAL
|
||||
MAY ( street $ seeAlso $ searchGuide $ st $ l $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.4 NAME 'organization'
|
||||
DESC 'RFC2256: an organization'
|
||||
SUP top STRUCTURAL
|
||||
MUST o
|
||||
MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $
|
||||
x121Address $ registeredAddress $ destinationIndicator $
|
||||
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
|
||||
telephoneNumber $ internationaliSDNNumber $
|
||||
facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $
|
||||
postalAddress $ physicalDeliveryOfficeName $ st $ l $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.5 NAME 'organizationalUnit'
|
||||
DESC 'RFC2256: an organizational unit'
|
||||
SUP top STRUCTURAL
|
||||
MUST ou
|
||||
MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $
|
||||
x121Address $ registeredAddress $ destinationIndicator $
|
||||
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
|
||||
telephoneNumber $ internationaliSDNNumber $
|
||||
facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $
|
||||
postalAddress $ physicalDeliveryOfficeName $ st $ l $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.6 NAME 'person'
|
||||
DESC 'RFC2256: a person'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( sn $ cn )
|
||||
MAY ( userPassword $ telephoneNumber $ seeAlso $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.7 NAME 'organizationalPerson'
|
||||
DESC 'RFC2256: an organizational person'
|
||||
SUP person STRUCTURAL
|
||||
MAY ( title $ x121Address $ registeredAddress $ destinationIndicator $
|
||||
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
|
||||
telephoneNumber $ internationaliSDNNumber $
|
||||
facsimileTelephoneNumber $ street $ postOfficeBox $ postalCode $
|
||||
postalAddress $ physicalDeliveryOfficeName $ ou $ st $ l ) )
|
||||
|
||||
objectclass ( 2.5.6.8 NAME 'organizationalRole'
|
||||
DESC 'RFC2256: an organizational role'
|
||||
SUP top STRUCTURAL
|
||||
MUST cn
|
||||
MAY ( x121Address $ registeredAddress $ destinationIndicator $
|
||||
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
|
||||
telephoneNumber $ internationaliSDNNumber $ facsimileTelephoneNumber $
|
||||
seeAlso $ roleOccupant $ preferredDeliveryMethod $ street $
|
||||
postOfficeBox $ postalCode $ postalAddress $
|
||||
physicalDeliveryOfficeName $ ou $ st $ l $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.9 NAME 'groupOfNames'
|
||||
DESC 'RFC2256: a group of names (DNs)'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( member $ cn )
|
||||
MAY ( businessCategory $ seeAlso $ owner $ ou $ o $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.10 NAME 'residentialPerson'
|
||||
DESC 'RFC2256: an residential person'
|
||||
SUP person STRUCTURAL
|
||||
MUST l
|
||||
MAY ( businessCategory $ x121Address $ registeredAddress $
|
||||
destinationIndicator $ preferredDeliveryMethod $ telexNumber $
|
||||
teletexTerminalIdentifier $ telephoneNumber $ internationaliSDNNumber $
|
||||
facsimileTelephoneNumber $ preferredDeliveryMethod $ street $
|
||||
postOfficeBox $ postalCode $ postalAddress $
|
||||
physicalDeliveryOfficeName $ st $ l ) )
|
||||
|
||||
objectclass ( 2.5.6.11 NAME 'applicationProcess'
|
||||
DESC 'RFC2256: an application process'
|
||||
SUP top STRUCTURAL
|
||||
MUST cn
|
||||
MAY ( seeAlso $ ou $ l $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.12 NAME 'applicationEntity'
|
||||
DESC 'RFC2256: an application entity'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( presentationAddress $ cn )
|
||||
MAY ( supportedApplicationContext $ seeAlso $ ou $ o $ l $
|
||||
description ) )
|
||||
|
||||
objectclass ( 2.5.6.13 NAME 'dSA'
|
||||
DESC 'RFC2256: a directory system agent (a server)'
|
||||
SUP applicationEntity STRUCTURAL
|
||||
MAY knowledgeInformation )
|
||||
|
||||
objectclass ( 2.5.6.14 NAME 'device'
|
||||
DESC 'RFC2256: a device'
|
||||
SUP top STRUCTURAL
|
||||
MUST cn
|
||||
MAY ( serialNumber $ seeAlso $ owner $ ou $ o $ l $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.15 NAME 'strongAuthenticationUser'
|
||||
DESC 'RFC2256: a strong authentication user'
|
||||
SUP top AUXILIARY
|
||||
MUST userCertificate )
|
||||
|
||||
objectclass ( 2.5.6.16 NAME 'certificationAuthority'
|
||||
DESC 'RFC2256: a certificate authority'
|
||||
SUP top AUXILIARY
|
||||
MUST ( authorityRevocationList $ certificateRevocationList $
|
||||
cACertificate ) MAY crossCertificatePair )
|
||||
|
||||
objectclass ( 2.5.6.17 NAME 'groupOfUniqueNames'
|
||||
DESC 'RFC2256: a group of unique names (DN and Unique Identifier)'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( uniqueMember $ cn )
|
||||
MAY ( businessCategory $ seeAlso $ owner $ ou $ o $ description ) )
|
||||
|
||||
objectclass ( 2.5.6.18 NAME 'userSecurityInformation'
|
||||
DESC 'RFC2256: a user security information'
|
||||
SUP top AUXILIARY
|
||||
MAY ( supportedAlgorithms ) )
|
||||
|
||||
objectclass ( 2.5.6.16.2 NAME 'certificationAuthority-V2'
|
||||
SUP certificationAuthority
|
||||
AUXILIARY MAY ( deltaRevocationList ) )
|
||||
|
||||
objectclass ( 2.5.6.19 NAME 'cRLDistributionPoint'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( cn )
|
||||
MAY ( certificateRevocationList $ authorityRevocationList $
|
||||
deltaRevocationList ) )
|
||||
|
||||
objectclass ( 2.5.6.20 NAME 'dmd'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( dmdName )
|
||||
MAY ( userPassword $ searchGuide $ seeAlso $ businessCategory $
|
||||
x121Address $ registeredAddress $ destinationIndicator $
|
||||
preferredDeliveryMethod $ telexNumber $ teletexTerminalIdentifier $
|
||||
telephoneNumber $ internationaliSDNNumber $ facsimileTelephoneNumber $
|
||||
street $ postOfficeBox $ postalCode $ postalAddress $
|
||||
physicalDeliveryOfficeName $ st $ l $ description ) )
|
||||
|
||||
#
|
||||
# Object Classes from RFC 2587
|
||||
#
|
||||
objectclass ( 2.5.6.21 NAME 'pkiUser'
|
||||
DESC 'RFC2587: a PKI user'
|
||||
SUP top AUXILIARY
|
||||
MAY userCertificate )
|
||||
|
||||
objectclass ( 2.5.6.22 NAME 'pkiCA'
|
||||
DESC 'RFC2587: PKI certificate authority'
|
||||
SUP top AUXILIARY
|
||||
MAY ( authorityRevocationList $ certificateRevocationList $
|
||||
cACertificate $ crossCertificatePair ) )
|
||||
|
||||
objectclass ( 2.5.6.23 NAME 'deltaCRL'
|
||||
DESC 'RFC2587: PKI user'
|
||||
SUP top AUXILIARY
|
||||
MAY deltaRevocationList )
|
||||
|
||||
#
|
||||
# Standard Track URI label schema from RFC 2079
|
||||
# system schema
|
||||
#attributetype ( 1.3.6.1.4.1.250.1.57 NAME 'labeledURI'
|
||||
# DESC 'RFC2079: Uniform Resource Identifier with optional label'
|
||||
# EQUALITY caseExactMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
|
||||
|
||||
objectclass ( 1.3.6.1.4.1.250.3.15 NAME 'labeledURIObject'
|
||||
DESC 'RFC2079: object that contains the URI attribute type'
|
||||
SUP top AUXILIARY
|
||||
MAY ( labeledURI ) )
|
||||
|
||||
#
|
||||
# Derived from RFC 1274, but with new "short names"
|
||||
#
|
||||
#attributetype ( 0.9.2342.19200300.100.1.1
|
||||
# NAME ( 'uid' 'userid' )
|
||||
# DESC 'RFC1274: user identifier'
|
||||
# EQUALITY caseIgnoreMatch
|
||||
# SUBSTR caseIgnoreSubstringsMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{256} )
|
||||
|
||||
attributetype ( 0.9.2342.19200300.100.1.3
|
||||
NAME ( 'mail' 'rfc822Mailbox' )
|
||||
DESC 'RFC1274: RFC822 Mailbox'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SUBSTR caseIgnoreIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{256} )
|
||||
|
||||
objectclass ( 0.9.2342.19200300.100.4.19 NAME 'simpleSecurityObject'
|
||||
DESC 'RFC1274: simple security object'
|
||||
SUP top AUXILIARY
|
||||
MUST userPassword )
|
||||
|
||||
# RFC 1274 + RFC 2247
|
||||
attributetype ( 0.9.2342.19200300.100.1.25
|
||||
NAME ( 'dc' 'domainComponent' )
|
||||
DESC 'RFC1274/2247: domain component'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SUBSTR caseIgnoreIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
|
||||
|
||||
# RFC 2247
|
||||
objectclass ( 1.3.6.1.4.1.1466.344 NAME 'dcObject'
|
||||
DESC 'RFC2247: domain component object'
|
||||
SUP top AUXILIARY MUST dc )
|
||||
|
||||
# RFC 2377
|
||||
objectclass ( 1.3.6.1.1.3.1 NAME 'uidObject'
|
||||
DESC 'RFC2377: uid object'
|
||||
SUP top AUXILIARY MUST uid )
|
||||
|
||||
# RFC 4524
|
||||
# The 'associatedDomain' attribute specifies DNS [RFC1034][RFC2181]
|
||||
# host names [RFC1123] that are associated with an object. That is,
|
||||
# values of this attribute should conform to the following ABNF:
|
||||
#
|
||||
# domain = root / label *( DOT label )
|
||||
# root = SPACE
|
||||
# label = LETDIG [ *61( LETDIG / HYPHEN ) LETDIG ]
|
||||
# LETDIG = %x30-39 / %x41-5A / %x61-7A ; "0" - "9" / "A"-"Z" / "a"-"z"
|
||||
# SPACE = %x20 ; space (" ")
|
||||
# HYPHEN = %x2D ; hyphen ("-")
|
||||
# DOT = %x2E ; period (".")
|
||||
attributetype ( 0.9.2342.19200300.100.1.37
|
||||
NAME 'associatedDomain'
|
||||
DESC 'RFC1274: domain associated with object'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SUBSTR caseIgnoreIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
# RFC 2459 -- deprecated in favor of 'mail' (in cosine.schema)
|
||||
attributetype ( 1.2.840.113549.1.9.1
|
||||
NAME ( 'email' 'emailAddress' 'pkcs9email' )
|
||||
DESC 'RFC3280: legacy attribute for email addresses in DNs'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SUBSTR caseIgnoreIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} )
|
||||
|
File diff suppressed because it is too large
Load diff
|
@ -1,155 +0,0 @@
|
|||
# inetorgperson.schema -- InetOrgPerson (RFC2798)
|
||||
# $OpenLDAP$
|
||||
## This work is part of OpenLDAP Software <http://www.openldap.org/>.
|
||||
##
|
||||
## Copyright 1998-2019 The OpenLDAP Foundation.
|
||||
## All rights reserved.
|
||||
##
|
||||
## Redistribution and use in source and binary forms, with or without
|
||||
## modification, are permitted only as authorized by the OpenLDAP
|
||||
## Public License.
|
||||
##
|
||||
## A copy of this license is available in the file LICENSE in the
|
||||
## top-level directory of the distribution or, alternatively, at
|
||||
## <http://www.OpenLDAP.org/license.html>.
|
||||
#
|
||||
# InetOrgPerson (RFC2798)
|
||||
#
|
||||
# Depends upon
|
||||
# Definition of an X.500 Attribute Type and an Object Class to Hold
|
||||
# Uniform Resource Identifiers (URIs) [RFC2079]
|
||||
# (core.schema)
|
||||
#
|
||||
# A Summary of the X.500(96) User Schema for use with LDAPv3 [RFC2256]
|
||||
# (core.schema)
|
||||
#
|
||||
# The COSINE and Internet X.500 Schema [RFC1274] (cosine.schema)
|
||||
|
||||
# carLicense
|
||||
# This multivalued field is used to record the values of the license or
|
||||
# registration plate associated with an individual.
|
||||
attributetype ( 2.16.840.1.113730.3.1.1
|
||||
NAME 'carLicense'
|
||||
DESC 'RFC2798: vehicle license or registration plate'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
|
||||
|
||||
# departmentNumber
|
||||
# Code for department to which a person belongs. This can also be
|
||||
# strictly numeric (e.g., 1234) or alphanumeric (e.g., ABC/123).
|
||||
attributetype ( 2.16.840.1.113730.3.1.2
|
||||
NAME 'departmentNumber'
|
||||
DESC 'RFC2798: identifies a department within an organization'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
|
||||
|
||||
# displayName
|
||||
# When displaying an entry, especially within a one-line summary list, it
|
||||
# is useful to be able to identify a name to be used. Since other attri-
|
||||
# bute types such as 'cn' are multivalued, an additional attribute type is
|
||||
# needed. Display name is defined for this purpose.
|
||||
attributetype ( 2.16.840.1.113730.3.1.241
|
||||
NAME 'displayName'
|
||||
DESC 'RFC2798: preferred name to be used when displaying entries'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
|
||||
SINGLE-VALUE )
|
||||
|
||||
# employeeNumber
|
||||
# Numeric or alphanumeric identifier assigned to a person, typically based
|
||||
# on order of hire or association with an organization. Single valued.
|
||||
attributetype ( 2.16.840.1.113730.3.1.3
|
||||
NAME 'employeeNumber'
|
||||
DESC 'RFC2798: numerically identifies an employee within an organization'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
|
||||
SINGLE-VALUE )
|
||||
|
||||
# employeeType
|
||||
# Used to identify the employer to employee relationship. Typical values
|
||||
# used will be "Contractor", "Employee", "Intern", "Temp", "External", and
|
||||
# "Unknown" but any value may be used.
|
||||
attributetype ( 2.16.840.1.113730.3.1.4
|
||||
NAME 'employeeType'
|
||||
DESC 'RFC2798: type of employment for a person'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 )
|
||||
|
||||
# jpegPhoto
|
||||
# Used to store one or more images of a person using the JPEG File
|
||||
# Interchange Format [JFIF].
|
||||
# Note that the jpegPhoto attribute type was defined for use in the
|
||||
# Internet X.500 pilots but no referencable definition for it could be
|
||||
# located.
|
||||
attributetype ( 0.9.2342.19200300.100.1.60
|
||||
NAME 'jpegPhoto'
|
||||
DESC 'RFC2798: a JPEG image'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.28 )
|
||||
|
||||
# preferredLanguage
|
||||
# Used to indicate an individual's preferred written or spoken
|
||||
# language. This is useful for international correspondence or human-
|
||||
# computer interaction. Values for this attribute type MUST conform to
|
||||
# the definition of the Accept-Language header field defined in
|
||||
# [RFC2068] with one exception: the sequence "Accept-Language" ":"
|
||||
# should be omitted. This is a single valued attribute type.
|
||||
attributetype ( 2.16.840.1.113730.3.1.39
|
||||
NAME 'preferredLanguage'
|
||||
DESC 'RFC2798: preferred written or spoken language for a person'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
|
||||
SINGLE-VALUE )
|
||||
|
||||
# userSMIMECertificate
|
||||
# A PKCS#7 [RFC2315] SignedData, where the content that is signed is
|
||||
# ignored by consumers of userSMIMECertificate values. It is
|
||||
# recommended that values have a `contentType' of data with an absent
|
||||
# `content' field. Values of this attribute contain a person's entire
|
||||
# certificate chain and an smimeCapabilities field [RFC2633] that at a
|
||||
# minimum describes their SMIME algorithm capabilities. Values for
|
||||
# this attribute are to be stored and requested in binary form, as
|
||||
# 'userSMIMECertificate;binary'. If available, this attribute is
|
||||
# preferred over the userCertificate attribute for S/MIME applications.
|
||||
## OpenLDAP note: ";binary" transfer should NOT be used as syntax is binary
|
||||
attributetype ( 2.16.840.1.113730.3.1.40
|
||||
NAME 'userSMIMECertificate'
|
||||
DESC 'RFC2798: PKCS#7 SignedData used to support S/MIME'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 )
|
||||
|
||||
# userPKCS12
|
||||
# PKCS #12 [PKCS12] provides a format for exchange of personal identity
|
||||
# information. When such information is stored in a directory service,
|
||||
# the userPKCS12 attribute should be used. This attribute is to be stored
|
||||
# and requested in binary form, as 'userPKCS12;binary'. The attribute
|
||||
# values are PFX PDUs stored as binary data.
|
||||
## OpenLDAP note: ";binary" transfer should NOT be used as syntax is binary
|
||||
attributetype ( 2.16.840.1.113730.3.1.216
|
||||
NAME 'userPKCS12'
|
||||
DESC 'RFC2798: personal identity information, a PKCS #12 PFX'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.5 )
|
||||
|
||||
|
||||
# inetOrgPerson
|
||||
# The inetOrgPerson represents people who are associated with an
|
||||
# organization in some way. It is a structural class and is derived
|
||||
# from the organizationalPerson which is defined in X.521 [X521].
|
||||
objectclass ( 2.16.840.1.113730.3.2.2
|
||||
NAME 'inetOrgPerson'
|
||||
DESC 'RFC2798: Internet Organizational Person'
|
||||
SUP organizationalPerson
|
||||
STRUCTURAL
|
||||
MAY (
|
||||
audio $ businessCategory $ carLicense $ departmentNumber $
|
||||
displayName $ employeeNumber $ employeeType $ givenName $
|
||||
homePhone $ homePostalAddress $ initials $ jpegPhoto $
|
||||
labeledURI $ mail $ manager $ mobile $ o $ pager $
|
||||
photo $ roomNumber $ secretary $ uid $ userCertificate $
|
||||
x500uniqueIdentifier $ preferredLanguage $
|
||||
userSMIMECertificate $ userPKCS12 )
|
||||
)
|
|
@ -1,88 +0,0 @@
|
|||
## LDAP Schema Yunohost EMAIL
|
||||
## Version 0.1
|
||||
## Adrien Beudin
|
||||
|
||||
# Attributes
|
||||
attributetype ( 1.3.6.1.4.1.40328.1.20.2.1
|
||||
NAME 'maildrop'
|
||||
DESC 'Mail addresses where mails are forwarded -- ie forwards'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{512})
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.40328.1.20.2.2
|
||||
NAME 'mailalias'
|
||||
DESC 'Mail addresses accepted by this account -- ie aliases'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{512})
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.40328.1.20.2.3
|
||||
NAME 'mailenable'
|
||||
DESC 'Mail Account validity'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{8})
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.40328.1.20.2.4
|
||||
NAME 'mailbox'
|
||||
DESC 'Mailbox path where mails are delivered'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{512})
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.40328.1.20.2.5
|
||||
NAME 'virtualdomain'
|
||||
DESC 'A mail domain name'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{512})
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.40328.1.20.2.6
|
||||
NAME 'virtualdomaindescription'
|
||||
DESC 'Virtual domain description'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{512})
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.40328.1.20.2.7
|
||||
NAME 'mailuserquota'
|
||||
DESC 'Mailbox quota for a user'
|
||||
EQUALITY caseIgnoreMatch
|
||||
SUBSTR caseIgnoreSubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{16} SINGLE-VALUE )
|
||||
|
||||
# Mail Account Objectclass
|
||||
objectclass ( 1.3.6.1.4.1.40328.1.1.2.1
|
||||
NAME 'mailAccount'
|
||||
DESC 'Mail Account'
|
||||
SUP top
|
||||
AUXILIARY
|
||||
MUST (
|
||||
mail
|
||||
)
|
||||
MAY (
|
||||
mailalias $ maildrop $ mailenable $ mailbox $ mailuserquota
|
||||
)
|
||||
)
|
||||
|
||||
# Mail Domain Objectclass
|
||||
objectclass ( 1.3.6.1.4.1.40328.1.1.2.2
|
||||
NAME 'mailDomain'
|
||||
DESC 'Domain mail entry'
|
||||
SUP top
|
||||
STRUCTURAL
|
||||
MUST (
|
||||
virtualdomain
|
||||
)
|
||||
MAY (
|
||||
virtualdomaindescription $ mailuserquota
|
||||
)
|
||||
)
|
||||
|
||||
# Mail Group Objectclass
|
||||
objectclass ( 1.3.6.1.4.1.40328.1.1.2.3
|
||||
NAME 'mailGroup' SUP top AUXILIARY
|
||||
DESC 'Mail Group'
|
||||
MUST ( mail )
|
||||
)
|
|
@ -1,237 +0,0 @@
|
|||
# $OpenLDAP$
|
||||
## This work is part of OpenLDAP Software <http://www.openldap.org/>.
|
||||
##
|
||||
## Copyright 1998-2019 The OpenLDAP Foundation.
|
||||
## All rights reserved.
|
||||
##
|
||||
## Redistribution and use in source and binary forms, with or without
|
||||
## modification, are permitted only as authorized by the OpenLDAP
|
||||
## Public License.
|
||||
##
|
||||
## A copy of this license is available in the file LICENSE in the
|
||||
## top-level directory of the distribution or, alternatively, at
|
||||
## <http://www.OpenLDAP.org/license.html>.
|
||||
|
||||
# Definitions from RFC2307 (Experimental)
|
||||
# An Approach for Using LDAP as a Network Information Service
|
||||
|
||||
# Depends upon core.schema and cosine.schema
|
||||
|
||||
# Note: The definitions in RFC2307 are given in syntaxes closely related
|
||||
# to those in RFC2252, however, some liberties are taken that are not
|
||||
# supported by RFC2252. This file has been written following RFC2252
|
||||
# strictly.
|
||||
|
||||
# OID Base is iso(1) org(3) dod(6) internet(1) directory(1) nisSchema(1).
|
||||
# i.e. nisSchema in RFC2307 is 1.3.6.1.1.1
|
||||
#
|
||||
# Syntaxes are under 1.3.6.1.1.1.0 (two new syntaxes are defined)
|
||||
# validaters for these syntaxes are incomplete, they only
|
||||
# implement printable string validation (which is good as the
|
||||
# common use of these syntaxes violates the specification).
|
||||
# Attribute types are under 1.3.6.1.1.1.1
|
||||
# Object classes are under 1.3.6.1.1.1.2
|
||||
|
||||
# Attribute Type Definitions
|
||||
|
||||
# builtin
|
||||
#attributetype ( 1.3.6.1.1.1.1.0 NAME 'uidNumber'
|
||||
# DESC 'An integer uniquely identifying a user in an administrative domain'
|
||||
# EQUALITY integerMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
# builtin
|
||||
#attributetype ( 1.3.6.1.1.1.1.1 NAME 'gidNumber'
|
||||
# DESC 'An integer uniquely identifying a group in an administrative domain'
|
||||
# EQUALITY integerMatch
|
||||
# SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.2 NAME 'gecos'
|
||||
DESC 'The GECOS field; the common name'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SUBSTR caseIgnoreIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.3 NAME 'homeDirectory'
|
||||
DESC 'The absolute path to the home directory'
|
||||
EQUALITY caseExactIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.4 NAME 'loginShell'
|
||||
DESC 'The path to the login shell'
|
||||
EQUALITY caseExactIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.5 NAME 'shadowLastChange'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.6 NAME 'shadowMin'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.7 NAME 'shadowMax'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.8 NAME 'shadowWarning'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.9 NAME 'shadowInactive'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.10 NAME 'shadowExpire'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.11 NAME 'shadowFlag'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.12 NAME 'memberUid'
|
||||
EQUALITY caseExactIA5Match
|
||||
SUBSTR caseExactIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.13 NAME 'memberNisNetgroup'
|
||||
EQUALITY caseExactIA5Match
|
||||
SUBSTR caseExactIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.14 NAME 'nisNetgroupTriple'
|
||||
DESC 'Netgroup triple'
|
||||
SYNTAX 1.3.6.1.1.1.0.0 )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.15 NAME 'ipServicePort'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.16 NAME 'ipServiceProtocol'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.17 NAME 'ipProtocolNumber'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.18 NAME 'oncRpcNumber'
|
||||
EQUALITY integerMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.19 NAME 'ipHostNumber'
|
||||
DESC 'IP address'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.20 NAME 'ipNetworkNumber'
|
||||
DESC 'IP network'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.21 NAME 'ipNetmaskNumber'
|
||||
DESC 'IP netmask'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} SINGLE-VALUE )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.22 NAME 'macAddress'
|
||||
DESC 'MAC address'
|
||||
EQUALITY caseIgnoreIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{128} )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.23 NAME 'bootParameter'
|
||||
DESC 'rpc.bootparamd parameter'
|
||||
SYNTAX 1.3.6.1.1.1.0.1 )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.24 NAME 'bootFile'
|
||||
DESC 'Boot image name'
|
||||
EQUALITY caseExactIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.26 NAME 'nisMapName'
|
||||
SUP name )
|
||||
|
||||
attributetype ( 1.3.6.1.1.1.1.27 NAME 'nisMapEntry'
|
||||
EQUALITY caseExactIA5Match
|
||||
SUBSTR caseExactIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26{1024} SINGLE-VALUE )
|
||||
|
||||
# Object Class Definitions
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.0 NAME 'posixAccount'
|
||||
DESC 'Abstraction of an account with POSIX attributes'
|
||||
SUP top AUXILIARY
|
||||
MUST ( cn $ uid $ uidNumber $ gidNumber $ homeDirectory )
|
||||
MAY ( userPassword $ loginShell $ gecos $ description ) )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.1 NAME 'shadowAccount'
|
||||
DESC 'Additional attributes for shadow passwords'
|
||||
SUP top AUXILIARY
|
||||
MUST uid
|
||||
MAY ( userPassword $ shadowLastChange $ shadowMin $
|
||||
shadowMax $ shadowWarning $ shadowInactive $
|
||||
shadowExpire $ shadowFlag $ description ) )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.2 NAME 'posixGroup'
|
||||
DESC 'Abstraction of a group of accounts'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( cn $ gidNumber )
|
||||
MAY ( userPassword $ memberUid $ description ) )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.3 NAME 'ipService'
|
||||
DESC 'Abstraction an Internet Protocol service'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( cn $ ipServicePort $ ipServiceProtocol )
|
||||
MAY ( description ) )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.4 NAME 'ipProtocol'
|
||||
DESC 'Abstraction of an IP protocol'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( cn $ ipProtocolNumber $ description )
|
||||
MAY description )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.5 NAME 'oncRpc'
|
||||
DESC 'Abstraction of an ONC/RPC binding'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( cn $ oncRpcNumber $ description )
|
||||
MAY description )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.6 NAME 'ipHost'
|
||||
DESC 'Abstraction of a host, an IP device'
|
||||
SUP top AUXILIARY
|
||||
MUST ( cn $ ipHostNumber )
|
||||
MAY ( l $ description $ manager ) )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.7 NAME 'ipNetwork'
|
||||
DESC 'Abstraction of an IP network'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( cn $ ipNetworkNumber )
|
||||
MAY ( ipNetmaskNumber $ l $ description $ manager ) )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.8 NAME 'nisNetgroup'
|
||||
DESC 'Abstraction of a netgroup'
|
||||
SUP top STRUCTURAL
|
||||
MUST cn
|
||||
MAY ( nisNetgroupTriple $ memberNisNetgroup $ description ) )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.9 NAME 'nisMap'
|
||||
DESC 'A generic abstraction of a NIS map'
|
||||
SUP top STRUCTURAL
|
||||
MUST nisMapName
|
||||
MAY description )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.10 NAME 'nisObject'
|
||||
DESC 'An entry in a NIS map'
|
||||
SUP top STRUCTURAL
|
||||
MUST ( cn $ nisMapEntry $ nisMapName )
|
||||
MAY description )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.11 NAME 'ieee802Device'
|
||||
DESC 'A device with a MAC address'
|
||||
SUP top AUXILIARY
|
||||
MAY macAddress )
|
||||
|
||||
objectclass ( 1.3.6.1.1.1.2.12 NAME 'bootableDevice'
|
||||
DESC 'A device with boot parameters'
|
||||
SUP top AUXILIARY
|
||||
MAY ( bootFile $ bootParameter ) )
|
|
@ -1,76 +0,0 @@
|
|||
#
|
||||
# OpenLDAP schema file for Sudo
|
||||
# Save as /etc/openldap/schema/sudo.schema
|
||||
#
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.1
|
||||
NAME 'sudoUser'
|
||||
DESC 'User(s) who may run sudo'
|
||||
EQUALITY caseExactIA5Match
|
||||
SUBSTR caseExactIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.2
|
||||
NAME 'sudoHost'
|
||||
DESC 'Host(s) who may run sudo'
|
||||
EQUALITY caseExactIA5Match
|
||||
SUBSTR caseExactIA5SubstringsMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.3
|
||||
NAME 'sudoCommand'
|
||||
DESC 'Command(s) to be executed by sudo'
|
||||
EQUALITY caseExactIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.4
|
||||
NAME 'sudoRunAs'
|
||||
DESC 'User(s) impersonated by sudo (deprecated)'
|
||||
EQUALITY caseExactIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.5
|
||||
NAME 'sudoOption'
|
||||
DESC 'Options(s) followed by sudo'
|
||||
EQUALITY caseExactIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.6
|
||||
NAME 'sudoRunAsUser'
|
||||
DESC 'User(s) impersonated by sudo'
|
||||
EQUALITY caseExactIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.7
|
||||
NAME 'sudoRunAsGroup'
|
||||
DESC 'Group(s) impersonated by sudo'
|
||||
EQUALITY caseExactIA5Match
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.8
|
||||
NAME 'sudoNotBefore'
|
||||
DESC 'Start of time interval for which the entry is valid'
|
||||
EQUALITY generalizedTimeMatch
|
||||
ORDERING generalizedTimeOrderingMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 )
|
||||
|
||||
attributetype ( 1.3.6.1.4.1.15953.9.1.9
|
||||
NAME 'sudoNotAfter'
|
||||
DESC 'End of time interval for which the entry is valid'
|
||||
EQUALITY generalizedTimeMatch
|
||||
ORDERING generalizedTimeOrderingMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 )
|
||||
|
||||
attributeTypes ( 1.3.6.1.4.1.15953.9.1.10
|
||||
NAME 'sudoOrder'
|
||||
DESC 'an integer to order the sudoRole entries'
|
||||
EQUALITY integerMatch
|
||||
ORDERING integerOrderingMatch
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 )
|
||||
|
||||
objectclass ( 1.3.6.1.4.1.15953.9.2.1 NAME 'sudoRole' SUP top STRUCTURAL
|
||||
DESC 'Sudoer Entries'
|
||||
MUST ( cn )
|
||||
MAY ( sudoUser $ sudoHost $ sudoCommand $ sudoRunAs $ sudoRunAsUser $ sudoRunAsGroup $ sudoOption $ sudoOrder $ sudoNotBefore $ sudoNotAfter $
|
||||
description )
|
||||
)
|
|
@ -1,33 +0,0 @@
|
|||
#dn: cn=yunohost,cn=schema,cn=config
|
||||
#objectClass: olcSchemaConfig
|
||||
#cn: yunohost
|
||||
# ATTRIBUTES
|
||||
# For Permission
|
||||
attributetype ( 1.3.6.1.4.1.17953.9.1.1 NAME 'permission'
|
||||
DESC 'Yunohost permission on user and group side'
|
||||
SUP distinguishedName )
|
||||
attributetype ( 1.3.6.1.4.1.17953.9.1.2 NAME 'groupPermission'
|
||||
DESC 'Yunohost permission for a group on permission side'
|
||||
SUP distinguishedName )
|
||||
attributetype ( 1.3.6.1.4.1.17953.9.1.3 NAME 'inheritPermission'
|
||||
DESC 'Yunohost permission for user on permission side'
|
||||
SUP distinguishedName )
|
||||
attributetype ( 1.3.6.1.4.1.17953.9.1.4 NAME 'URL'
|
||||
DESC 'Yunohost application URL'
|
||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{128} )
|
||||
# OBJECTCLASS
|
||||
# For Applications
|
||||
objectclass ( 1.3.6.1.4.1.17953.9.2.1 NAME 'groupOfNamesYnh'
|
||||
DESC 'Yunohost user group'
|
||||
SUP top AUXILIARY
|
||||
MAY ( member $ businessCategory $ seeAlso $ owner $ ou $ o $ permission ) )
|
||||
objectclass ( 1.3.6.1.4.1.17953.9.2.2 NAME 'permissionYnh'
|
||||
DESC 'a Yunohost application'
|
||||
SUP top AUXILIARY
|
||||
MUST cn
|
||||
MAY ( groupPermission $ inheritPermission $ URL ) )
|
||||
# For User
|
||||
objectclass ( 1.3.6.1.4.1.17953.9.2.3 NAME 'userPermissionYnh'
|
||||
DESC 'a Yunohost application'
|
||||
SUP top AUXILIARY
|
||||
MAY ( permission ) )
|
|
@ -1,94 +0,0 @@
|
|||
serverID %(serverid)s
|
||||
moduleload back_%(database)s
|
||||
moduleload memberof
|
||||
%(include_directives)s
|
||||
loglevel %(loglevel)s
|
||||
#allow bind_v2
|
||||
database %(database)s
|
||||
directory "%(directory)s"
|
||||
suffix "%(suffix)s"
|
||||
rootdn "%(rootdn)s"
|
||||
rootpw "%(rootpw)s"
|
||||
TLSCACertificateFile "%(cafile)s"
|
||||
TLSCertificateFile "%(servercert)s"
|
||||
TLSCertificateKeyFile "%(serverkey)s"
|
||||
authz-regexp
|
||||
"gidnumber=%(root_gid)s\\+uidnumber=%(root_uid)s,cn=peercred,cn=external,cn=auth"
|
||||
"%(rootdn)s"
|
||||
|
||||
index objectClass eq
|
||||
index uid,sudoUser eq,sub
|
||||
index entryCSN,entryUUID eq
|
||||
index cn,mail eq
|
||||
index gidNumber,uidNumber eq
|
||||
index member,memberUid,uniqueMember eq
|
||||
index virtualdomain eq
|
||||
|
||||
# The userPassword by default can be changed
|
||||
# by the entry owning it if they are authenticated.
|
||||
# Others should not be able to see it, except the
|
||||
# admin entry below
|
||||
# These access lines apply to database #1 only
|
||||
access to attrs=userPassword,shadowLastChange
|
||||
by dn="cn=admin,dc=yunohost,dc=org" write
|
||||
by dn.exact="gidNumber=%(root_gid)s+uidnumber=%(root_uid)s,cn=peercred,cn=external,cn=auth" write
|
||||
by anonymous auth
|
||||
by self write
|
||||
by * none
|
||||
|
||||
# Personnal information can be changed by the entry
|
||||
# owning it if they are authenticated.
|
||||
# Others should be able to see it.
|
||||
access to attrs=cn,gecos,givenName,mail,maildrop,displayName,sn
|
||||
by dn="cn=admin,dc=yunohost,dc=org" write
|
||||
by dn.exact="gidNumber=%(root_gid)s+uidnumber=%(root_uid)s,cn=peercred,cn=external,cn=auth" write
|
||||
by self write
|
||||
by * read
|
||||
|
||||
# Ensure read access to the base for things like
|
||||
# supportedSASLMechanisms. Without this you may
|
||||
# have problems with SASL not knowing what
|
||||
# mechanisms are available and the like.
|
||||
# Note that this is covered by the 'access to *'
|
||||
# ACL below too but if you change that as people
|
||||
# are wont to do you'll still need this if you
|
||||
# want SASL (and possible ldap_files things) to work
|
||||
# happily.
|
||||
access to dn.base="" by * read
|
||||
|
||||
# The admin dn has full write access, everyone else
|
||||
# can read everything.
|
||||
access to *
|
||||
by dn="cn=admin,dc=yunohost,dc=org" write
|
||||
by dn.exact="gidNumber=%(root_gid)s+uidnumber=%(root_uid)s,cn=peercred,cn=external,cn=auth" write
|
||||
by group/groupOfNames/Member="cn=admin,ou=groups,dc=yunohost,dc=org" write
|
||||
by * read
|
||||
|
||||
# Configure Memberof Overlay (used for Yunohost permission)
|
||||
|
||||
# Link user <-> group
|
||||
#dn: olcOverlay={0}memberof,olcDatabase={1}mdb,cn=config
|
||||
overlay memberof
|
||||
memberof-group-oc groupOfNamesYnh
|
||||
memberof-member-ad member
|
||||
memberof-memberof-ad memberOf
|
||||
memberof-dangling error
|
||||
memberof-refint TRUE
|
||||
|
||||
# Link permission <-> groupes
|
||||
#dn: olcOverlay={1}memberof,olcDatabase={1}mdb,cn=config
|
||||
overlay memberof
|
||||
memberof-group-oc permissionYnh
|
||||
memberof-member-ad groupPermission
|
||||
memberof-memberof-ad permission
|
||||
memberof-dangling error
|
||||
memberof-refint TRUE
|
||||
|
||||
# Link permission <-> user
|
||||
#dn: olcOverlay={2}memberof,olcDatabase={1}mdb,cn=config
|
||||
overlay memberof
|
||||
memberof-group-oc permissionYnh
|
||||
memberof-member-ad inheritPermission
|
||||
memberof-memberof-ad permission
|
||||
memberof-dangling error
|
||||
memberof-refint TRUE
|
|
@ -1,205 +0,0 @@
|
|||
dn: dc=yunohost,dc=org
|
||||
dc: yunohost
|
||||
o: yunohost.org
|
||||
objectclass: top
|
||||
objectclass: dcObject
|
||||
objectclass: organization
|
||||
|
||||
dn: cn=admin,dc=yunohost,dc=org
|
||||
objectClass: simpleSecurityObject
|
||||
objectClass: organizationalRole
|
||||
cn: admin
|
||||
userPassword: yunohost
|
||||
|
||||
#dn: ou=people,dc=yunohost,dc=org
|
||||
#objectClass: organizationalUnit
|
||||
#ou: people
|
||||
#
|
||||
#dn: ou=moregroups,dc=yunohost,dc=org
|
||||
#objectClass: organizationalUnit
|
||||
#ou: moregroups
|
||||
#
|
||||
#dn: ou=mirror_groups,dc=yunohost,dc=org
|
||||
#objectClass: organizationalUnit
|
||||
#ou: mirror_groups
|
||||
#
|
||||
#
|
||||
#dn: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#objectClass: person
|
||||
#objectClass: organizationalPerson
|
||||
#objectClass: inetOrgPerson
|
||||
#objectClass: posixAccount
|
||||
#cn: alice
|
||||
#uid: alice
|
||||
#userPassword: password
|
||||
#uidNumber: 1000
|
||||
#gidNumber: 1000
|
||||
#givenName: Alice
|
||||
#sn: Adams
|
||||
#homeDirectory: /home/alice
|
||||
#
|
||||
#dn: uid=bob,ou=people,dc=yunohost,dc=org
|
||||
#objectClass: person
|
||||
#objectClass: organizationalPerson
|
||||
#objectClass: inetOrgPerson
|
||||
#objectClass: posixAccount
|
||||
#cn: bob
|
||||
#uid: bob
|
||||
#userPassword: password
|
||||
#uidNumber: 1001
|
||||
#gidNumber: 50
|
||||
#givenName: Robert
|
||||
#sn: Barker
|
||||
#homeDirectory: /home/bob
|
||||
#
|
||||
#dn: uid=dreßler,ou=people,dc=yunohost,dc=org
|
||||
#objectClass: person
|
||||
#objectClass: organizationalPerson
|
||||
#objectClass: inetOrgPerson
|
||||
#objectClass: posixAccount
|
||||
#cn: dreßler
|
||||
#uid: dreßler
|
||||
#userPassword: password
|
||||
#uidNumber: 1002
|
||||
#gidNumber: 50
|
||||
#givenName: Wolfgang
|
||||
#sn: Dreßler
|
||||
#homeDirectory: /home/dressler
|
||||
#
|
||||
#dn: uid=nobody,ou=people,dc=yunohost,dc=org
|
||||
#objectClass: person
|
||||
#objectClass: organizationalPerson
|
||||
#objectClass: inetOrgPerson
|
||||
#objectClass: posixAccount
|
||||
#cn: nobody
|
||||
#uid: nobody
|
||||
#userPassword: password
|
||||
#uidNumber: 1003
|
||||
#gidNumber: 50
|
||||
#sn: nobody
|
||||
#homeDirectory: /home/nobody
|
||||
#
|
||||
#dn: uid=nonposix,ou=people,dc=yunohost,dc=org
|
||||
#objectClass: person
|
||||
#objectClass: organizationalPerson
|
||||
#objectClass: inetOrgPerson
|
||||
#cn: nonposix
|
||||
#uid: nonposix
|
||||
#userPassword: password
|
||||
#sn: nonposix
|
||||
#
|
||||
#
|
||||
## posixGroup objects
|
||||
#dn: cn=active_px,ou=moregroups,dc=yunohost,dc=org
|
||||
#objectClass: posixGroup
|
||||
#cn: active_px
|
||||
#gidNumber: 1000
|
||||
#memberUid: nonposix
|
||||
#
|
||||
#dn: cn=staff_px,ou=moregroups,dc=yunohost,dc=org
|
||||
#objectClass: posixGroup
|
||||
#cn: staff_px
|
||||
#gidNumber: 1001
|
||||
#memberUid: alice
|
||||
#memberUid: nonposix
|
||||
#
|
||||
#dn: cn=superuser_px,ou=moregroups,dc=yunohost,dc=org
|
||||
#objectClass: posixGroup
|
||||
#cn: superuser_px
|
||||
#gidNumber: 1002
|
||||
#memberUid: alice
|
||||
#memberUid: nonposix
|
||||
#
|
||||
#
|
||||
## groupOfNames groups
|
||||
#dn: cn=empty_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#cn: empty_gon
|
||||
#objectClass: groupOfNames
|
||||
#member:
|
||||
#
|
||||
#dn: cn=active_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#cn: active_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=staff_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#cn: staff_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=superuser_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#cn: superuser_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=other_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#cn: other_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=bob,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#
|
||||
## groupOfNames objects for LDAPGroupQuery testing
|
||||
#dn: ou=query_groups,dc=yunohost,dc=org
|
||||
#objectClass: organizationalUnit
|
||||
#ou: query_groups
|
||||
#
|
||||
#dn: cn=alice_gon,ou=query_groups,dc=yunohost,dc=org
|
||||
#cn: alice_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=mutual_gon,ou=query_groups,dc=yunohost,dc=org
|
||||
#cn: mutual_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#member: uid=bob,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=bob_gon,ou=query_groups,dc=yunohost,dc=org
|
||||
#cn: bob_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=bob,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=dreßler_gon,ou=query_groups,dc=yunohost,dc=org
|
||||
#cn: dreßler_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=dreßler,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#
|
||||
## groupOfNames objects for selective group mirroring.
|
||||
#dn: cn=mirror1,ou=mirror_groups,dc=yunohost,dc=org
|
||||
#cn: mirror1
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=mirror2,ou=mirror_groups,dc=yunohost,dc=org
|
||||
#cn: mirror2
|
||||
#objectClass: groupOfNames
|
||||
#member:
|
||||
#
|
||||
#dn: cn=mirror3,ou=mirror_groups,dc=yunohost,dc=org
|
||||
#cn: mirror3
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=mirror4,ou=mirror_groups,dc=yunohost,dc=org
|
||||
#cn: mirror4
|
||||
#objectClass: groupOfNames
|
||||
#member:
|
||||
#
|
||||
#
|
||||
## Nested groups with a circular reference
|
||||
#dn: cn=parent_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#cn: parent_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: cn=nested_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: CN=nested_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#cn: nested_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: uid=alice,ou=people,dc=yunohost,dc=org
|
||||
#member: cn=circular_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#
|
||||
#dn: cn=circular_gon,ou=moregroups,dc=yunohost,dc=org
|
||||
#cn: circular_gon
|
||||
#objectClass: groupOfNames
|
||||
#member: cn=parent_gon,ou=moregroups,dc=yunohost,dc=org
|
26
test/src/authenticators/dummy.py
Normal file
26
test/src/authenticators/dummy.py
Normal file
|
@ -0,0 +1,26 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
from moulinette.core import MoulinetteError
|
||||
from moulinette.authentication import BaseAuthenticator
|
||||
|
||||
logger = logging.getLogger("moulinette.authenticator.dummy")
|
||||
|
||||
# Dummy authenticator implementation
|
||||
|
||||
|
||||
class Authenticator(BaseAuthenticator):
|
||||
|
||||
"""Dummy authenticator used for tests"""
|
||||
|
||||
name = "dummy"
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def _authenticate_credentials(self, credentials=None):
|
||||
|
||||
if not credentials == self.name:
|
||||
raise MoulinetteError("invalid_password")
|
||||
|
||||
return
|
26
test/src/authenticators/yoloswag.py
Normal file
26
test/src/authenticators/yoloswag.py
Normal file
|
@ -0,0 +1,26 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
from moulinette.core import MoulinetteError
|
||||
from moulinette.authentication import BaseAuthenticator
|
||||
|
||||
logger = logging.getLogger("moulinette.authenticator.yoloswag")
|
||||
|
||||
# Dummy authenticator implementation
|
||||
|
||||
|
||||
class Authenticator(BaseAuthenticator):
|
||||
|
||||
"""Dummy authenticator used for tests"""
|
||||
|
||||
name = "yoloswag"
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def _authenticate_credentials(self, credentials=None):
|
||||
|
||||
if not credentials == self.name:
|
||||
raise MoulinetteError("invalid_password")
|
||||
|
||||
return
|
|
@ -1,122 +0,0 @@
|
|||
import slapdtest
|
||||
import os
|
||||
from moulinette.authenticators import ldap as m_ldap
|
||||
|
||||
HERE = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
|
||||
class LDAPServer:
|
||||
def __init__(self):
|
||||
self.server_default = slapdtest.SlapdObject()
|
||||
with open(
|
||||
os.path.join(HERE, "..", "ldap_files", "slapd.conf.template"),
|
||||
encoding="utf-8",
|
||||
) as f:
|
||||
SLAPD_CONF_TEMPLATE = f.read()
|
||||
self.server_default.slapd_conf_template = SLAPD_CONF_TEMPLATE
|
||||
self.server_default.suffix = "dc=yunohost,dc=org"
|
||||
self.server_default.root_cn = "admin"
|
||||
self.server_default.SCHEMADIR = os.path.join(HERE, "..", "ldap_files", "schema")
|
||||
self.server_default.openldap_schema_files = [
|
||||
"core.schema",
|
||||
"cosine.schema",
|
||||
"nis.schema",
|
||||
"inetorgperson.schema",
|
||||
"sudo.schema",
|
||||
"yunohost.schema",
|
||||
"mailserver.schema",
|
||||
]
|
||||
self.server = None
|
||||
self.uri = ""
|
||||
|
||||
def start(self):
|
||||
self.server = self.server_default
|
||||
self.server.start()
|
||||
self.uri = self.server.ldapi_uri
|
||||
with open(
|
||||
os.path.join(HERE, "..", "ldap_files", "tests.ldif"), encoding="utf-8"
|
||||
) as fp:
|
||||
ldif = fp.read()
|
||||
self.server.ldapadd(ldif)
|
||||
self.tools_ldapinit()
|
||||
|
||||
def stop(self):
|
||||
if self.server:
|
||||
self.server.stop()
|
||||
|
||||
def __del__(self):
|
||||
if self.server:
|
||||
self.server.stop()
|
||||
|
||||
def tools_ldapinit(self):
|
||||
"""
|
||||
YunoHost LDAP initialization
|
||||
|
||||
|
||||
"""
|
||||
import yaml
|
||||
|
||||
with open(os.path.join(HERE, "..", "ldap_files", "ldap_scheme.yml"), "rb") as f:
|
||||
ldap_map = yaml.safe_load(f)
|
||||
|
||||
def _get_ldap_interface():
|
||||
conf = {
|
||||
"vendor": "ldap",
|
||||
"name": "as-root",
|
||||
"parameters": {
|
||||
"uri": self.server.ldapi_uri,
|
||||
"base_dn": "dc=yunohost,dc=org",
|
||||
"user_rdn": "gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
|
||||
% (os.getgid(), os.getuid()),
|
||||
},
|
||||
"extra": {},
|
||||
}
|
||||
|
||||
_ldap_interface = m_ldap.Authenticator(**conf)
|
||||
|
||||
return _ldap_interface
|
||||
|
||||
ldap_interface = _get_ldap_interface()
|
||||
|
||||
for rdn, attr_dict in ldap_map["parents"].items():
|
||||
ldap_interface.add(rdn, attr_dict)
|
||||
|
||||
for rdn, attr_dict in ldap_map["children"].items():
|
||||
ldap_interface.add(rdn, attr_dict)
|
||||
|
||||
for rdn, attr_dict in ldap_map["depends_children"].items():
|
||||
ldap_interface.add(rdn, attr_dict)
|
||||
|
||||
admin_dict = {
|
||||
"cn": ["admin"],
|
||||
"uid": ["admin"],
|
||||
"description": ["LDAP Administrator"],
|
||||
"gidNumber": ["1007"],
|
||||
"uidNumber": ["1007"],
|
||||
"homeDirectory": ["/home/admin"],
|
||||
"loginShell": ["/bin/bash"],
|
||||
"objectClass": [
|
||||
"organizationalRole",
|
||||
"posixAccount",
|
||||
"simpleSecurityObject",
|
||||
],
|
||||
"userPassword": [self._hash_user_password("yunohost")],
|
||||
}
|
||||
|
||||
ldap_interface.update("cn=admin", admin_dict)
|
||||
|
||||
def _hash_user_password(self, password):
|
||||
"""
|
||||
Copy pasta of what's in yunohost/user.py
|
||||
"""
|
||||
import string
|
||||
import random
|
||||
import crypt
|
||||
|
||||
char_set = (
|
||||
string.ascii_uppercase + string.ascii_lowercase + string.digits + "./"
|
||||
)
|
||||
salt = "".join([random.SystemRandom().choice(char_set) for x in range(16)])
|
||||
|
||||
salt = "$6$" + salt + "$"
|
||||
return "{CRYPT}" + crypt.crypt(str(password), salt)
|
|
@ -34,10 +34,6 @@ def testauth_only_cli():
|
|||
return "some_data_from_only_cli"
|
||||
|
||||
|
||||
def testauth_ldap():
|
||||
return "some_data_from_ldap"
|
||||
|
||||
|
||||
def testauth_with_arg(super_arg):
|
||||
return super_arg
|
||||
|
||||
|
|
|
@ -10,15 +10,18 @@ from moulinette.actionsmap import (
|
|||
ActionsMap,
|
||||
)
|
||||
|
||||
from moulinette.interfaces import GLOBAL_SECTION
|
||||
from moulinette.interfaces import BaseActionsMapParser
|
||||
from moulinette.core import MoulinetteError
|
||||
from moulinette import m18n
|
||||
from moulinette import m18n, Moulinette
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def iface():
|
||||
return "iface"
|
||||
class DummyInterface:
|
||||
|
||||
def prompt():
|
||||
pass
|
||||
|
||||
return DummyInterface()
|
||||
|
||||
|
||||
def test_comment_parameter_bad_bool_value(iface, caplog):
|
||||
|
@ -68,10 +71,11 @@ def test_ask_parameter(iface, mocker):
|
|||
arg = ask("foobar", "a", "a")
|
||||
assert arg == "a"
|
||||
|
||||
from moulinette.core import Moulinette18n, MoulinetteSignals
|
||||
from moulinette.core import Moulinette18n
|
||||
|
||||
Moulinette._interface = iface
|
||||
mocker.patch.object(Moulinette18n, "n", return_value="awesome_test")
|
||||
mocker.patch.object(MoulinetteSignals, "prompt", return_value="awesome_test")
|
||||
mocker.patch.object(iface, "prompt", return_value="awesome_test")
|
||||
arg = ask("foobar", "a", None)
|
||||
assert arg == "awesome_test"
|
||||
|
||||
|
@ -81,10 +85,11 @@ def test_password_parameter(iface, mocker):
|
|||
arg = ask("foobar", "a", "a")
|
||||
assert arg == "a"
|
||||
|
||||
from moulinette.core import Moulinette18n, MoulinetteSignals
|
||||
from moulinette.core import Moulinette18n
|
||||
|
||||
Moulinette._interface = iface
|
||||
mocker.patch.object(Moulinette18n, "n", return_value="awesome_test")
|
||||
mocker.patch.object(MoulinetteSignals, "prompt", return_value="awesome_test")
|
||||
mocker.patch.object(iface, "prompt", return_value="awesome_test")
|
||||
arg = ask("foobar", "a", None)
|
||||
assert arg == "awesome_test"
|
||||
|
||||
|
@ -157,14 +162,13 @@ def test_required_paremeter_missing_value(iface, caplog):
|
|||
|
||||
|
||||
def test_actions_map_unknown_authenticator(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("MOULINETTE_DATA_DIR", str(tmp_path))
|
||||
actionsmap_dir = tmp_path / "actionsmap"
|
||||
actionsmap_dir.mkdir()
|
||||
|
||||
amap = ActionsMap(BaseActionsMapParser())
|
||||
with pytest.raises(ValueError) as exception:
|
||||
amap.get_authenticator_for_profile("unknown")
|
||||
assert "Unknown authenticator" in str(exception)
|
||||
from moulinette.interfaces.api import ActionsMapParser
|
||||
amap = ActionsMap(ActionsMapParser())
|
||||
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
amap.get_authenticator("unknown")
|
||||
assert "No module named" in str(exception)
|
||||
|
||||
|
||||
def test_extra_argument_parser_add_argument(iface):
|
||||
|
@ -176,17 +180,17 @@ def test_extra_argument_parser_add_argument(iface):
|
|||
assert extra_argument_parse._extra_params["Test"]["foo"]["ask"] == "lol"
|
||||
|
||||
extra_argument_parse = ExtraArgumentParser(iface)
|
||||
extra_argument_parse.add_argument(GLOBAL_SECTION, "foo", {"ask": "lol"})
|
||||
assert GLOBAL_SECTION in extra_argument_parse._extra_params
|
||||
assert "foo" in extra_argument_parse._extra_params[GLOBAL_SECTION]
|
||||
assert "ask" in extra_argument_parse._extra_params[GLOBAL_SECTION]["foo"]
|
||||
assert extra_argument_parse._extra_params[GLOBAL_SECTION]["foo"]["ask"] == "lol"
|
||||
extra_argument_parse.add_argument("_global", "foo", {"ask": "lol"})
|
||||
assert "_global" in extra_argument_parse._extra_params
|
||||
assert "foo" in extra_argument_parse._extra_params["_global"]
|
||||
assert "ask" in extra_argument_parse._extra_params["_global"]["foo"]
|
||||
assert extra_argument_parse._extra_params["_global"]["foo"]["ask"] == "lol"
|
||||
|
||||
|
||||
def test_extra_argument_parser_add_argument_bad_arg(iface):
|
||||
extra_argument_parse = ExtraArgumentParser(iface)
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
extra_argument_parse.add_argument(GLOBAL_SECTION, "foo", {"ask": 1})
|
||||
extra_argument_parse.add_argument("_global", "foo", {"ask": 1})
|
||||
|
||||
expected_msg = "unable to validate extra parameter '%s' for argument '%s': %s" % (
|
||||
"ask",
|
||||
|
@ -196,23 +200,23 @@ def test_extra_argument_parser_add_argument_bad_arg(iface):
|
|||
assert expected_msg in str(exception)
|
||||
|
||||
extra_argument_parse = ExtraArgumentParser(iface)
|
||||
extra_argument_parse.add_argument(GLOBAL_SECTION, "foo", {"error": 1})
|
||||
extra_argument_parse.add_argument("_global", "foo", {"error": 1})
|
||||
|
||||
assert GLOBAL_SECTION in extra_argument_parse._extra_params
|
||||
assert "foo" in extra_argument_parse._extra_params[GLOBAL_SECTION]
|
||||
assert not len(extra_argument_parse._extra_params[GLOBAL_SECTION]["foo"])
|
||||
assert "_global" in extra_argument_parse._extra_params
|
||||
assert "foo" in extra_argument_parse._extra_params["_global"]
|
||||
assert not len(extra_argument_parse._extra_params["_global"]["foo"])
|
||||
|
||||
|
||||
def test_extra_argument_parser_parse_args(iface, mocker):
|
||||
extra_argument_parse = ExtraArgumentParser(iface)
|
||||
extra_argument_parse.add_argument(GLOBAL_SECTION, "foo", {"ask": "lol"})
|
||||
extra_argument_parse.add_argument(GLOBAL_SECTION, "foo2", {"ask": "lol2"})
|
||||
extra_argument_parse.add_argument("_global", "foo", {"ask": "lol"})
|
||||
extra_argument_parse.add_argument("_global", "foo2", {"ask": "lol2"})
|
||||
extra_argument_parse.add_argument(
|
||||
GLOBAL_SECTION, "bar", {"password": "lul", "ask": "lul"}
|
||||
"_global", "bar", {"password": "lul", "ask": "lul"}
|
||||
)
|
||||
|
||||
args = extra_argument_parse.parse_args(
|
||||
GLOBAL_SECTION, {"foo": 1, "foo2": ["a", "b", {"foobar": True}], "bar": "rab"}
|
||||
"_global", {"foo": 1, "foo2": ["a", "b", {"foobar": True}], "bar": "rab"}
|
||||
)
|
||||
|
||||
assert "foo" in args
|
||||
|
@ -228,24 +232,32 @@ def test_extra_argument_parser_parse_args(iface, mocker):
|
|||
def test_actions_map_api():
|
||||
from moulinette.interfaces.api import ActionsMapParser
|
||||
|
||||
amap = ActionsMap(ActionsMapParser())
|
||||
parser = ActionsMapParser()
|
||||
amap = ActionsMap(parser)
|
||||
|
||||
assert amap.parser.global_conf["authenticate"] == "all"
|
||||
assert "default" in amap.parser.global_conf["authenticator"]
|
||||
assert "yoloswag" in amap.parser.global_conf["authenticator"]
|
||||
assert amap.main_namespace == "moulitest"
|
||||
assert amap.default_authentication == "dummy"
|
||||
assert ("GET", "/test-auth/default") in amap.parser.routes
|
||||
assert ("POST", "/test-auth/subcat/post") in amap.parser.routes
|
||||
|
||||
assert parser.auth_method(None, ("GET", "/test-auth/default")) == "dummy"
|
||||
assert parser.auth_method(None, ("GET", "/test-auth/only-api")) == "dummy"
|
||||
assert parser.auth_method(None, ("GET", "/test-auth/only-cli")) is None
|
||||
|
||||
amap.generate_cache("moulitest")
|
||||
|
||||
amap = ActionsMap(ActionsMapParser())
|
||||
parser = ActionsMapParser()
|
||||
amap = ActionsMap(parser)
|
||||
|
||||
assert amap.parser.global_conf["authenticate"] == "all"
|
||||
assert "default" in amap.parser.global_conf["authenticator"]
|
||||
assert "yoloswag" in amap.parser.global_conf["authenticator"]
|
||||
assert amap.main_namespace == "moulitest"
|
||||
assert amap.default_authentication == "dummy"
|
||||
assert ("GET", "/test-auth/default") in amap.parser.routes
|
||||
assert ("POST", "/test-auth/subcat/post") in amap.parser.routes
|
||||
|
||||
assert parser.auth_method(None, ("GET", "/test-auth/default")) == "dummy"
|
||||
assert parser.auth_method(None, ("GET", "/test-auth/only-api")) == "dummy"
|
||||
assert parser.auth_method(None, ("GET", "/test-auth/only-cli")) is None
|
||||
|
||||
|
||||
def test_actions_map_import_error(mocker):
|
||||
from moulinette.interfaces.api import ActionsMapParser
|
||||
|
@ -280,18 +292,19 @@ def test_actions_map_cli():
|
|||
from moulinette.interfaces.cli import ActionsMapParser
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(add_help=False)
|
||||
parser.add_argument(
|
||||
top_parser = argparse.ArgumentParser(add_help=False)
|
||||
top_parser.add_argument(
|
||||
"--debug",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Log and print debug messages",
|
||||
)
|
||||
amap = ActionsMap(ActionsMapParser(top_parser=parser))
|
||||
|
||||
assert amap.parser.global_conf["authenticate"] == "all"
|
||||
assert "default" in amap.parser.global_conf["authenticator"]
|
||||
assert "yoloswag" in amap.parser.global_conf["authenticator"]
|
||||
parser = ActionsMapParser(top_parser=top_parser)
|
||||
amap = ActionsMap(parser)
|
||||
|
||||
assert amap.main_namespace == "moulitest"
|
||||
assert amap.default_authentication == "dummy"
|
||||
assert "testauth" in amap.parser._subparsers.choices
|
||||
assert "none" in amap.parser._subparsers.choices["testauth"]._actions[1].choices
|
||||
assert "subcat" in amap.parser._subparsers.choices["testauth"]._actions[1].choices
|
||||
|
@ -304,13 +317,17 @@ def test_actions_map_cli():
|
|||
.choices
|
||||
)
|
||||
|
||||
assert parser.auth_method(["testauth", "default"]) == "dummy"
|
||||
assert parser.auth_method(["testauth", "only-api"]) is None
|
||||
assert parser.auth_method(["testauth", "only-cli"]) == "dummy"
|
||||
|
||||
amap.generate_cache("moulitest")
|
||||
|
||||
amap = ActionsMap(ActionsMapParser(top_parser=parser))
|
||||
parser = ActionsMapParser(top_parser=top_parser)
|
||||
amap = ActionsMap(parser)
|
||||
|
||||
assert amap.parser.global_conf["authenticate"] == "all"
|
||||
assert "default" in amap.parser.global_conf["authenticator"]
|
||||
assert "yoloswag" in amap.parser.global_conf["authenticator"]
|
||||
assert amap.main_namespace == "moulitest"
|
||||
assert amap.default_authentication == "dummy"
|
||||
assert "testauth" in amap.parser._subparsers.choices
|
||||
assert "none" in amap.parser._subparsers.choices["testauth"]._actions[1].choices
|
||||
assert "subcat" in amap.parser._subparsers.choices["testauth"]._actions[1].choices
|
||||
|
@ -322,3 +339,7 @@ def test_actions_map_cli():
|
|||
._actions[1]
|
||||
.choices
|
||||
)
|
||||
|
||||
assert parser.auth_method(["testauth", "default"]) == "dummy"
|
||||
assert parser.auth_method(["testauth", "only-api"]) is None
|
||||
assert parser.auth_method(["testauth", "only-cli"]) == "dummy"
|
||||
|
|
|
@ -6,8 +6,12 @@ from moulinette import m18n
|
|||
|
||||
|
||||
class TestAuthAPI:
|
||||
def login(self, webapi, csrf=False, profile=None, status=200, password="default"):
|
||||
data = {"password": password}
|
||||
def login(self, webapi, csrf=False, profile=None, status=200, password=None):
|
||||
if password is None:
|
||||
password = "dummy"
|
||||
|
||||
data = {"credentials": password}
|
||||
|
||||
if profile:
|
||||
data["profile"] = profile
|
||||
|
||||
|
@ -64,13 +68,7 @@ class TestAuthAPI:
|
|||
def test_login(self, moulinette_webapi):
|
||||
assert self.login(moulinette_webapi).text == "Logged in"
|
||||
|
||||
assert "session.id" in moulinette_webapi.cookies
|
||||
assert "session.tokens" in moulinette_webapi.cookies
|
||||
|
||||
cache_session_default = os.environ["MOULINETTE_CACHE_DIR"] + "/session/default/"
|
||||
assert moulinette_webapi.cookies["session.id"] + ".asc" in os.listdir(
|
||||
cache_session_default
|
||||
)
|
||||
assert "session.moulitest" in moulinette_webapi.cookies
|
||||
|
||||
def test_login_bad_password(self, moulinette_webapi):
|
||||
assert (
|
||||
|
@ -78,8 +76,7 @@ class TestAuthAPI:
|
|||
== "Invalid password"
|
||||
)
|
||||
|
||||
assert "session.id" not in moulinette_webapi.cookies
|
||||
assert "session.tokens" not in moulinette_webapi.cookies
|
||||
assert "session.moulitest" not in moulinette_webapi.cookies
|
||||
|
||||
def test_login_csrf_attempt(self, moulinette_webapi):
|
||||
# C.f.
|
||||
|
@ -90,8 +87,7 @@ class TestAuthAPI:
|
|||
"CSRF protection"
|
||||
in self.login(moulinette_webapi, csrf=True, status=403).text
|
||||
)
|
||||
assert not any(c.name == "session.id" for c in moulinette_webapi.cookiejar)
|
||||
assert not any(c.name == "session.tokens" for c in moulinette_webapi.cookiejar)
|
||||
assert not any(c.name == "session.moulitest" for c in moulinette_webapi.cookiejar)
|
||||
|
||||
def test_login_then_legit_request_without_cookies(self, moulinette_webapi):
|
||||
self.login(moulinette_webapi)
|
||||
|
@ -103,6 +99,8 @@ class TestAuthAPI:
|
|||
def test_login_then_legit_request(self, moulinette_webapi):
|
||||
self.login(moulinette_webapi)
|
||||
|
||||
assert "session.moulitest" in moulinette_webapi.cookies
|
||||
|
||||
assert (
|
||||
moulinette_webapi.get("/test-auth/default", status=200).text
|
||||
== '"some_data_from_default"'
|
||||
|
@ -118,11 +116,6 @@ class TestAuthAPI:
|
|||
|
||||
moulinette_webapi.get("/logout", status=200)
|
||||
|
||||
cache_session_default = os.environ["MOULINETTE_CACHE_DIR"] + "/session/default/"
|
||||
assert not moulinette_webapi.cookies["session.id"] + ".asc" in os.listdir(
|
||||
cache_session_default
|
||||
)
|
||||
|
||||
assert (
|
||||
moulinette_webapi.get("/test-auth/default", status=401).text
|
||||
== "Authentication required"
|
||||
|
@ -131,15 +124,7 @@ class TestAuthAPI:
|
|||
def test_login_other_profile(self, moulinette_webapi):
|
||||
self.login(moulinette_webapi, profile="yoloswag", password="yoloswag")
|
||||
|
||||
assert "session.id" in moulinette_webapi.cookies
|
||||
assert "session.tokens" in moulinette_webapi.cookies
|
||||
|
||||
cache_session_default = (
|
||||
os.environ["MOULINETTE_CACHE_DIR"] + "/session/yoloswag/"
|
||||
)
|
||||
assert moulinette_webapi.cookies["session.id"] + ".asc" in os.listdir(
|
||||
cache_session_default
|
||||
)
|
||||
assert "session.moulitest" in moulinette_webapi.cookies
|
||||
|
||||
def test_login_wrong_profile(self, moulinette_webapi):
|
||||
self.login(moulinette_webapi)
|
||||
|
@ -158,21 +143,6 @@ class TestAuthAPI:
|
|||
== "Authentication required"
|
||||
)
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_login_ldap(self, moulinette_webapi, ldap_server, mocker):
|
||||
mocker.patch(
|
||||
"moulinette.authenticators.ldap.Authenticator._get_uri",
|
||||
return_value=ldap_server.uri,
|
||||
)
|
||||
self.login(moulinette_webapi, profile="ldap", password="yunohost")
|
||||
|
||||
assert (
|
||||
moulinette_webapi.get("/test-auth/ldap", status=200).text
|
||||
== '"some_data_from_ldap"'
|
||||
)
|
||||
|
||||
def test_request_with_arg(self, moulinette_webapi, capsys):
|
||||
self.login(moulinette_webapi)
|
||||
|
||||
|
@ -217,7 +187,8 @@ class TestAuthAPI:
|
|||
|
||||
class TestAuthCLI:
|
||||
def test_login(self, moulinette_cli, capsys, mocker):
|
||||
mocker.patch("getpass.getpass", return_value="default")
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="dummy")
|
||||
moulinette_cli.run(["testauth", "default"], output_as="plain")
|
||||
message = capsys.readouterr()
|
||||
|
||||
|
@ -229,16 +200,19 @@ class TestAuthCLI:
|
|||
assert "some_data_from_default" in message.out
|
||||
|
||||
def test_login_bad_password(self, moulinette_cli, capsys, mocker):
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="Bad Password")
|
||||
with pytest.raises(MoulinetteError):
|
||||
moulinette_cli.run(["testauth", "default"], output_as="plain")
|
||||
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="Bad Password")
|
||||
with pytest.raises(MoulinetteError):
|
||||
moulinette_cli.run(["testauth", "default"], output_as="plain")
|
||||
|
||||
def test_login_wrong_profile(self, moulinette_cli, mocker):
|
||||
mocker.patch("getpass.getpass", return_value="default")
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="dummy")
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
moulinette_cli.run(["testauth", "other-profile"], output_as="none")
|
||||
|
||||
|
@ -246,6 +220,7 @@ class TestAuthCLI:
|
|||
expected_msg = translation.format()
|
||||
assert expected_msg in str(exception)
|
||||
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="yoloswag")
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
moulinette_cli.run(["testauth", "default"], output_as="none")
|
||||
|
@ -266,7 +241,8 @@ class TestAuthCLI:
|
|||
assert "some_data_from_only_api" in message.out
|
||||
|
||||
def test_request_only_cli(self, capsys, moulinette_cli, mocker):
|
||||
mocker.patch("getpass.getpass", return_value="default")
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="dummy")
|
||||
moulinette_cli.run(["testauth", "only-cli"], output_as="plain")
|
||||
|
||||
message = capsys.readouterr()
|
||||
|
@ -274,6 +250,7 @@ class TestAuthCLI:
|
|||
assert "some_data_from_only_cli" in message.out
|
||||
|
||||
def test_request_not_logged_only_cli(self, capsys, moulinette_cli, mocker):
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass")
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
moulinette_cli.run(["testauth", "only-cli"], output_as="plain")
|
||||
|
@ -286,7 +263,8 @@ class TestAuthCLI:
|
|||
assert expected_msg in str(exception)
|
||||
|
||||
def test_request_with_callback(self, moulinette_cli, capsys, mocker):
|
||||
mocker.patch("getpass.getpass", return_value="default")
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="dummy")
|
||||
moulinette_cli.run(["--version"], output_as="plain")
|
||||
message = capsys.readouterr()
|
||||
|
||||
|
@ -304,14 +282,16 @@ class TestAuthCLI:
|
|||
assert "cannot get value from callback method" in message.err
|
||||
|
||||
def test_request_with_arg(self, moulinette_cli, capsys, mocker):
|
||||
mocker.patch("getpass.getpass", return_value="default")
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="dummy")
|
||||
moulinette_cli.run(["testauth", "with_arg", "yoloswag"], output_as="plain")
|
||||
message = capsys.readouterr()
|
||||
|
||||
assert "yoloswag" in message.out
|
||||
|
||||
def test_request_arg_with_extra(self, moulinette_cli, capsys, mocker):
|
||||
mocker.patch("getpass.getpass", return_value="default")
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="dummy")
|
||||
moulinette_cli.run(
|
||||
["testauth", "with_extra_str_only", "YoLoSwAg"], output_as="plain"
|
||||
)
|
||||
|
@ -330,7 +310,8 @@ class TestAuthCLI:
|
|||
assert "doesn't match pattern" in message.err
|
||||
|
||||
def test_request_arg_with_type(self, moulinette_cli, capsys, mocker):
|
||||
mocker.patch("getpass.getpass", return_value="default")
|
||||
mocker.patch("os.isatty", return_value=True)
|
||||
mocker.patch("getpass.getpass", return_value="dummy")
|
||||
moulinette_cli.run(["testauth", "with_type_int", "12345"], output_as="plain")
|
||||
message = capsys.readouterr()
|
||||
|
||||
|
|
|
@ -12,7 +12,6 @@ from moulinette.utils.filesystem import (
|
|||
read_json,
|
||||
read_yaml,
|
||||
read_toml,
|
||||
read_ldif,
|
||||
rm,
|
||||
write_to_file,
|
||||
write_to_json,
|
||||
|
@ -117,46 +116,6 @@ def test_read_toml_cannot_read(test_toml, mocker):
|
|||
assert expected_msg in str(exception)
|
||||
|
||||
|
||||
def test_read_ldif(test_ldif):
|
||||
dn, entry = read_ldif(str(test_ldif))[0]
|
||||
|
||||
assert dn == "mail=alice@example.com"
|
||||
assert entry["mail"] == ["alice@example.com".encode("utf-8")]
|
||||
assert entry["objectclass"] == ["top".encode("utf-8"), "person".encode("utf-8")]
|
||||
assert entry["cn"] == ["Alice Alison".encode("utf-8")]
|
||||
|
||||
dn, entry = read_ldif(str(test_ldif), ["objectclass"])[0]
|
||||
|
||||
assert dn == "mail=alice@example.com"
|
||||
assert entry["mail"] == ["alice@example.com".encode("utf-8")]
|
||||
assert "objectclass" not in entry
|
||||
assert entry["cn"] == ["Alice Alison".encode("utf-8")]
|
||||
|
||||
|
||||
def test_read_ldif_cannot_ioerror(test_ldif, mocker):
|
||||
error = "foobar"
|
||||
|
||||
mocker.patch("builtins.open", side_effect=IOError(error))
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
read_ldif(str(test_ldif))
|
||||
|
||||
translation = m18n.g("cannot_open_file", file=str(test_ldif), error=error)
|
||||
expected_msg = translation.format(file=str(test_ldif), error=error)
|
||||
assert expected_msg in str(exception)
|
||||
|
||||
|
||||
def test_read_ldif_cannot_exception(test_ldif, mocker):
|
||||
error = "foobar"
|
||||
|
||||
mocker.patch("builtins.open", side_effect=Exception(error))
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
read_ldif(str(test_ldif))
|
||||
|
||||
translation = m18n.g("unknown_error_reading_file", file=str(test_ldif), error=error)
|
||||
expected_msg = translation.format(file=str(test_ldif), error=error)
|
||||
assert expected_msg in str(exception)
|
||||
|
||||
|
||||
def test_write_to_existing_file(test_file):
|
||||
write_to_file(str(test_file), "yolo\nswag")
|
||||
assert read_file(str(test_file)) == "yolo\nswag"
|
||||
|
|
|
@ -1,486 +0,0 @@
|
|||
import pytest
|
||||
import os
|
||||
|
||||
from moulinette.authenticators import ldap as m_ldap
|
||||
from moulinette import m18n
|
||||
from moulinette.core import MoulinetteError
|
||||
|
||||
|
||||
class TestLDAP:
|
||||
def setup_method(self):
|
||||
self.ldap_conf = {
|
||||
"vendor": "ldap",
|
||||
"name": "as-root",
|
||||
"parameters": {"base_dn": "dc=yunohost,dc=org"},
|
||||
"extra": {},
|
||||
}
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_authenticate_simple_bind_with_admin(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
self.ldap_conf["parameters"]["user_rdn"] = "cn=admin,dc=yunohost,dc=org"
|
||||
ldap_interface = m_ldap.Authenticator(**self.ldap_conf)
|
||||
ldap_interface.authenticate(password="yunohost")
|
||||
|
||||
assert ldap_interface.con
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_authenticate_simple_bind_with_wrong_user(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
self.ldap_conf["parameters"]["user_rdn"] = "cn=yoloswag,dc=yunohost,dc=org"
|
||||
ldap_interface = m_ldap.Authenticator(**self.ldap_conf)
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
ldap_interface.authenticate(password="yunohost")
|
||||
|
||||
translation = m18n.g("invalid_password")
|
||||
expected_msg = translation.format()
|
||||
assert expected_msg in str(exception)
|
||||
assert ldap_interface.con is None
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_authenticate_simple_bind_with_rdn_wrong_password(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
self.ldap_conf["parameters"]["user_rdn"] = "cn=admin,dc=yunohost,dc=org"
|
||||
ldap_interface = m_ldap.Authenticator(**self.ldap_conf)
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
ldap_interface.authenticate(password="bad_password_lul")
|
||||
|
||||
translation = m18n.g("invalid_password")
|
||||
expected_msg = translation.format()
|
||||
assert expected_msg in str(exception)
|
||||
|
||||
assert ldap_interface.con is None
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_authenticate_simple_bind_anonymous(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
self.ldap_conf["parameters"]["user_rdn"] = ""
|
||||
ldap_interface = m_ldap.Authenticator(**self.ldap_conf)
|
||||
ldap_interface.authenticate()
|
||||
|
||||
assert ldap_interface.con
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_authenticate_sasl_non_interactive_bind(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
self.ldap_conf["parameters"][
|
||||
"user_rdn"
|
||||
] = "gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth" % (
|
||||
os.getgid(),
|
||||
os.getuid(),
|
||||
)
|
||||
ldap_interface = m_ldap.Authenticator(**self.ldap_conf)
|
||||
|
||||
assert ldap_interface.con
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_authenticate_server_down(self, ldap_server, mocker):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
self.ldap_conf["parameters"]["user_rdn"] = "cn=admin,dc=yunohost,dc=org"
|
||||
ldap_server.stop()
|
||||
ldap_interface = m_ldap.Authenticator(**self.ldap_conf)
|
||||
|
||||
# Now if slapd is down, moulinette tries to restart it
|
||||
mocker.patch("os.system")
|
||||
mocker.patch("time.sleep")
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
ldap_interface.authenticate(password="yunohost")
|
||||
|
||||
translation = m18n.g("ldap_server_down")
|
||||
expected_msg = translation.format()
|
||||
assert expected_msg in str(exception)
|
||||
|
||||
assert ldap_interface.con is None
|
||||
|
||||
def create_ldap_interface(self, user_rdn, password=None):
|
||||
self.ldap_conf["parameters"]["user_rdn"] = user_rdn
|
||||
ldap_interface = m_ldap.Authenticator(**self.ldap_conf)
|
||||
if not ldap_interface.con:
|
||||
ldap_interface.authenticate(password=password)
|
||||
return ldap_interface
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_admin_read(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
|
||||
admin_info = ldap_interface.search("cn=admin,dc=yunohost,dc=org", attrs=None)[0]
|
||||
assert "cn" in admin_info
|
||||
assert admin_info["cn"] == ["admin"]
|
||||
assert "description" in admin_info
|
||||
assert admin_info["description"] == ["LDAP Administrator"]
|
||||
assert "userPassword" in admin_info
|
||||
assert admin_info["userPassword"][0].startswith("{CRYPT}$6$")
|
||||
|
||||
admin_info = ldap_interface.search(
|
||||
"cn=admin,dc=yunohost,dc=org", attrs=["userPassword"]
|
||||
)[0]
|
||||
assert list(admin_info.keys()) == ["userPassword"]
|
||||
assert admin_info["userPassword"][0].startswith("{CRYPT}$6$")
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_sasl_read(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
|
||||
% (os.getgid(), os.getuid())
|
||||
)
|
||||
|
||||
admin_info = ldap_interface.search("cn=admin,dc=yunohost,dc=org", attrs=None)[0]
|
||||
assert "cn" in admin_info
|
||||
assert admin_info["cn"] == ["admin"]
|
||||
assert "description" in admin_info
|
||||
assert admin_info["description"] == ["LDAP Administrator"]
|
||||
assert "userPassword" in admin_info
|
||||
assert admin_info["userPassword"][0].startswith("{CRYPT}$6$")
|
||||
|
||||
admin_info = ldap_interface.search(
|
||||
"cn=admin,dc=yunohost,dc=org", attrs=["userPassword"]
|
||||
)[0]
|
||||
assert list(admin_info.keys()) == ["userPassword"]
|
||||
assert admin_info["userPassword"][0].startswith("{CRYPT}$6$")
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_anonymous_read(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface("")
|
||||
|
||||
admin_info = ldap_interface.search("cn=admin,dc=yunohost,dc=org", attrs=None)[0]
|
||||
assert "cn" in admin_info
|
||||
assert admin_info["cn"] == ["admin"]
|
||||
assert "description" in admin_info
|
||||
assert admin_info["description"] == ["LDAP Administrator"]
|
||||
assert "userPassword" not in admin_info
|
||||
|
||||
admin_info = ldap_interface.search(
|
||||
"cn=admin,dc=yunohost,dc=org", attrs=["userPassword"]
|
||||
)[0]
|
||||
assert not admin_info
|
||||
|
||||
def add_new_user(self, ldap_interface):
|
||||
new_user = "new_user"
|
||||
attr_dict = {
|
||||
"objectClass": ["inetOrgPerson", "posixAccount"],
|
||||
"sn": new_user,
|
||||
"cn": new_user,
|
||||
"userPassword": new_user,
|
||||
"gidNumber": "666",
|
||||
"uidNumber": "666",
|
||||
"homeDirectory": "/home/" + new_user,
|
||||
}
|
||||
ldap_interface.add("uid=%s,ou=users" % new_user, attr_dict)
|
||||
|
||||
# Check if we can login as the new user
|
||||
assert self.create_ldap_interface(
|
||||
"uid=%s,ou=users,dc=yunohost,dc=org" % new_user, new_user
|
||||
).con
|
||||
|
||||
return ldap_interface.search(
|
||||
"uid=%s,ou=users,dc=yunohost,dc=org" % new_user, attrs=None
|
||||
)[0]
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_admin_add(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
|
||||
new_user_info = self.add_new_user(ldap_interface)
|
||||
assert "cn" in new_user_info
|
||||
assert new_user_info["cn"] == ["new_user"]
|
||||
assert "sn" in new_user_info
|
||||
assert new_user_info["sn"] == ["new_user"]
|
||||
assert "uid" in new_user_info
|
||||
assert new_user_info["uid"] == ["new_user"]
|
||||
assert "objectClass" in new_user_info
|
||||
assert "inetOrgPerson" in new_user_info["objectClass"]
|
||||
assert "posixAccount" in new_user_info["objectClass"]
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_sasl_add(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
|
||||
% (os.getgid(), os.getuid())
|
||||
)
|
||||
|
||||
new_user_info = self.add_new_user(ldap_interface)
|
||||
assert "cn" in new_user_info
|
||||
assert new_user_info["cn"] == ["new_user"]
|
||||
assert "sn" in new_user_info
|
||||
assert new_user_info["sn"] == ["new_user"]
|
||||
assert "uid" in new_user_info
|
||||
assert new_user_info["uid"] == ["new_user"]
|
||||
assert "objectClass" in new_user_info
|
||||
assert "inetOrgPerson" in new_user_info["objectClass"]
|
||||
assert "posixAccount" in new_user_info["objectClass"]
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_anonymous_add(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface("")
|
||||
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
self.add_new_user(ldap_interface)
|
||||
|
||||
expected_message = "error during LDAP add operation with: rdn="
|
||||
expected_error = "modifications require authentication"
|
||||
assert expected_error in str(exception)
|
||||
assert expected_message in str(exception)
|
||||
|
||||
def remove_new_user(self, ldap_interface):
|
||||
new_user_info = self.add_new_user(
|
||||
self.create_ldap_interface(
|
||||
"gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
|
||||
% (os.getgid(), os.getuid()),
|
||||
"yunohost",
|
||||
)
|
||||
)
|
||||
|
||||
uid = new_user_info["uid"][0]
|
||||
ldap_interface.remove("uid=%s,ou=users" % uid)
|
||||
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
ldap_interface.search(
|
||||
"uid=%s,ou=users,dc=yunohost,dc=org" % uid, attrs=None
|
||||
)
|
||||
|
||||
expected_message = "error during LDAP search operation with: base="
|
||||
expected_error = "No such object"
|
||||
assert expected_error in str(exception)
|
||||
assert expected_message in str(exception)
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_admin_remove(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
|
||||
self.remove_new_user(ldap_interface)
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_sasl_remove(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
|
||||
% (os.getgid(), os.getuid())
|
||||
)
|
||||
|
||||
self.remove_new_user(ldap_interface)
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_anonymous_remove(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface("")
|
||||
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
self.remove_new_user(ldap_interface)
|
||||
|
||||
expected_message = "error during LDAP delete operation with: rdn="
|
||||
expected_error = "modifications require authentication"
|
||||
assert expected_error in str(exception)
|
||||
assert expected_message in str(exception)
|
||||
|
||||
def update_new_user(self, ldap_interface, new_rdn=False):
|
||||
new_user_info = self.add_new_user(
|
||||
self.create_ldap_interface(
|
||||
"gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
|
||||
% (os.getgid(), os.getuid()),
|
||||
"yunohost",
|
||||
)
|
||||
)
|
||||
|
||||
uid = new_user_info["uid"][0]
|
||||
new_user_info["uidNumber"] = ["555"]
|
||||
new_user_info["gidNumber"] = ["555"]
|
||||
new_another_user_uid = "new_another_user"
|
||||
if new_rdn:
|
||||
new_rdn = "uid=%s" % new_another_user_uid
|
||||
ldap_interface.update("uid=%s,ou=users" % uid, new_user_info, new_rdn)
|
||||
|
||||
if new_rdn:
|
||||
uid = new_another_user_uid
|
||||
return ldap_interface.search(
|
||||
"uid=%s,ou=users,dc=yunohost,dc=org" % uid, attrs=None
|
||||
)[0]
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_admin_update(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
|
||||
new_user_info = self.update_new_user(ldap_interface)
|
||||
assert new_user_info["uid"] == ["new_user"]
|
||||
assert new_user_info["uidNumber"] == ["555"]
|
||||
assert new_user_info["gidNumber"] == ["555"]
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_admin_update_new_rdn(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
|
||||
new_user_info = self.update_new_user(ldap_interface, True)
|
||||
assert new_user_info["uid"] == ["new_another_user"]
|
||||
assert new_user_info["uidNumber"] == ["555"]
|
||||
assert new_user_info["gidNumber"] == ["555"]
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_sasl_update(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"gidNumber=%s+uidNumber=%s,cn=peercred,cn=external,cn=auth"
|
||||
% (os.getgid(), os.getuid())
|
||||
)
|
||||
|
||||
new_user_info = self.update_new_user(ldap_interface)
|
||||
assert new_user_info["uid"] == ["new_user"]
|
||||
assert new_user_info["uidNumber"] == ["555"]
|
||||
assert new_user_info["gidNumber"] == ["555"]
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_sasl_update_new_rdn(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
|
||||
new_user_info = self.update_new_user(ldap_interface, True)
|
||||
assert new_user_info["uid"] == ["new_another_user"]
|
||||
assert new_user_info["uidNumber"] == ["555"]
|
||||
assert new_user_info["gidNumber"] == ["555"]
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_anonymous_update(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface("")
|
||||
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
self.update_new_user(ldap_interface)
|
||||
|
||||
expected_message = "error during LDAP update operation with: rdn="
|
||||
expected_error = "modifications require authentication"
|
||||
assert expected_error in str(exception)
|
||||
assert expected_message in str(exception)
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_anonymous_update_new_rdn(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface("")
|
||||
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
self.update_new_user(ldap_interface, True)
|
||||
|
||||
expected_message = "error during LDAP update operation with: rdn="
|
||||
expected_error = "modifications require authentication"
|
||||
assert expected_error in str(exception)
|
||||
assert expected_message in str(exception)
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_empty_update(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
|
||||
new_user_info = self.update_new_user(ldap_interface)
|
||||
assert new_user_info["uid"] == ["new_user"]
|
||||
assert new_user_info["uidNumber"] == ["555"]
|
||||
assert new_user_info["gidNumber"] == ["555"]
|
||||
|
||||
uid = new_user_info["uid"][0]
|
||||
|
||||
assert ldap_interface.update("uid=%s,ou=users" % uid, new_user_info)
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_get_conflict(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
self.add_new_user(ldap_interface)
|
||||
|
||||
conflict = ldap_interface.get_conflict({"uid": "new_user"})
|
||||
assert conflict == ("uid", "new_user")
|
||||
|
||||
conflict = ldap_interface.get_conflict(
|
||||
{"uid": "new_user"}, base_dn="ou=users,dc=yunohost,dc=org"
|
||||
)
|
||||
assert conflict == ("uid", "new_user")
|
||||
|
||||
conflict = ldap_interface.get_conflict({"uid": "not_a_user"})
|
||||
assert not conflict
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Not passing because setup issue idk, to be removed or moved to Yunohost soon anyway..."
|
||||
)
|
||||
def test_validate_uniqueness(self, ldap_server):
|
||||
self.ldap_conf["parameters"]["uri"] = ldap_server.uri
|
||||
ldap_interface = self.create_ldap_interface(
|
||||
"cn=admin,dc=yunohost,dc=org", "yunohost"
|
||||
)
|
||||
self.add_new_user(ldap_interface)
|
||||
|
||||
with pytest.raises(MoulinetteError) as exception:
|
||||
ldap_interface.validate_uniqueness({"uid": "new_user"})
|
||||
|
||||
translation = m18n.g(
|
||||
"ldap_attribute_already_exists", attribute="uid", value="new_user"
|
||||
)
|
||||
expected_msg = translation.format(attribute="uid", value="new_user")
|
||||
assert expected_msg in str(exception)
|
||||
|
||||
assert ldap_interface.validate_uniqueness({"uid": "not_a_user"})
|
52
test/test_translation_format_consistency.py
Normal file
52
test/test_translation_format_consistency.py
Normal file
|
@ -0,0 +1,52 @@
|
|||
import re
|
||||
import json
|
||||
import glob
|
||||
import pytest
|
||||
|
||||
# List all locale files (except en.json being the ref)
|
||||
locale_folder = "locales/"
|
||||
locale_files = glob.glob(locale_folder + "*.json")
|
||||
locale_files = [filename.split("/")[-1] for filename in locale_files]
|
||||
locale_files.remove("en.json")
|
||||
|
||||
reference = json.loads(open(locale_folder + "en.json").read())
|
||||
|
||||
|
||||
def find_inconsistencies(locale_file):
|
||||
|
||||
this_locale = json.loads(open(locale_folder + locale_file).read())
|
||||
|
||||
# We iterate over all keys/string in en.json
|
||||
for key, string in reference.items():
|
||||
|
||||
# Ignore check if there's no translation yet for this key
|
||||
if key not in this_locale:
|
||||
continue
|
||||
|
||||
# Then we check that every "{stuff}" (for python's .format())
|
||||
# should also be in the translated string, otherwise the .format
|
||||
# will trigger an exception!
|
||||
subkeys_in_ref = set(k[0] for k in re.findall(r"{(\w+)(:\w)?}", string))
|
||||
subkeys_in_this_locale = set(
|
||||
k[0] for k in re.findall(r"{(\w+)(:\w)?}", this_locale[key])
|
||||
)
|
||||
|
||||
if any(k not in subkeys_in_ref for k in subkeys_in_this_locale):
|
||||
yield """\n
|
||||
==========================
|
||||
Format inconsistency for string {key} in {locale_file}:"
|
||||
en.json -> {string}
|
||||
{locale_file} -> {translated_string}
|
||||
""".format(
|
||||
key=key,
|
||||
string=string.encode("utf-8"),
|
||||
locale_file=locale_file,
|
||||
translated_string=this_locale[key].encode("utf-8"),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("locale_file", locale_files)
|
||||
def test_translation_format_consistency(locale_file):
|
||||
inconsistencies = list(find_inconsistencies(locale_file))
|
||||
if inconsistencies:
|
||||
raise Exception("".join(inconsistencies))
|
Loading…
Add table
Reference in a new issue