Merge branch 'dev' into bullseye

This commit is contained in:
Kay0u 2021-09-01 16:58:54 +02:00
commit 4774e2a0a9
No known key found for this signature in database
GPG key ID: AAFEEB16CFA2AE2D
81 changed files with 1398 additions and 6846 deletions

28
.github/workflows/autoblack.yml vendored Normal file
View file

@ -0,0 +1,28 @@
name: Check / auto apply Black
on:
push:
branches:
- dev
jobs:
black:
name: Check / auto apply black
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Check files using the black formatter
uses: rickstaa/action-black@v1
id: action_black
with:
black_args: "."
continue-on-error: true
- name: Create Pull Request
if: steps.action_black.outputs.is_formatted == 'true'
uses: peter-evans/create-pull-request@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
title: "Format Python code with Black"
commit-message: ":art: Format Python code with Black"
body: |
This pull request uses the [psf/black](https://github.com/psf/black) formatter.
base: ${{ github.head_ref }} # Creates pull request onto pull request or commit branch
branch: actions/black

46
.github/workflows/tox.yml vendored Normal file
View file

@ -0,0 +1,46 @@
name: Tests
on:
push:
branches:
- dev
pull_request:
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.7]
steps:
- uses: actions/checkout@v1
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install apt dependencies
run: sudo apt install ldap-utils slapd libsasl2-dev libldap2-dev libssl-dev
- name: Install tox
run: |
python -m pip install --upgrade pip
pip install tox tox-gh-actions
- name: Test with tox
run: tox -e py37-pytest
invalidcode:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.7]
steps:
- uses: actions/checkout@v1
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install tox
run: |
python -m pip install --upgrade pip
pip install tox tox-gh-actions
- name: Linter
run: tox -e py37-invalidcode

View file

@ -1,24 +0,0 @@
language: python
addons:
apt:
packages:
- ldap-utils
- slapd
matrix:
include:
- python: 3.7
env: TOXENV=py37-pytest
- python: 3.7
env: TOXENV=py37-lint
- python: 3.7
env: TOXENV=format-check
- python: 3.7
env: TOXENV=docs
install:
- pip install tox
script:
- tox

View file

@ -1,15 +1,16 @@
[![Build Status](https://travis-ci.org/YunoHost/moulinette.svg?branch=stretch-unstable)](https://travis-ci.org/YunoHost/moulinette) <h1 align="center">Moulinette</h1>
[![GitHub license](https://img.shields.io/github/license/YunoHost/moulinette)](https://github.com/YunoHost/moulinette/blob/stretch-unstable/LICENSE)
Moulinette <div align="center">
==========
The *moulinette* is a Python package that allows to quickly and easily [![Tests status](https://github.com/YunoHost/moulinette/actions/workflows/tox.yml/badge.svg)](https://github.com/YunoHost/moulinette/actions/workflows/tox.yml)
prototype interfaces for your application. [![GitHub license](https://img.shields.io/github/license/YunoHost/moulinette)](https://github.com/YunoHost/moulinette/blob/dev/LICENSE)
<a href="https://translate.yunohost.org/engage/yunohost/?utm_source=widget">
<img src="https://translate.yunohost.org/widgets/yunohost/-/287x66-white.png" alt="Translation status" /> Moulinette is a small Python framework meant to easily create programs with unified CLI and API.
</a>
In particular, it is used as a base framework for the YunoHost project.
</div>
Issues Issues
------ ------
@ -19,35 +20,23 @@ Issues
Overview Overview
-------- --------
Initially, the moulinette was an application made for the Moulinette allows to create a YAML "actionmaps" that describes what commands are available. Moulinette will automatically make these commands available through the CLI and Web API, and will be mapped to a python function. Moulinette also provide some general helpers, for example for logging, i18n, authentication, or common file system operations.
[YunoHost](https://yunohost.org/) project in order to regroup all its
related operations into a single program called *moulinette*. Those
operations were available from a command-line interface and a Web server
providing an API. Moreover, the usage of these operations (e.g.
required/optional arguments) was defined into a simple yaml file -
called *actionsmap*. This file was parsed in order to construct an
*ArgumentParser* object and to parse the command arguments to process
the proper operation.
During a long refactoring with the goal of unify both interfaces, the <div align="center"><img src="doc/actionsmap.png" width="700" /></div>
idea to separate the core of the YunoHost operations has emerged.
The core kept the same name *moulinette* and try to follow the same
initial principle. An [Actions Map](#actions-map) - which defines
available operations and their usage - is parsed and it's used to
process an operation from several unified [Interfaces](#interfaces). It
also supports a configuration mechanism - which allows to restrict an
operation on an interface for example (see
[Authenticators](#authenticators)).
Translation
-----------
Dev Documentation You can help translate Moulinette on our [translation platform](https://translate.yunohost.org/engage/yunohost/?utm_source=widget)
-----------------
https://moulinette.readthedocs.org <div align="center"><img src="https://translate.yunohost.org/widgets/yunohost/-/moulinette/horizontal-auto.svg" alt="Translation status" /></div>
Developpers
-----------
Testing - You can learn how to get started with developing on YunoHost by reading [this piece of documentation](https://yunohost.org/dev).
------- - Specific doc for moulinette: https://moulinette.readthedocs.org
- Run tests with:
``` ```
$ pip install tox $ pip install tox

27
debian/changelog vendored
View file

@ -4,6 +4,33 @@ moulinette (11.0.0~alpha) unstable; urgency=low
-- Alexandre Aubin <alex.aubin@mailoo.org> Fri, 05 Feb 2021 00:02:38 +0100 -- Alexandre Aubin <alex.aubin@mailoo.org> Fri, 05 Feb 2021 00:02:38 +0100
moulinette (4.2.4) stable; urgency=low
- [fix] Avoid warning and use safeloader ([#281](https://github.com/YunoHost/moulinette/pull/281))
- [fix] Add warning when trying to feed non-string values to Popen env (2a89a82)
- [i18n] Translations updated for Esperanto, French, German, Portuguese
Thanks to all contributors <3 ! (amirale qt, Christian Wehrli, Éric Gaspar, ljf, mifegui)
-- Alexandre Aubin <alex.aubin@mailoo.org> Thu, 19 Aug 2021 19:25:30 +0200
moulinette (4.2.3.3) stable; urgency=low
- [fix] Damn array args bug (2c9ec9f6)
Thanks to all contributors <3 ! (ljf)
-- Alexandre Aubin <alex.aubin@mailoo.org> Thu, 03 Jun 2021 18:40:18 +0200
moulinette (4.2.3.2) stable; urgency=low
- [fix] wait 1s for message in call_async_output, prevent CPU overload ([#275](https://github.com/YunoHost/moulinette/pull/275))
- [i18n] Translations updated for Chinese (Simplified)
Thanks to all contributors <3 ! (Kayou, yahoo)
-- Alexandre Aubin <alex.aubin@mailoo.org> Wed, 02 Jun 2021 20:23:31 +0200
moulinette (4.2.3.1) stable; urgency=low moulinette (4.2.3.1) stable; urgency=low
- [fix] Request params not decoded ([#277](https://github.com/YunoHost/moulinette/pull/277)) - [fix] Request params not decoded ([#277](https://github.com/YunoHost/moulinette/pull/277))

2
debian/control vendored
View file

@ -9,11 +9,9 @@ Homepage: https://github.com/YunoHost/moulinette
Package: moulinette Package: moulinette
Architecture: all Architecture: all
Depends: ${misc:Depends}, ${python3:Depends}, Depends: ${misc:Depends}, ${python3:Depends},
python3-ldap,
python3-yaml, python3-yaml,
python3-bottle (>= 0.12), python3-bottle (>= 0.12),
python3-gevent-websocket, python3-gevent-websocket,
python3-argcomplete,
python3-toml, python3-toml,
python3-psutil, python3-psutil,
python3-tz python3-tz

View file

@ -18,18 +18,21 @@
import os import os
import sys import sys
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(".."))
import sys import sys
from mock import Mock as MagicMock from mock import Mock as MagicMock
class Mock(MagicMock): class Mock(MagicMock):
@classmethod @classmethod
def __getattr__(cls, name): def __getattr__(cls, name):
return MagicMock() return MagicMock()
MOCK_MODULES = ['ldap', 'ldap.modlist', 'ldap.sasl']
MOCK_MODULES = ["ldap", "ldap.modlist", "ldap.sasl"]
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
@ -42,36 +45,38 @@ sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
# Add any Sphinx extension module names here, as strings. They can be # Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones. # ones.
extensions = ['sphinx.ext.autodoc', extensions = [
'sphinx.ext.intersphinx', "sphinx.ext.autodoc",
'sphinx.ext.todo', "sphinx.ext.intersphinx",
'sphinx.ext.viewcode'] "sphinx.ext.todo",
"sphinx.ext.viewcode",
]
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates'] templates_path = ["_templates"]
# The suffix(es) of source filenames. # The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string: # You can specify multiple suffix as a list of string:
# #
# source_suffix = ['.rst', '.md'] # source_suffix = ['.rst', '.md']
source_suffix = '.rst' source_suffix = ".rst"
# The master toctree document. # The master toctree document.
master_doc = 'index' master_doc = "index"
# General information about the project. # General information about the project.
project = u'Moulinette' project = u"Moulinette"
copyright = u'2017, YunoHost Collective' copyright = u"2017, YunoHost Collective"
author = u'YunoHost Collective' author = u"YunoHost Collective"
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
# built documents. # built documents.
# #
# The short X.Y version. # The short X.Y version.
version = u'2.6.1' version = u"2.6.1"
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
release = u'2.6.1' release = u"2.6.1"
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
@ -83,10 +88,10 @@ language = None
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path # This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx' pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing. # If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True todo_include_todos = True
@ -97,7 +102,7 @@ todo_include_todos = True
# The theme to use for HTML and HTML Help pages. See the documentation for # The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. # a list of builtin themes.
# #
html_theme = 'classic' html_theme = "classic"
# Theme options are theme-specific and customize the look and feel of a theme # Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the # further. For a list of options available for each theme, see the
@ -108,7 +113,7 @@ html_theme = 'classic'
# Add any paths that contain custom static files (such as style sheets) here, # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files, # relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css". # so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static'] html_static_path = ["_static"]
# Custom sidebar templates, must be a dictionary that maps document names # Custom sidebar templates, must be a dictionary that maps document names
# to template names. # to template names.
@ -116,11 +121,11 @@ html_static_path = ['_static']
# This is required for the alabaster theme # This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = { html_sidebars = {
'**': [ "**": [
# 'about.html', # 'about.html',
# 'navigation.html', # 'navigation.html',
# 'relations.html', # needs 'show_related': True theme option to display # 'relations.html', # needs 'show_related': True theme option to display
'searchbox.html', "searchbox.html",
# 'donate.html', # 'donate.html',
] ]
} }
@ -129,7 +134,7 @@ html_sidebars = {
# -- Options for HTMLHelp output ------------------------------------------ # -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = 'Moulinettedoc' htmlhelp_basename = "Moulinettedoc"
# -- Options for LaTeX output --------------------------------------------- # -- Options for LaTeX output ---------------------------------------------
@ -138,15 +143,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
# #
# 'papersize': 'letterpaper', # 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt'). # The font size ('10pt', '11pt' or '12pt').
# #
# 'pointsize': '10pt', # 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble. # Additional stuff for the LaTeX preamble.
# #
# 'preamble': '', # 'preamble': '',
# Latex figure (float) alignment # Latex figure (float) alignment
# #
# 'figure_align': 'htbp', # 'figure_align': 'htbp',
@ -156,8 +158,13 @@ latex_elements = {
# (source start file, target name, title, # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]). # author, documentclass [howto, manual, or own class]).
latex_documents = [ latex_documents = [
(master_doc, 'Moulinette.tex', u'Moulinette Documentation', (
u'YunoHost Collective', 'manual'), master_doc,
"Moulinette.tex",
u"Moulinette Documentation",
u"YunoHost Collective",
"manual",
),
] ]
@ -165,10 +172,7 @@ latex_documents = [
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [ man_pages = [(master_doc, "moulinette", u"Moulinette Documentation", [author], 1)]
(master_doc, 'moulinette', u'Moulinette Documentation',
[author], 1)
]
# -- Options for Texinfo output ------------------------------------------- # -- Options for Texinfo output -------------------------------------------
@ -177,13 +181,17 @@ man_pages = [
# (source start file, target name, title, author, # (source start file, target name, title, author,
# dir menu entry, description, category) # dir menu entry, description, category)
texinfo_documents = [ texinfo_documents = [
(master_doc, 'Moulinette', u'Moulinette Documentation', (
author, 'Moulinette', 'One line description of project.', master_doc,
'Miscellaneous'), "Moulinette",
u"Moulinette Documentation",
author,
"Moulinette",
"One line description of project.",
"Miscellaneous",
),
] ]
# Example configuration for intersphinx: refer to the Python standard library. # Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None} intersphinx_mapping = {"https://docs.python.org/": None}

View file

@ -1,6 +1,5 @@
{ {
"argument_required": "المُعامِل '{argument}' مطلوب", "argument_required": "المُعامِل '{argument}' مطلوب",
"authentication_profile_required": "المصادقة مع الملف الشخصي '{profile}' مطلوبة",
"authentication_required": "المصادقة مطلوبة", "authentication_required": "المصادقة مطلوبة",
"authentication_required_long": "المصادقة مطلوبة قبل القيام بهذا الإجراء", "authentication_required_long": "المصادقة مطلوبة قبل القيام بهذا الإجراء",
"colon": "{}: ", "colon": "{}: ",
@ -8,11 +7,8 @@
"deprecated_command": "'{prog} {command}' تم التخلي عنه و سوف تتم إزالته مستقبلا", "deprecated_command": "'{prog} {command}' تم التخلي عنه و سوف تتم إزالته مستقبلا",
"deprecated_command_alias": "'{prog} {old}' تم التخلي عنه و سوف يتم إزالته مستقبلا، إستخدم '{prog} {new}' بدلا من ذلك", "deprecated_command_alias": "'{prog} {old}' تم التخلي عنه و سوف يتم إزالته مستقبلا، إستخدم '{prog} {new}' بدلا من ذلك",
"error": "خطأ :", "error": "خطأ :",
"error_see_log": "طرأ هناك خطأ. يرجى الإطلاع على السجلات للمزيد مِن التفاصيل على المسار /var/log/yunohost/.",
"file_exists": "إنّ الملف موجود من قبل : '{path}'",
"file_not_exist": "الملف غير موجود : '{path}'", "file_not_exist": "الملف غير موجود : '{path}'",
"folder_exists": "إنّ المجلد موجود من قبل : '{path}'", "folder_exists": "إنّ المجلد موجود من قبل : '{path}'",
"folder_not_exist": "المجلد غير موجود",
"instance_already_running": "هناك بالفعل عملية YunoHost جارية. الرجاء الانتظار حتى ينتهي الأمر قبل تشغيل آخر.", "instance_already_running": "هناك بالفعل عملية YunoHost جارية. الرجاء الانتظار حتى ينتهي الأمر قبل تشغيل آخر.",
"invalid_argument": "المُعامِل غير صالح '{argument}': {error}", "invalid_argument": "المُعامِل غير صالح '{argument}': {error}",
"invalid_password": "كلمة السر خاطئة", "invalid_password": "كلمة السر خاطئة",
@ -25,7 +21,6 @@
"operation_interrupted": "تم توقيف العملية", "operation_interrupted": "تم توقيف العملية",
"password": "كلمة السر", "password": "كلمة السر",
"pattern_not_match": "لا يتطابق مع النموذج", "pattern_not_match": "لا يتطابق مع النموذج",
"permission_denied": "رُفض التصريح",
"root_required": "يتوجب عليك أن تكون مدير الجذر root للقيام بهذا الإجراء", "root_required": "يتوجب عليك أن تكون مدير الجذر root للقيام بهذا الإجراء",
"server_already_running": "هناك خادم يشتغل على ذاك المنفذ", "server_already_running": "هناك خادم يشتغل على ذاك المنفذ",
"success": "تم بنجاح !", "success": "تم بنجاح !",
@ -36,20 +31,19 @@
"values_mismatch": "القيمتين غير متطابقتين", "values_mismatch": "القيمتين غير متطابقتين",
"warning": "تحذير :", "warning": "تحذير :",
"websocket_request_expected": "كان ينتظر طلبًا عبر الويب سوكت WebSocket", "websocket_request_expected": "كان ينتظر طلبًا عبر الويب سوكت WebSocket",
"cannot_open_file": "ليس بالإمكان فتح الملف {file:s} (السبب : {error:s})", "cannot_open_file": "ليس بالإمكان فتح الملف {file} (السبب : {error})",
"cannot_write_file": "لا يمكن الكتابة في الملف {file:s} (السبب : {error:s})", "cannot_write_file": "لا يمكن الكتابة في الملف {file} (السبب : {error})",
"unknown_error_reading_file": "طرأ هناك خطأ ما أثناء عملية قراءة الملف {file:s} (السبب: {error:s})", "unknown_error_reading_file": "طرأ هناك خطأ ما أثناء عملية قراءة الملف {file} (السبب: {error})",
"corrupted_json": "قراءة json مُشوّهة مِن {ressource:s} (السبب : {error:s})", "corrupted_json": "قراءة json مُشوّهة مِن {ressource} (السبب : {error})",
"error_writing_file": "طرأ هناك خطأ أثناء الكتابة في الملف {file:s}: {error:s}", "error_writing_file": "طرأ هناك خطأ أثناء الكتابة في الملف {file}: {error}",
"error_removing": "خطأ أثناء عملية حذف {path:s}: {error:s}", "error_removing": "خطأ أثناء عملية حذف {path}: {error}",
"error_changing_file_permissions": "خطأ أثناء عملية تعديل التصريحات لـ {path:s}: {error:s}", "error_changing_file_permissions": "خطأ أثناء عملية تعديل التصريحات لـ {path}: {error}",
"invalid_url": "خطأ في عنوان الرابط {url:s} (هل هذا الموقع موجود حقًا ؟)", "invalid_url": "خطأ في عنوان الرابط {url} (هل هذا الموقع موجود حقًا ؟)",
"download_ssl_error": "خطأ في الاتصال الآمن عبر الـ SSL أثناء محاولة الربط بـ {url:s}", "download_ssl_error": "خطأ في الاتصال الآمن عبر الـ SSL أثناء محاولة الربط بـ {url}",
"download_timeout": "{url:s} استغرق مدة طويلة جدا للإستجابة، فتوقّف.", "download_timeout": "{url} استغرق مدة طويلة جدا للإستجابة، فتوقّف.",
"download_unknown_error": "خطأ أثناء عملية تنزيل البيانات مِن {url:s} : {error:s}", "download_unknown_error": "خطأ أثناء عملية تنزيل البيانات مِن {url} : {error}",
"download_bad_status_code": "{url:s} أعاد رمز الحالة {code:s}", "download_bad_status_code": "{url} أعاد رمز الحالة {code}",
"command_unknown": "الأمر '{command:s}' مجهول؟", "corrupted_yaml": "قراءة مُشوّهة لنسق yaml مِن {ressource} (السبب : {error})",
"corrupted_yaml": "قراءة مُشوّهة لنسق yaml مِن {ressource:s} (السبب : {error:s})",
"info": "معلومة:", "info": "معلومة:",
"warn_the_user_about_waiting_lock_again": "جارٍ الانتظار…", "warn_the_user_about_waiting_lock_again": "جارٍ الانتظار…",
"warn_the_user_that_lock_is_acquired": "لقد انتهى تنفيذ ذاك الأمر للتوّ ، جارٍ تنفيذ هذا الأمر", "warn_the_user_that_lock_is_acquired": "لقد انتهى تنفيذ ذاك الأمر للتوّ ، جارٍ تنفيذ هذا الأمر",

View file

@ -1,6 +1,5 @@
{ {
"argument_required": "Es requereix l'argument {argument}", "argument_required": "Es requereix l'argument {argument}",
"authentication_profile_required": "Autenticació requerida al perfil {profile}",
"authentication_required": "Es requereix autenticació", "authentication_required": "Es requereix autenticació",
"authentication_required_long": "Es requereix autenticació per realitzar aquesta tasca", "authentication_required_long": "Es requereix autenticació per realitzar aquesta tasca",
"colon": "{}: ", "colon": "{}: ",
@ -8,11 +7,8 @@
"deprecated_command": "{prog}{command}és obsolet i es desinstal·larà en el futur", "deprecated_command": "{prog}{command}és obsolet i es desinstal·larà en el futur",
"deprecated_command_alias": "{prog}{old}és obsolet i es desinstal·larà en el futur, utilitzeu {prog}{new}en el seu lloc", "deprecated_command_alias": "{prog}{old}és obsolet i es desinstal·larà en el futur, utilitzeu {prog}{new}en el seu lloc",
"error": "Error:", "error": "Error:",
"error_see_log": "Hi ha hagut un error. Si us plau verifiqueu el registre per a més informació, són a /var/log/yunohost/.",
"file_exists": "El fitxer ja existeix: '{path}'",
"file_not_exist": "El fitxer no existeix: '{path}'", "file_not_exist": "El fitxer no existeix: '{path}'",
"folder_exists": "La carpeta ja existeix: '{path}'", "folder_exists": "La carpeta ja existeix: '{path}'",
"folder_not_exist": "La carpeta no existeix",
"instance_already_running": "Ja hi ha una operació de YunoHost en curs. Espereu a que s'acabi abans d'executar-ne una altra.", "instance_already_running": "Ja hi ha una operació de YunoHost en curs. Espereu a que s'acabi abans d'executar-ne una altra.",
"invalid_argument": "Argument invàlid '{argument}': {error}", "invalid_argument": "Argument invàlid '{argument}': {error}",
"invalid_password": "Contrasenya invàlida", "invalid_password": "Contrasenya invàlida",
@ -25,7 +21,6 @@
"operation_interrupted": "Operació interrompuda", "operation_interrupted": "Operació interrompuda",
"password": "Contrasenya", "password": "Contrasenya",
"pattern_not_match": "No coincideix amb el patró", "pattern_not_match": "No coincideix amb el patró",
"permission_denied": "Permís denegat",
"root_required": "Ha de ser root per realitzar aquesta acció", "root_required": "Ha de ser root per realitzar aquesta acció",
"server_already_running": "Ja s'està executant un servidor en aquest port", "server_already_running": "Ja s'està executant un servidor en aquest port",
"success": "Èxit!", "success": "Èxit!",
@ -36,22 +31,21 @@
"values_mismatch": "Els valors no coincideixen", "values_mismatch": "Els valors no coincideixen",
"warning": "Atenció:", "warning": "Atenció:",
"websocket_request_expected": "S'esperava una petició WebSocket", "websocket_request_expected": "S'esperava una petició WebSocket",
"cannot_open_file": "No s'ha pogut obrir el fitxer {file:s} (motiu: {error:s})", "cannot_open_file": "No s'ha pogut obrir el fitxer {file} (motiu: {error})",
"cannot_write_file": "No s'ha pogut escriure el fitxer {file:s} (motiu: {error:s})", "cannot_write_file": "No s'ha pogut escriure el fitxer {file} (motiu: {error})",
"unknown_error_reading_file": "Error desconegut al intentar llegir el fitxer {file:s} (motiu: {error:s})", "unknown_error_reading_file": "Error desconegut al intentar llegir el fitxer {file} (motiu: {error})",
"corrupted_json": "JSON corrupte llegit des de {ressource:s} (motiu: {error:s})", "corrupted_json": "JSON corrupte llegit des de {ressource} (motiu: {error})",
"corrupted_yaml": "YAML corrupte llegit des de {ressource:s} (motiu: {error:s})", "corrupted_yaml": "YAML corrupte llegit des de {ressource} (motiu: {error})",
"error_writing_file": "Error al escriure el fitxer {file:s}: {error:s}", "error_writing_file": "Error al escriure el fitxer {file}: {error}",
"error_removing": "Error al eliminar {path:s}: {error:s}", "error_removing": "Error al eliminar {path}: {error}",
"error_changing_file_permissions": "Error al canviar els permisos per {path:s}: {error:s}", "error_changing_file_permissions": "Error al canviar els permisos per {path}: {error}",
"invalid_url": "URL invàlid {url:s} (el lloc web existeix?)", "invalid_url": "URL invàlid {url} (el lloc web existeix?)",
"download_ssl_error": "Error SSL al connectar amb {url:s}", "download_ssl_error": "Error SSL al connectar amb {url}",
"download_timeout": "{url:s} ha tardat massa en respondre, s'ha deixat d'esperar.", "download_timeout": "{url} ha tardat massa en respondre, s'ha deixat d'esperar.",
"download_unknown_error": "Error al baixar dades des de {url:s}: {error:s}", "download_unknown_error": "Error al baixar dades des de {url}: {error}",
"download_bad_status_code": "{url:s} ha retornat el codi d'estat {code:s}", "download_bad_status_code": "{url} ha retornat el codi d'estat {code}",
"command_unknown": "Ordre '{command:s}' desconegut?",
"info": "Info:", "info": "Info:",
"corrupted_toml": "El fitxer TOML ha estat corromput en la lectura des de {ressource:s} (motiu: {error:s})", "corrupted_toml": "El fitxer TOML ha estat corromput en la lectura des de {ressource} (motiu: {error})",
"warn_the_user_about_waiting_lock": "Hi ha una altra ordre de YunoHost en execució, s'executarà aquesta ordre un cop l'anterior hagi acabat", "warn_the_user_about_waiting_lock": "Hi ha una altra ordre de YunoHost en execució, s'executarà aquesta ordre un cop l'anterior hagi acabat",
"warn_the_user_about_waiting_lock_again": "Encara en espera…", "warn_the_user_about_waiting_lock_again": "Encara en espera…",
"warn_the_user_that_lock_is_acquired": "L'altra ordre tot just ha acabat, ara s'executarà aquesta ordre", "warn_the_user_that_lock_is_acquired": "L'altra ordre tot just ha acabat, ara s'executarà aquesta ordre",

1
locales/ckb.json Normal file
View file

@ -0,0 +1 @@
{}

View file

@ -1,6 +1,5 @@
{ {
"argument_required": "参数“{argument}”是必须的", "argument_required": "参数“{argument}”是必须的",
"authentication_profile_required": "必须验证配置文件{profile}",
"authentication_required": "需要验证", "authentication_required": "需要验证",
"authentication_required_long": "此操作需要验证", "authentication_required_long": "此操作需要验证",
"colon": "{} ", "colon": "{} ",
@ -8,11 +7,8 @@
"deprecated_command": "{prog}{command}已经放弃使用,将来会删除", "deprecated_command": "{prog}{command}已经放弃使用,将来会删除",
"deprecated_command_alias": "{prog}{old}已经放弃使用,将来会删除,请使用{prog}{new}代替", "deprecated_command_alias": "{prog}{old}已经放弃使用,将来会删除,请使用{prog}{new}代替",
"error": "错误:", "error": "错误:",
"error_see_log": "发生错误。请参看日志文件获取错误详情,日志文件位于 /var/log/yunohost/。", "file_not_exist": "文件不存在: '{path}'",
"file_exists": "文件已存在:{path}", "folder_exists": "目录已存在: '{path}'",
"file_not_exist": "文件不存在:{path}",
"folder_exists": "目录已存在:{path}",
"folder_not_exist": "目录不存在",
"info": "信息:", "info": "信息:",
"instance_already_running": "已经有一个YunoHost操作正在运行。 请等待它完成再运行另一个。", "instance_already_running": "已经有一个YunoHost操作正在运行。 请等待它完成再运行另一个。",
"invalid_argument": "参数错误{argument}{error}", "invalid_argument": "参数错误{argument}{error}",
@ -36,20 +32,19 @@
"values_mismatch": "值不匹配", "values_mismatch": "值不匹配",
"warning": "警告:", "warning": "警告:",
"websocket_request_expected": "期望一个WebSocket请求", "websocket_request_expected": "期望一个WebSocket请求",
"cannot_open_file": "不能打开文件{file:s}(原因:{error:s}", "cannot_open_file": "不能打开文件{file}(原因:{error}",
"cannot_write_file": "写入文件{file:s}失败(原因:{error:s}", "cannot_write_file": "写入文件{file}失败(原因:{error}",
"unknown_error_reading_file": "尝试读取文件{files}时发生未知错误(原因:{errors}", "unknown_error_reading_file": "尝试读取文件{file}时发生未知错误(原因:{error}",
"corrupted_json": "从{ressource:s}读取的JSON损坏原因{error:s}", "corrupted_json": "从{ressource}读取的JSON损坏原因{error}",
"corrupted_yaml": "从{ressource:s}读取的YMAL损坏原因{error:s}", "corrupted_yaml": "从{ressource}读取的YMAL损坏原因{error}",
"error_writing_file": "写入文件{file:s}失败:{error:s}", "error_writing_file": "写入文件{file}失败:{error}",
"error_removing": "删除路径{path:s}失败:{error:s}", "error_removing": "删除路径{path}失败:{error}",
"error_changing_file_permissions": "目录{path:s}权限修改失败:{error:s}", "error_changing_file_permissions": "目录{path}权限修改失败:{error}",
"invalid_url": "URL{url:s}无效site是否存在", "invalid_url": "URL{url}无效site是否存在",
"download_ssl_error": "连接{url:s}时发生SSL错误", "download_ssl_error": "连接{url}时发生SSL错误",
"download_timeout": "{url:s}响应超时,放弃。", "download_timeout": "{url}响应超时,放弃。",
"download_unknown_error": "下载{url:s}失败:{error:s}", "download_unknown_error": "下载{url}失败:{error}",
"download_bad_status_code": "{url:s}返回状态码:{code:s}", "download_bad_status_code": "{url}返回状态码:{code}",
"command_unknown": "命令'{command:s}'未知?",
"warn_the_user_that_lock_is_acquired": "另一个命令刚刚完成,现在启动此命令", "warn_the_user_that_lock_is_acquired": "另一个命令刚刚完成,现在启动此命令",
"warn_the_user_about_waiting_lock_again": "还在等...", "warn_the_user_about_waiting_lock_again": "还在等...",
"warn_the_user_about_waiting_lock": "目前正在运行另一个YunoHost命令我们在运行此命令之前等待它完成", "warn_the_user_about_waiting_lock": "目前正在运行另一个YunoHost命令我们在运行此命令之前等待它完成",

View file

@ -5,21 +5,20 @@
"warn_the_user_that_lock_is_acquired": "Předchozí operace dokončena, nyní spouštíme tuto", "warn_the_user_that_lock_is_acquired": "Předchozí operace dokončena, nyní spouštíme tuto",
"warn_the_user_about_waiting_lock_again": "Stále čekáme...", "warn_the_user_about_waiting_lock_again": "Stále čekáme...",
"warn_the_user_about_waiting_lock": "Jiná YunoHost operace právě probíhá, před spuštěním této čekáme na její dokončení", "warn_the_user_about_waiting_lock": "Jiná YunoHost operace právě probíhá, před spuštěním této čekáme na její dokončení",
"command_unknown": "Příkaz '{command:s}' neznámý?", "download_bad_status_code": "{url} vrátil stavový kód {code}",
"download_bad_status_code": "{url:s} vrátil stavový kód {code:s}", "download_unknown_error": "Chyba při stahování dat z {url}: {error}",
"download_unknown_error": "Chyba při stahování dat z {url:s}: {error:s}", "download_timeout": "{url} příliš dlouho neodpovídá, akce přerušena.",
"download_timeout": "{url:s} příliš dlouho neodpovídá, akce přerušena.", "download_ssl_error": "SSL chyba při spojení s {url}",
"download_ssl_error": "SSL chyba při spojení s {url:s}", "invalid_url": "Špatný odkaz {url} (je vůbec dostupný?)",
"invalid_url": "Špatný odkaz {url:s} (je vůbec dostupný?)", "error_changing_file_permissions": "Chyba při nastavování oprávnění pro {path}: {error}",
"error_changing_file_permissions": "Chyba při nastavování oprávnění pro {path:s}: {error:s}", "error_removing": "Chyba při přesunu {path}: {error}",
"error_removing": "Chyba při přesunu {path:s}: {error:s}", "error_writing_file": "Chyba při zápisu souboru/ů {file}: {error}",
"error_writing_file": "Chyba při zápisu souboru/ů {file:s}: {error:s}", "corrupted_toml": "Nepodařilo se načíst TOML z {ressource} (reason: {error})",
"corrupted_toml": "Nepodařilo se načíst TOML z {ressource:s} (reason: {error:s})", "corrupted_yaml": "Nepodařilo se načíst YAML z {ressource} (reason: {error})",
"corrupted_yaml": "Nepodařilo se načíst YAML z {ressource:s} (reason: {error:s})", "corrupted_json": "Nepodařilo se načíst JSON {ressource} (reason: {error})",
"corrupted_json": "Nepodařilo se načíst JSON {ressource:s} (reason: {error:s})", "unknown_error_reading_file": "Vyskytla se neznámá chyba při čtení souboru/ů {file} (reason: {error})",
"unknown_error_reading_file": "Vyskytla se neznámá chyba při čtení souboru/ů {file:s} (reason: {error:s})", "cannot_write_file": "Nelze zapsat soubor/y {file} (reason: {error})",
"cannot_write_file": "Nelze zapsat soubor/y {file:s} (reason: {error:s})", "cannot_open_file": "Nelze otevřít soubor/y {file} (reason: {error})",
"cannot_open_file": "Nelze otevřít soubor/y {file:s} (reason: {error:s})",
"websocket_request_expected": "Očekáván WebSocket požadavek", "websocket_request_expected": "Očekáván WebSocket požadavek",
"warning": "Varování:", "warning": "Varování:",
"values_mismatch": "Hodnoty nesouhlasí", "values_mismatch": "Hodnoty nesouhlasí",
@ -43,10 +42,8 @@
"invalid_argument": "Nesprávný argument '{argument}': {error}", "invalid_argument": "Nesprávný argument '{argument}': {error}",
"instance_already_running": "Právě probíhá jiná YunoHost operace. Před spuštěním další operace vyčkejte na její dokončení.", "instance_already_running": "Právě probíhá jiná YunoHost operace. Před spuštěním další operace vyčkejte na její dokončení.",
"info": "Info:", "info": "Info:",
"folder_not_exist": "Adresář neexistuje",
"folder_exists": "Adresář již existuje: '{path}'", "folder_exists": "Adresář již existuje: '{path}'",
"file_not_exist": "Soubor neexistuje: '{path}'", "file_not_exist": "Soubor neexistuje: '{path}'",
"file_exists": "Soubor již existuje: '{path}'",
"error": "Chyba:", "error": "Chyba:",
"deprecated_command_alias": "'{prog} {old}' je zastaralý a bude odebrán v budoucích verzích, použijte '{prog} {new}'", "deprecated_command_alias": "'{prog} {old}' je zastaralý a bude odebrán v budoucích verzích, použijte '{prog} {new}'",
"deprecated_command": "'{prog} {command}' je zastaralý a bude odebrán v budoucích verzích", "deprecated_command": "'{prog} {command}' je zastaralý a bude odebrán v budoucích verzích",

View file

@ -1,16 +1,12 @@
{ {
"argument_required": "Der Parameter {argument} ist erforderlich", "argument_required": "Der Parameter {argument} ist erforderlich",
"authentication_profile_required": "Anmeldung als Nutzer '{profile}' wird benötigt",
"authentication_required": "Anmeldung erforderlich", "authentication_required": "Anmeldung erforderlich",
"authentication_required_long": "Bitte erst anmelden um diese Aktion auszuführen", "authentication_required_long": "Bitte erst anmelden um diese Aktion auszuführen",
"colon": "{}: ", "colon": "{}: ",
"confirm": "Bestätige {prompt}", "confirm": "Bestätige {prompt}",
"error": "Fehler:", "error": "Fehler:",
"error_see_log": "Ein Fehler ist aufgetreten. Für Details bitte im Log nachsehen.",
"file_exists": "Datei existiert bereits: '{path}'",
"file_not_exist": "Datei ist nicht vorhanden: '{path}'", "file_not_exist": "Datei ist nicht vorhanden: '{path}'",
"folder_exists": "Ordner existiert bereits: '{path}'", "folder_exists": "Ordner existiert bereits: '{path}'",
"folder_not_exist": "Ordner existiert nicht",
"instance_already_running": "Es läuft bereits eine YunoHost-Operation. Bitte warte, bis sie fertig ist, bevor du eine weitere startest.", "instance_already_running": "Es läuft bereits eine YunoHost-Operation. Bitte warte, bis sie fertig ist, bevor du eine weitere startest.",
"invalid_argument": "Argument ungültig '{argument}': {error}", "invalid_argument": "Argument ungültig '{argument}': {error}",
"invalid_password": "Passwort falsch", "invalid_password": "Passwort falsch",
@ -23,39 +19,37 @@
"operation_interrupted": "Vorgang unterbrochen", "operation_interrupted": "Vorgang unterbrochen",
"password": "Passwort", "password": "Passwort",
"pattern_not_match": "Entspricht nicht dem Muster", "pattern_not_match": "Entspricht nicht dem Muster",
"permission_denied": "Zugriff verweigert",
"root_required": "Nur der Nutzer root kann diesen Vorgang ausführen", "root_required": "Nur der Nutzer root kann diesen Vorgang ausführen",
"server_already_running": "Einen anderer Dienst arbeitet bereits auf diesem Port", "server_already_running": "Einen anderer Dienst arbeitet bereits auf diesem Port",
"success": "Erfolg!", "success": "Erfolg!",
"unable_authenticate": "Anmelden fehlgeschlagen", "unable_authenticate": "Anmelden fehlgeschlagen",
"unable_retrieve_session": "Sitzung konnte nicht abgerufen werden. Grund: '{exception}'", "unable_retrieve_session": "Sitzung konnte nicht abgerufen werden. Grund: '{exception}'",
"values_mismatch": "Die Werte passen nicht", "values_mismatch": "Die Werte passen nicht zusammen",
"warning": "Warnung:", "warning": "Warnung:",
"websocket_request_expected": "Eine WebSocket Anfrage wurde erwartet", "websocket_request_expected": "Eine WebSocket-Anfrage wurde erwartet",
"deprecated_command": "'{prog} {command}' ist veraltet und wird bald entfernt werden", "deprecated_command": "'{prog} {command}' ist veraltet und wird bald entfernt werden",
"deprecated_command_alias": "'{prog} {old}' ist veraltet und wird bald entfernt werden, benutze '{prog} {new}' stattdessen", "deprecated_command_alias": "'{prog} {old}' ist veraltet und wird bald entfernt werden, benutze '{prog} {new}' stattdessen",
"unknown_group": "Gruppe '{group}' ist unbekannt", "unknown_group": "Gruppe '{group}' ist unbekannt",
"unknown_user": "Benutzer '{user}' ist unbekannt", "unknown_user": "Benutzer '{user}' ist unbekannt",
"info": "Info:", "info": "Info:",
"invalid_token": "Ungültiger Token - bitte authentifizieren", "invalid_token": "Ungültiger Token - bitte authentifizieren",
"corrupted_json": "Beschädigtes JSON gelesen von {ressource:s} (reason: {error:s})", "corrupted_json": "Beschädigtes JSON gelesen von {ressource} (reason: {error})",
"unknown_error_reading_file": "Unbekannter Fehler beim Lesen der Datei {file:s} (reason: {error:s})", "unknown_error_reading_file": "Unbekannter Fehler beim Lesen der Datei {file} (reason: {error})",
"cannot_write_file": "Kann Datei {file:s} nicht schreiben (reason: {error:s})", "cannot_write_file": "Kann Datei {file} nicht schreiben (reason: {error})",
"cannot_open_file": "Kann Datei {file:s} nicht öffnen (reason: {error:s})", "cannot_open_file": "Datei {file} konnte nicht geöffnet werden (Ursache: {error})",
"corrupted_yaml": "Beschädigtes YAML gelesen von {ressource:s} (reason: {error:s})", "corrupted_yaml": "Beschädigtes YAML gelesen von {ressource} (reason: {error})",
"warn_the_user_that_lock_is_acquired": "Der andere Befehl wurde gerade abgeschlossen, starte jetzt diesen Befehl", "warn_the_user_that_lock_is_acquired": "Der andere Befehl wurde gerade abgeschlossen, starte jetzt diesen Befehl",
"warn_the_user_about_waiting_lock_again": "Immer noch wartend...", "warn_the_user_about_waiting_lock_again": "Immer noch wartend...",
"warn_the_user_about_waiting_lock": "Ein anderer YunoHost Befehl läuft gerade, wir warten bis er fertig ist, bevor dieser laufen kann", "warn_the_user_about_waiting_lock": "Ein anderer YunoHost Befehl läuft gerade, wir warten bis er fertig ist, bevor dieser laufen kann",
"command_unknown": "Befehl '{command:s}' unbekannt?", "download_bad_status_code": "{url} lieferte folgende(n) Status Code(s) {code}",
"download_bad_status_code": "{url:s} lieferte folgende(n) Status Code(s) {code:s}", "download_unknown_error": "Fehler beim Herunterladen von Daten von {url}: {error}",
"download_unknown_error": "Fehler beim Herunterladen von Daten von {url:s}: {error:s}", "download_timeout": "{url} brauchte zu lange zum Antworten, hab aufgegeben.",
"download_timeout": "{url:s} brauchte zu lange zum Antworten, hab aufgegeben.", "download_ssl_error": "SSL Fehler beim Verbinden zu {url}",
"download_ssl_error": "SSL Fehler beim Verbinden zu {url:s}", "invalid_url": "Ungültige URL {url} (existiert diese Seite?)",
"invalid_url": "Ungültige URL {url:s} (existiert diese Seite?)", "error_changing_file_permissions": "Fehler beim Ändern der Berechtigungen für {path}: {error}",
"error_changing_file_permissions": "Fehler beim Ändern der Berechtigungen für {path:s}: {error:s}", "error_removing": "Fehler beim Entfernen {path}: {error}",
"error_removing": "Fehler beim Entfernen {path:s}: {error:s}", "error_writing_file": "Fehler beim Schreiben von Datei {file}: {error}",
"error_writing_file": "Fehler beim Schreiben von Datei {file:s}: {error:s}", "corrupted_toml": "Beschädigtes TOML gelesen von {ressource} (reason: {error})",
"corrupted_toml": "Beschädigtes TOML gelesen von {ressource:s} (reason: {error:s})",
"ldap_server_is_down_restart_it": "Der LDAP-Dienst wurde angehalten. Es wird versucht, ihn erneut zu starten...", "ldap_server_is_down_restart_it": "Der LDAP-Dienst wurde angehalten. Es wird versucht, ihn erneut zu starten...",
"session_expired": "Die Sitzung ist abgelaufen. Bitte neuauthentifizieren." "session_expired": "Die Sitzung ist abgelaufen. Bitte authentifizieren Sie sich neu ."
} }

View file

@ -1,24 +1,17 @@
{ {
"argument_required": "Argument '{argument}' is required", "argument_required": "Argument '{argument}' is required",
"authentication_required": "Authentication required", "authentication_required": "Authentication required",
"authentication_required_long": "Authentication is required to perform this action",
"colon": "{}: ", "colon": "{}: ",
"confirm": "Confirm {prompt}", "confirm": "Confirm {prompt}",
"deprecated_command": "'{prog} {command}' is deprecated and will be removed in the future", "deprecated_command": "'{prog} {command}' is deprecated and will be removed in the future",
"deprecated_command_alias": "'{prog} {old}' is deprecated and will be removed in the future, use '{prog} {new}' instead", "deprecated_command_alias": "'{prog} {old}' is deprecated and will be removed in the future, use '{prog} {new}' instead",
"error": "Error:", "error": "Error:",
"file_exists": "File already exists: '{path}'",
"file_not_exist": "File does not exist: '{path}'", "file_not_exist": "File does not exist: '{path}'",
"folder_exists": "Folder already exists: '{path}'", "folder_exists": "Folder already exists: '{path}'",
"folder_not_exist": "Folder does not exist",
"info": "Info:", "info": "Info:",
"instance_already_running": "There is already a YunoHost operation running. Please wait for it to finish before running another one.", "instance_already_running": "There is already a YunoHost operation running. Please wait for it to finish before running another one.",
"invalid_argument": "Invalid argument '{argument}': {error}", "invalid_argument": "Invalid argument '{argument}': {error}",
"invalid_password": "Invalid password",
"invalid_token": "Invalid token - please authenticate",
"invalid_usage": "Invalid usage, pass --help to see help", "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_in": "Logged in",
"logged_out": "Logged out", "logged_out": "Logged out",
"not_logged_in": "You are not logged in", "not_logged_in": "You are not logged in",
@ -29,31 +22,26 @@
"server_already_running": "A server is already running on that port", "server_already_running": "A server is already running on that port",
"success": "Success!", "success": "Success!",
"unable_authenticate": "Unable to authenticate", "unable_authenticate": "Unable to authenticate",
"unable_retrieve_session": "Unable to retrieve the session because '{exception}'",
"session_expired": "The session expired. Please re-authenticate.",
"unknown_group": "Unknown '{group}' group", "unknown_group": "Unknown '{group}' group",
"unknown_user": "Unknown '{user}' user", "unknown_user": "Unknown '{user}' user",
"values_mismatch": "Values don't match", "values_mismatch": "Values don't match",
"info": "Info:",
"warning": "Warning:", "warning": "Warning:",
"websocket_request_expected": "Expected a WebSocket request", "websocket_request_expected": "Expected a WebSocket request",
"cannot_open_file": "Could not open file {file:s} (reason: {error:s})", "cannot_open_file": "Could not open file {file} (reason: {error})",
"cannot_write_file": "Could not write file {file:s} (reason: {error:s})", "cannot_write_file": "Could not write file {file} (reason: {error})",
"unknown_error_reading_file": "Unknown error while trying to read file {file:s} (reason: {error:s})", "unknown_error_reading_file": "Unknown error while trying to read file {file} (reason: {error})",
"corrupted_json": "Corrupted JSON read from {ressource:s} (reason: {error:s})", "corrupted_json": "Corrupted JSON read from {ressource} (reason: {error})",
"corrupted_yaml": "Corrupted YAML read from {ressource:s} (reason: {error:s})", "corrupted_yaml": "Corrupted YAML read from {ressource} (reason: {error})",
"corrupted_toml": "Corrupted TOML read from {ressource:s} (reason: {error:s})", "corrupted_toml": "Corrupted TOML read from {ressource} (reason: {error})",
"error_writing_file": "Error when writing file {file:s}: {error:s}", "error_writing_file": "Error when writing file {file}: {error}",
"error_removing": "Error when removing {path:s}: {error:s}", "error_removing": "Error when removing {path}: {error}",
"error_changing_file_permissions": "Error when changing permissions for {path:s}: {error:s}", "error_changing_file_permissions": "Error when changing permissions for {path}: {error}",
"invalid_url": "Invalid URL {url:s} (does this site exists?)", "invalid_url": "Failed to connect to {url} ... maybe the service is down, or you are not properly connected to the Internet in IPv4/IPv6.",
"download_ssl_error": "SSL error when connecting to {url:s}", "download_ssl_error": "SSL error when connecting to {url}",
"download_timeout": "{url:s} took too long to answer, gave up.", "download_timeout": "{url} took too long to answer, gave up.",
"download_unknown_error": "Error when downloading data from {url:s}: {error:s}", "download_unknown_error": "Error when downloading data from {url}: {error}",
"download_bad_status_code": "{url:s} returned status code {code:s}", "download_bad_status_code": "{url} returned status code {code}",
"command_unknown": "Command '{command:s}' unknown?",
"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": "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_about_waiting_lock_again": "Still waiting...",
"warn_the_user_that_lock_is_acquired": "The other command just completed, now starting this command", "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..."
} }

View file

@ -1,23 +1,22 @@
{ {
"password": "Pasvorto", "password": "Pasvorto",
"colon": "{}: ", "colon": "{}: ",
"warn_the_user_that_lock_is_acquired": "la alia komando ĵus kompletigis, nun komencante ĉi tiun komandon", "warn_the_user_that_lock_is_acquired": "La alia komando ĵus kompletigis, nun komencante ĉi tiun komandon",
"warn_the_user_about_waiting_lock_again": "Ankoraŭ atendanta...", "warn_the_user_about_waiting_lock_again": "Ankoraŭ atendanta...",
"warn_the_user_about_waiting_lock": "Alia komando de YunoHost funkcias ĝuste nun, ni atendas, ke ĝi finiĝos antaŭ ol funkcii ĉi tiu", "warn_the_user_about_waiting_lock": "Alia komando de YunoHost funkcias ĝuste nun, ni atendas, ke ĝi finiĝos antaŭ ol funkcii ĉi tiu",
"command_unknown": "Komando '{command:s}' nekonata?", "download_bad_status_code": "{url} redonita statuskodo {code}",
"download_bad_status_code": "{url:s} redonita statuskodo {code:s}", "download_unknown_error": "Eraro dum elŝutado de datumoj de {url}: {error}",
"download_unknown_error": "Eraro dum elŝutado de datumoj de {url:s}: {error:s}", "download_timeout": "{url} prenis tro da tempo por respondi, rezignis.",
"download_timeout": "{url:s} prenis tro da tempo por respondi, rezignis.", "download_ssl_error": "SSL-eraro dum konekto al {url}",
"download_ssl_error": "SSL-eraro dum konekto al {url:s}", "invalid_url": "Nevalida URL{url} (ĉu ĉi tiu retejo ekzistas?)",
"invalid_url": "Nevalida url {url:s} (ĉu ĉi tiu retejo ekzistas?)", "error_changing_file_permissions": "Eraro dum ŝanĝo de permesoj por {path}: {error}",
"error_changing_file_permissions": "Eraro dum ŝanĝo de permesoj por {path:s}: {error:s}", "error_removing": "Eraro dum la forigo de {path}: {error}",
"error_removing": "Eraro dum la forigo de {path:s}: {error:s}", "error_writing_file": "Eraro skribinte dosieron {file}: {error}",
"error_writing_file": "Eraro skribinte dosieron {file:s}: {error:s}", "corrupted_toml": "Korupta TOML legita el {ressource} (kialo: {error})",
"corrupted_toml": "Korupta toml legita el {ressource:s} (kialo: {error:s})", "corrupted_yaml": "Korupta YAML legita de {ressource} (kialo: {error})",
"corrupted_yaml": "Korupta yaml legita de {ressource:s} (kialo: {error:s})", "corrupted_json": "Koruptita JSON legis de {ressource} (Kialo: {error})",
"corrupted_json": "Koruptita json legita de {ressource:s} (kialo: {error:s})", "unknown_error_reading_file": "Nekonata eraro dum provi legi dosieron {file} (kialo: {error})",
"unknown_error_reading_file": "Nekonata eraro dum provi legi dosieron {file:s} (kialo: {error:s})", "cannot_write_file": "Ne povis skribi dosieron {file} (kialo: {error})",
"cannot_write_file": "Ne povis skribi dosieron {file:s} (kialo: {error:s})",
"cannot_open_file": "Ne povis malfermi dosieron {file: s} (kialo: {error: s})", "cannot_open_file": "Ne povis malfermi dosieron {file: s} (kialo: {error: s})",
"websocket_request_expected": "Atendis ret-peto", "websocket_request_expected": "Atendis ret-peto",
"warning": "Averto:", "warning": "Averto:",
@ -40,19 +39,17 @@
"invalid_argument": "Nevalida argumento '{argument}': {error}", "invalid_argument": "Nevalida argumento '{argument}': {error}",
"instance_already_running": "Jam funkcias YunoHost-operacio. Bonvolu atendi, ke ĝi finiĝos antaŭ ol funkcii alia.", "instance_already_running": "Jam funkcias YunoHost-operacio. Bonvolu atendi, ke ĝi finiĝos antaŭ ol funkcii alia.",
"info": "informoj:", "info": "informoj:",
"folder_not_exist": "Dosierujo ne ekzistas",
"folder_exists": "Dosierujo jam ekzistas: '{path}'", "folder_exists": "Dosierujo jam ekzistas: '{path}'",
"file_not_exist": "Dosiero ne ekzistas: '{path}'", "file_not_exist": "Dosiero ne ekzistas: '{path}'",
"file_exists": "Dosiero jam ekzistas: '{path}'",
"error_see_log": "Eraro okazis. Bonvolu vidi la protokolojn por detaloj, ili troviĝas en /var/log/yunohost/.",
"error": "Eraro:", "error": "Eraro:",
"deprecated_command_alias": "'{prog} {old}' malakceptas kaj estos forigita estonte, uzu anstataŭe '{prog} {new}'", "deprecated_command_alias": "'{prog} {old}' malakceptas kaj estos forigita estonte, uzu anstataŭe '{prog} {new}'",
"deprecated_command": "'{prog} {command}' malakceptas kaj estos forigita estonte", "deprecated_command": "'{prog} {command}' malakceptas kaj estos forigita estonte",
"confirm": "Konfirmu {prompt}", "confirm": "Konfirmu {prompt}",
"authentication_required_long": "Aŭtentigo necesas por plenumi ĉi tiun agon", "authentication_required_long": "Aŭtentigo necesas por plenumi ĉi tiun agon",
"authentication_required": "Aŭtentigo bezonata", "authentication_required": "Aŭtentigo bezonata",
"authentication_profile_required": "Aŭtentigo al la profilo '{profile}' bezonata",
"argument_required": "Argumento '{argument}' estas bezonata", "argument_required": "Argumento '{argument}' estas bezonata",
"logged_out": "Ensalutinta", "logged_out": "Ensalutinta",
"invalid_token": "Nevalida tokeno - bonvolu autentiki" "invalid_token": "Nevalida tokeno - bonvolu autentiki",
"ldap_server_is_down_restart_it": "La LDAP-servo malpliiĝas, provu rekomenci ĝin...",
"session_expired": "La sesio eksvalidiĝis. Bonvolu re-aŭtentikigi."
} }

View file

@ -1,6 +1,5 @@
{ {
"argument_required": "Se requiere el argumento «{argument}»", "argument_required": "Se requiere el argumento «{argument}»",
"authentication_profile_required": "Autentificación requerida para el perfil «{profile}»",
"authentication_required": "Se requiere autentificación", "authentication_required": "Se requiere autentificación",
"authentication_required_long": "Debe autentificarse para realizar esta acción", "authentication_required_long": "Debe autentificarse para realizar esta acción",
"colon": "{}: ", "colon": "{}: ",
@ -8,11 +7,8 @@
"deprecated_command": "«{prog} {command}» está obsoleto y será eliminado en el futuro", "deprecated_command": "«{prog} {command}» está obsoleto y será eliminado en el futuro",
"deprecated_command_alias": "«{prog} {old}» está obsoleto y se eliminará en el futuro, use «{prog} {new}» en su lugar", "deprecated_command_alias": "«{prog} {old}» está obsoleto y se eliminará en el futuro, use «{prog} {new}» en su lugar",
"error": "Error:", "error": "Error:",
"error_see_log": "Ha ocurrido un error. Consulte el registro para obtener más información, localizado en /var/log/yunohost/.",
"file_exists": "El archivo ya existe: «{path}»",
"file_not_exist": "El archivo no existe: «{path}»", "file_not_exist": "El archivo no existe: «{path}»",
"folder_exists": "El directorio ya existe: «{path}»", "folder_exists": "El directorio ya existe: «{path}»",
"folder_not_exist": "La carpeta no existe",
"instance_already_running": "Ya se está ejecutando una instancia de YunoHost. Espere a que termine antes de ejecutar otra.", "instance_already_running": "Ya se está ejecutando una instancia de YunoHost. Espere a que termine antes de ejecutar otra.",
"invalid_argument": "Argumento no válido «{argument}»: {error}", "invalid_argument": "Argumento no válido «{argument}»: {error}",
"invalid_password": "Contraseña no válida", "invalid_password": "Contraseña no válida",
@ -25,7 +21,6 @@
"operation_interrupted": "Operación interrumpida", "operation_interrupted": "Operación interrumpida",
"password": "Contraseña", "password": "Contraseña",
"pattern_not_match": "No coincide con el patrón", "pattern_not_match": "No coincide con el patrón",
"permission_denied": "Permiso denegado",
"root_required": "Solo root puede realizar esta acción", "root_required": "Solo root puede realizar esta acción",
"server_already_running": "Ya se está ejecutando un servidor en ese puerto", "server_already_running": "Ya se está ejecutando un servidor en ese puerto",
"success": "¡Éxito!", "success": "¡Éxito!",
@ -36,22 +31,21 @@
"values_mismatch": "Los valores no coinciden", "values_mismatch": "Los valores no coinciden",
"warning": "Advertencia:", "warning": "Advertencia:",
"websocket_request_expected": "Se esperaba una petición WebSocket", "websocket_request_expected": "Se esperaba una petición WebSocket",
"cannot_open_file": "No se pudo abrir el archivo {file:s} (motivo: {error:s})", "cannot_open_file": "No se pudo abrir el archivo {file} (motivo: {error})",
"cannot_write_file": "No se pudo escribir el archivo {file:s} (motivo: {error:s})", "cannot_write_file": "No se pudo escribir el archivo {file} (motivo: {error})",
"unknown_error_reading_file": "Error desconocido al intentar leer el archivo {file:s} (motivo: {error:s})", "unknown_error_reading_file": "Error desconocido al intentar leer el archivo {file} (motivo: {error})",
"corrupted_json": "Lectura corrupta de JSON desde {ressource:s} (motivo: {error:s})", "corrupted_json": "Lectura corrupta de JSON desde {ressource} (motivo: {error})",
"error_writing_file": "Error al escribir el archivo {file:s}: {error:s}", "error_writing_file": "Error al escribir el archivo {file}: {error}",
"error_removing": "Error al eliminar {path:s}: {error:s}", "error_removing": "Error al eliminar {path}: {error}",
"error_changing_file_permissions": "Error al cambiar los permisos para {path:s}: {error:s}", "error_changing_file_permissions": "Error al cambiar los permisos para {path}: {error}",
"invalid_url": "URL inválida {url:s} (¿Existe este sitio?)", "invalid_url": "URL inválida {url} (¿Existe este sitio?)",
"download_ssl_error": "Error SSL al conectar con {url:s}", "download_ssl_error": "Error SSL al conectar con {url}",
"download_timeout": "{url:s} tardó demasiado en responder, abandono.", "download_timeout": "{url} tardó demasiado en responder, abandono.",
"download_unknown_error": "Error al descargar datos desde {url:s} : {error:s}", "download_unknown_error": "Error al descargar datos desde {url} : {error}",
"download_bad_status_code": "{url:s} devolvió el código de estado {code:s}", "download_bad_status_code": "{url} devolvió el código de estado {code}",
"command_unknown": "¿Orden «{command:s}» desconocida?", "corrupted_yaml": "Lectura corrupta de YAML desde {ressource} (motivo: {error})",
"corrupted_yaml": "Lectura corrupta de YAML desde {ressource:s} (motivo: {error:s})",
"info": "Información:", "info": "Información:",
"corrupted_toml": "Lectura corrupta de TOML desde {ressource:s} (motivo: {error:s})", "corrupted_toml": "Lectura corrupta de TOML desde {ressource} (motivo: {error})",
"warn_the_user_that_lock_is_acquired": "La otra orden recién terminó, iniciando esta orden ahora", "warn_the_user_that_lock_is_acquired": "La otra orden recién terminó, iniciando esta orden ahora",
"warn_the_user_about_waiting_lock_again": "Aún esperando...", "warn_the_user_about_waiting_lock_again": "Aún esperando...",
"warn_the_user_about_waiting_lock": "Otra orden de YunoHost se está ejecutando ahora, estamos esperando a que termine antes de ejecutar esta", "warn_the_user_about_waiting_lock": "Otra orden de YunoHost se está ejecutando ahora, estamos esperando a que termine antes de ejecutar esta",

47
locales/fa.json Normal file
View file

@ -0,0 +1,47 @@
{
"logged_in": "وارد شده",
"invalid_usage": "استفاده نامعتبر ، برای مشاهده راهنما --help را ارسال کنید",
"invalid_argument": "استدلال نامعتبر '{argument}': {error}",
"instance_already_running": "در حال حاضر یک عملیات YunoHost در حال اجرا است. لطفاً قبل از اجرای یکی دیگر ، منتظر بمانید تا آن به پایان برسد.",
"info": "اطلاعات:",
"folder_exists": "پوشه موجود است: '{path}'",
"file_not_exist": "فایل وجود ندارد: '{path}'",
"error": "خطا:",
"deprecated_command_alias": "'{prog} {old}' منسوخ شده است و در آینده حذف خواهد شد ، بجای آن از '{prog} {new}' استفاده کنید",
"deprecated_command": "'{prog} {command}' منسوخ شده است و در آینده حذف خواهد شد",
"confirm": "تأیید {prompt}",
"colon": "{}: ",
"authentication_required": "احراز هویّت الزامی است",
"argument_required": "استدلال '{argument}' ضروری است",
"password": "کلمه عبور",
"warn_the_user_that_lock_is_acquired": "فرمان دیگر به تازگی تکمیل شده است ، اکنون این دستور را شروع کنید",
"warn_the_user_about_waiting_lock_again": "هنوز در انتظار...",
"warn_the_user_about_waiting_lock": "یکی دیگر از دستورات YunoHost در حال اجرا است ، ما منتظر هستیم تا قبل از اجرای این دستور به پایان برسد",
"download_bad_status_code": "{url} کد وضعیّت بازگشتی {code}",
"download_unknown_error": "خطا هنگام بارگیری داده ها از {url}: {error}",
"download_timeout": "پاسخ {url} خیلی طول کشید ، منصرف شو.",
"download_ssl_error": "خطای SSL هنگام اتصال به {url}",
"invalid_url": "اتصال به {url} انجام نشد ... شاید سرویس خاموش باشد یا در IPv4/IPv6 به درستی به اینترنت متصل نشده باشید.",
"error_changing_file_permissions": "خطا هنگام تغییر مجوزهای {path}: {error}",
"error_removing": "خطا هنگام حذف {path}: {error}",
"error_writing_file": "خطا هنگام نوشتن فایل {file}: {error}",
"corrupted_toml": "TOML خراب از {ressource} (دلیل: {error})",
"corrupted_yaml": "YAML خراب از {ressource} (دلیل: {error})",
"corrupted_json": "جی سان خراب شده از {ressource} میخواند (دلیل: {error})",
"unknown_error_reading_file": "خطای ناشناخته هنگام تلاش برای خواندن فایل {file} (دلیل: {error})",
"cannot_write_file": "نمی توان فایل {file} را نوشت (دلیل: {error})",
"cannot_open_file": "فایل {file} باز نشد (دلیل: {error})",
"websocket_request_expected": "در انتظار درخواست وب سوکت",
"warning": "هشدار:",
"values_mismatch": "مقدار ها مطابقت ندارند",
"unknown_user": "کاربر'{user}' ناشناخته",
"unknown_group": "گروه '{group}' ناشناخته",
"unable_authenticate": "احراز هویّت امکان پذیر نیست",
"success": "موفقیّت!",
"server_already_running": "در حال حاضر یک سرور روی آن پورت کار می کند",
"root_required": "برای انجام این عمل باید کاربر ریشه باشید",
"pattern_not_match": "با الگو مطابقت ندارد",
"operation_interrupted": "عملیات قطع شد",
"not_logged_in": "‌شما وارد نشده اید",
"logged_out": "خارج شده"
}

View file

@ -1,18 +1,14 @@
{ {
"argument_required": "Largument '{argument}' est requis", "argument_required": "Largument '{argument}' est requis",
"authentication_profile_required": "Lauthentification au profil '{profile}' est requise",
"authentication_required": "Authentification requise", "authentication_required": "Authentification requise",
"authentication_required_long": "Lauthentification est requise pour exécuter cette action", "authentication_required_long": "Lauthentification est requise pour exécuter cette action",
"colon": "{} : ", "colon": "{} : ",
"confirm": "Confirmez : {prompt}", "confirm": "Confirmez {prompt}",
"deprecated_command": "'{prog} {command}' est déprécié et sera bientôt supprimé", "deprecated_command": "'{prog} {command}' est déprécié et sera bientôt supprimé",
"deprecated_command_alias": "'{prog} {old}' est déprécié et sera bientôt supprimé, utilisez '{prog} {new}' à la place", "deprecated_command_alias": "'{prog} {old}' est déprécié et sera bientôt supprimé, utilisez '{prog} {new}' à la place",
"error": "Erreur :", "error": "Erreur :",
"error_see_log": "Une erreur est survenue. Veuillez consulter les journaux pour plus de détails, ils sont situés dans /var/log/yunohost/.",
"file_exists": "Le fichier existe déjà : '{path}'",
"file_not_exist": "Le fichier '{path}' nexiste pas", "file_not_exist": "Le fichier '{path}' nexiste pas",
"folder_exists": "Le dossier existe déjà : '{path}'", "folder_exists": "Le dossier existe déjà : '{path}'",
"folder_not_exist": "Le dossier nexiste pas",
"instance_already_running": "Une instance est déjà en cours dexécution, merci d'attendre sa fin avant d'en lancer une autre.", "instance_already_running": "Une instance est déjà en cours dexécution, merci d'attendre sa fin avant d'en lancer une autre.",
"invalid_argument": "Argument '{argument}' incorrect : {error}", "invalid_argument": "Argument '{argument}' incorrect : {error}",
"invalid_password": "Mot de passe incorrect", "invalid_password": "Mot de passe incorrect",
@ -25,7 +21,6 @@
"operation_interrupted": "Opération interrompue", "operation_interrupted": "Opération interrompue",
"password": "Mot de passe", "password": "Mot de passe",
"pattern_not_match": "Ne correspond pas au motif", "pattern_not_match": "Ne correspond pas au motif",
"permission_denied": "Permission refusée",
"root_required": "Vous devez être super-utilisateur pour exécuter cette action", "root_required": "Vous devez être super-utilisateur pour exécuter cette action",
"server_already_running": "Un serveur est déjà en cours dexécution sur ce port", "server_already_running": "Un serveur est déjà en cours dexécution sur ce port",
"success": "Succès !", "success": "Succès !",
@ -36,22 +31,21 @@
"values_mismatch": "Les valeurs ne correspondent pas", "values_mismatch": "Les valeurs ne correspondent pas",
"warning": "Attention :", "warning": "Attention :",
"websocket_request_expected": "Une requête WebSocket est attendue", "websocket_request_expected": "Une requête WebSocket est attendue",
"cannot_open_file": "Impossible douvrir le fichier {file:s} (raison : {error:s})", "cannot_open_file": "Impossible douvrir le fichier {file} (raison : {error})",
"cannot_write_file": "Ne peut pas écrire le fichier {file:s} (raison : {error:s})", "cannot_write_file": "Ne peut pas écrire le fichier {file} (raison : {error})",
"unknown_error_reading_file": "Erreur inconnue en essayant de lire le fichier {file:s} (cause:{error:s})", "unknown_error_reading_file": "Erreur inconnue en essayant de lire le fichier {file} (cause:{error})",
"corrupted_json": "Fichier JSON corrompu en lecture depuis {ressource:s} (raison : {error:s})", "corrupted_json": "Fichier JSON corrompu en lecture depuis {ressource} (raison : {error})",
"error_writing_file": "Erreur en écrivant le fichier {file:s} : {error:s}", "error_writing_file": "Erreur en écrivant le fichier {file} : {error}",
"error_removing": "Erreur lors de la suppression {path:s} : {error:s}", "error_removing": "Erreur lors de la suppression {path} : {error}",
"error_changing_file_permissions": "Erreur lors de la modification des autorisations pour {path:s} : {error:s}", "error_changing_file_permissions": "Erreur lors de la modification des autorisations pour {path} : {error}",
"invalid_url": "URL {url:s} invalide : ce site existe-t-il ?", "invalid_url": "Impossible de se connecter à {url} ... peut-être que le service est hors service/indisponible/interrompu, ou que vous n'êtes pas correctement connecté à Internet en IPv4/IPv6.",
"download_ssl_error": "Erreur SSL lors de la connexion à {url:s}", "download_ssl_error": "Erreur SSL lors de la connexion à {url}",
"download_timeout": "{url:s} a pris trop de temps pour répondre : abandon.", "download_timeout": "{url} a pris trop de temps pour répondre : abandon.",
"download_unknown_error": "Erreur lors du téléchargement des données à partir de {url:s} : {error:s}", "download_unknown_error": "Erreur lors du téléchargement des données à partir de {url} : {error}",
"download_bad_status_code": "{url:s} renvoie le code d'état {code:s}", "download_bad_status_code": "{url} renvoie le code d'état {code}",
"command_unknown": "Commande '{command:s}' inconnue ?", "corrupted_yaml": "Fichier YAML corrompu en lecture depuis {ressource} (raison : {error})",
"corrupted_yaml": "Fichier YAML corrompu en lecture depuis {ressource:s} (raison : {error:s})",
"info": "Info :", "info": "Info :",
"corrupted_toml": "Fichier TOML corrompu en lecture depuis {ressource:s} (cause : {error:s})", "corrupted_toml": "Fichier TOML corrompu en lecture depuis {ressource} (cause : {error})",
"warn_the_user_about_waiting_lock": "Une autre commande YunoHost est actuellement en cours, nous attendons qu'elle se termine avant de démarrer celle là", "warn_the_user_about_waiting_lock": "Une autre commande YunoHost est actuellement en cours, nous attendons qu'elle se termine avant de démarrer celle là",
"warn_the_user_about_waiting_lock_again": "Toujours en attente...", "warn_the_user_about_waiting_lock_again": "Toujours en attente...",
"warn_the_user_that_lock_is_acquired": "La commande précédente vient de se terminer, lancement de cette nouvelle commande", "warn_the_user_that_lock_is_acquired": "La commande précédente vient de se terminer, lancement de cette nouvelle commande",

View file

@ -6,10 +6,8 @@
"invalid_argument": "Argumento non válido '{argument}': {error}", "invalid_argument": "Argumento non válido '{argument}': {error}",
"instance_already_running": "Hai unha operación de YunoHost en execución. Por favor agarda a que remate antes de realizar unha nova.", "instance_already_running": "Hai unha operación de YunoHost en execución. Por favor agarda a que remate antes de realizar unha nova.",
"info": "Info:", "info": "Info:",
"folder_not_exist": "O cartafol non existe",
"folder_exists": "Xa existe o cartafol: '{path}'", "folder_exists": "Xa existe o cartafol: '{path}'",
"file_not_exist": "Non existe o ficheiro: '{path}'", "file_not_exist": "Non existe o ficheiro: '{path}'",
"file_exists": "Xa existe o ficheiro: '{path}'",
"error": "Erro:", "error": "Erro:",
"deprecated_command_alias": "'{prog} {old}' xa non se utiliza e será eliminado no futuro, usa '{prog} {new}' no seu lugar", "deprecated_command_alias": "'{prog} {old}' xa non se utiliza e será eliminado no futuro, usa '{prog} {new}' no seu lugar",
"deprecated_command": "'{prog} {command}' xa non se utiliza e xa non se usará no futuro", "deprecated_command": "'{prog} {command}' xa non se utiliza e xa non se usará no futuro",
@ -39,20 +37,19 @@
"warn_the_user_that_lock_is_acquired": "O outro comando rematou, agora executarase este", "warn_the_user_that_lock_is_acquired": "O outro comando rematou, agora executarase este",
"warn_the_user_about_waiting_lock_again": "Agardando...", "warn_the_user_about_waiting_lock_again": "Agardando...",
"warn_the_user_about_waiting_lock": "Estase executando outro comando de YunoHost neste intre, estamos agardando a que remate para executar este", "warn_the_user_about_waiting_lock": "Estase executando outro comando de YunoHost neste intre, estamos agardando a que remate para executar este",
"command_unknown": "Comando '{command:s}' descoñecido?", "download_bad_status_code": "{url} devolveu o código de estado {code}",
"download_bad_status_code": "{url:s} devolveu o código de estado {code:s}", "download_unknown_error": "Erro ao descargar os datos desde {url}: {error}",
"download_unknown_error": "Erro ao descargar os datos desde {url:s}: {error:s}", "download_timeout": "{url} está tardando en responder, deixámolo.",
"download_timeout": "{url:s} está tardando en responder, deixámolo.", "download_ssl_error": "Erro SSL ao conectar con {url}",
"download_ssl_error": "Erro SSL ao conectar con {url:s}", "invalid_url": "Fallou a conexión con {url} ... pode que o servizo esté caído, ou que non teñas conexión a Internet con IPv4/IPv6.",
"invalid_url": "URL non válido {url:s} (existe esta web?)", "error_changing_file_permissions": "Erro ao cambiar os permisos de {path}: {error}",
"error_changing_file_permissions": "Erro ao cambiar os permisos de {path:s}: {error:s}", "error_removing": "Erro ao eliminar {path}: {error}",
"error_removing": "Erro ao eliminar {path:s}: {error:s}", "error_writing_file": "Erro ao escribir o ficheiro {file}: {error}",
"error_writing_file": "Erro ao escribir o ficheiro {file:s}: {error:s}", "corrupted_toml": "Lectura corrupta de datos TOML de {ressource} (razón: {error})",
"corrupted_toml": "Lectura corrupta de datos TOML de {ressource:s} (razón: {error:s})", "corrupted_yaml": "Lectura corrupta dos datos YAML de {ressource} (razón: {error})",
"corrupted_yaml": "Lectura corrupta dos datos YAML de {ressource:s} (razón: {error:s})", "corrupted_json": "Lectura corrupta dos datos JSON de {ressource} (razón: {error})",
"corrupted_json": "Lectura corrupta dos datos JSON de {ressource:s} (razón: {error:s})", "unknown_error_reading_file": "Erro descoñecido ao intentar ler o ficheiro {file} (razón: {error})",
"unknown_error_reading_file": "Erro descoñecido ao intentar ler o ficheiro {file:s} (razón: {error:s})", "cannot_write_file": "Non se puido escribir o ficheiro {file} (razón: {error})",
"cannot_write_file": "Non se puido escribir o ficheiro {file:s} (razón: {error:s})", "cannot_open_file": "Non se puido abrir o ficheiro {file} (razón: {error})",
"cannot_open_file": "Non se puido abrir o ficheiro {file:s} (razón: {error:s})",
"websocket_request_expected": "Agardábase unha solicitude WebSocket" "websocket_request_expected": "Agardábase unha solicitude WebSocket"
} }

View file

@ -1,6 +1,5 @@
{ {
"argument_required": "तर्क '{argument}' आवश्यक है", "argument_required": "तर्क '{argument}' आवश्यक है",
"authentication_profile_required": "{profile} प्रोफ़ाइल के लिए प्रमाणीकरण की आवश्यकता है",
"authentication_required": "प्रमाणीकरण आवश्यक", "authentication_required": "प्रमाणीकरण आवश्यक",
"authentication_required_long": "इस कार्य को करने के लिए प्रमाणीकरण आवश्यक है", "authentication_required_long": "इस कार्य को करने के लिए प्रमाणीकरण आवश्यक है",
"colon": "{}: ", "colon": "{}: ",
@ -8,11 +7,8 @@
"deprecated_command": "'{prog}' '{command}' का प्रयोग न करे, भविष्य में इसे हटा दिया जाएगा", "deprecated_command": "'{prog}' '{command}' का प्रयोग न करे, भविष्य में इसे हटा दिया जाएगा",
"deprecated_command_alias": "'{prog} {old}' अब पुराना हो गया है और इसे भविष्य में हटा दिया जाएगा, इस की जगह '{prog} {new}' का प्रयोग करें", "deprecated_command_alias": "'{prog} {old}' अब पुराना हो गया है और इसे भविष्य में हटा दिया जाएगा, इस की जगह '{prog} {new}' का प्रयोग करें",
"error": "गलती:", "error": "गलती:",
"error_see_log": "एक त्रुटि पाई गई। कृपया विवरण के लिए लॉग देखें।",
"file_exists": "फ़ाइल पहले से ही मौजूद है:'{path}'",
"file_not_exist": "फ़ाइल मौजूद नहीं है: '{path}'", "file_not_exist": "फ़ाइल मौजूद नहीं है: '{path}'",
"folder_exists": "फ़ोल्डर में पहले से ही मौजूद है: '{path}'", "folder_exists": "फ़ोल्डर में पहले से ही मौजूद है: '{path}'",
"folder_not_exist": "फ़ोल्डर मौजूद नहीं है",
"instance_already_running": "यूनोहोस्ट का एक कार्य पहले से चल रहा है। कृपया इस कार्य के समाप्त होने का इंतज़ार करें।", "instance_already_running": "यूनोहोस्ट का एक कार्य पहले से चल रहा है। कृपया इस कार्य के समाप्त होने का इंतज़ार करें।",
"invalid_argument": "अवैध तर्क '{argument}':'{error}'", "invalid_argument": "अवैध तर्क '{argument}':'{error}'",
"invalid_password": "अवैध पासवर्ड", "invalid_password": "अवैध पासवर्ड",
@ -25,7 +21,6 @@
"operation_interrupted": "कार्य बाधित", "operation_interrupted": "कार्य बाधित",
"password": "पासवर्ड", "password": "पासवर्ड",
"pattern_not_match": "पैटर्न मेल नहीं खता है।", "pattern_not_match": "पैटर्न मेल नहीं खता है।",
"permission_denied": "अनुमति से इनकार।",
"root_required": "इस कार्य को करने के लिए ,आप का root होना आवक्षक है।", "root_required": "इस कार्य को करने के लिए ,आप का root होना आवक्षक है।",
"server_already_running": "कोई सर्वर पहले से ही इस पोर्ट पर चल रहा है।", "server_already_running": "कोई सर्वर पहले से ही इस पोर्ट पर चल रहा है।",
"success": "सफलता!", "success": "सफलता!",

View file

@ -1,9 +1,9 @@
{ {
"logged_out": "Kilépett", "logged_out": "Kilépett",
"password": "Jelszó", "password": "Jelszó",
"download_timeout": "{url:s} régóta nem válaszol, folyamat megszakítva.", "download_timeout": "{url} régóta nem válaszol, folyamat megszakítva.",
"invalid_url": "Helytelen URL: {url:s} (biztos létezik az oldal?)", "invalid_url": "Helytelen URL: {url} (biztos létezik az oldal?)",
"cannot_open_file": "{file:s} megnyitása sikertelen (Oka: {error:s})", "cannot_open_file": "{file} megnyitása sikertelen (Oka: {error})",
"unknown_user": "Ismeretlen felhasználó: '{user}'", "unknown_user": "Ismeretlen felhasználó: '{user}'",
"unknown_group": "Ismeretlen csoport: '{group}'", "unknown_group": "Ismeretlen csoport: '{group}'",
"server_already_running": "Egy szerver már fut ezen a porton", "server_already_running": "Egy szerver már fut ezen a porton",
@ -14,6 +14,5 @@
"invalid_password": "Helytelen jelszó", "invalid_password": "Helytelen jelszó",
"info": "Információ:", "info": "Információ:",
"file_not_exist": "A fájl nem létezik: '{path}'", "file_not_exist": "A fájl nem létezik: '{path}'",
"file_exists": "A fájl már létezik: '{path}'",
"error": "Hiba:" "error": "Hiba:"
} }

View file

@ -2,7 +2,6 @@
"logged_out": "Disconnesso", "logged_out": "Disconnesso",
"password": "Password", "password": "Password",
"argument_required": "L'argomento '{argument}' è richiesto", "argument_required": "L'argomento '{argument}' è richiesto",
"authentication_profile_required": "Autenticazione al profilo '{profile}' richiesta",
"authentication_required": "Autenticazione richiesta", "authentication_required": "Autenticazione richiesta",
"authentication_required_long": "Autenticazione richiesta per eseguire questa azione", "authentication_required_long": "Autenticazione richiesta per eseguire questa azione",
"colon": "{}: ", "colon": "{}: ",
@ -10,11 +9,8 @@
"deprecated_command": "'{prog} {command}' è deprecato e sarà rimosso in futuro", "deprecated_command": "'{prog} {command}' è deprecato e sarà rimosso in futuro",
"deprecated_command_alias": "'{prog} {old}' è deprecato e sarà rimosso in futuro, usa invece '{prog} {new}'", "deprecated_command_alias": "'{prog} {old}' è deprecato e sarà rimosso in futuro, usa invece '{prog} {new}'",
"error": "Errore:", "error": "Errore:",
"error_see_log": "Si è verificato un errore. Per favore controlla i registri per i dettagli, sono salvati in /var/log/yunohost/.",
"file_exists": "Il file esiste già: '{path}'",
"file_not_exist": "Il file non esiste: '{path}'", "file_not_exist": "Il file non esiste: '{path}'",
"folder_exists": "La cartella esiste già: '{path}'", "folder_exists": "La cartella esiste già: '{path}'",
"folder_not_exist": "La cartella non esiste",
"instance_already_running": "Esiste già un'operazione YunoHost in esecuzione. Attendi il completamento prima di eseguirne un altro.", "instance_already_running": "Esiste già un'operazione YunoHost in esecuzione. Attendi il completamento prima di eseguirne un altro.",
"invalid_argument": "Argomento non valido '{argument}': {error}", "invalid_argument": "Argomento non valido '{argument}': {error}",
"invalid_password": "Password non valida", "invalid_password": "Password non valida",
@ -25,7 +21,6 @@
"not_logged_in": "Non hai effettuato l'accesso", "not_logged_in": "Non hai effettuato l'accesso",
"operation_interrupted": "Operazione interrotta", "operation_interrupted": "Operazione interrotta",
"pattern_not_match": "Non corrisponde al modello", "pattern_not_match": "Non corrisponde al modello",
"permission_denied": "Permesso negato",
"root_required": "Devi essere root per eseguire questa azione", "root_required": "Devi essere root per eseguire questa azione",
"server_already_running": "Un server è già in esecuzione su quella porta", "server_already_running": "Un server è già in esecuzione su quella porta",
"success": "Riuscito!", "success": "Riuscito!",
@ -36,25 +31,24 @@
"values_mismatch": "I valori non corrispondono", "values_mismatch": "I valori non corrispondono",
"warning": "Attenzione:", "warning": "Attenzione:",
"websocket_request_expected": "Richiesta WebSocket attesa", "websocket_request_expected": "Richiesta WebSocket attesa",
"cannot_open_file": "Impossibile aprire il file {file:s} (motivo: {error:s})", "cannot_open_file": "Impossibile aprire il file {file} (motivo: {error})",
"cannot_write_file": "Impossibile scrivere il file {file:s} (motivo: {error:s})", "cannot_write_file": "Impossibile scrivere il file {file} (motivo: {error})",
"unknown_error_reading_file": "Errore sconosciuto durante il tentativo di leggere il file {file:s} (motivo: {errore:s})", "unknown_error_reading_file": "Errore sconosciuto durante il tentativo di leggere il file {file} (motivo: {error})",
"corrupted_json": "Lettura JSON corrotta da {resource:s} (motivo: {error:s})", "corrupted_json": "Lettura JSON corrotta da {ressource} (motivo: {error})",
"corrupted_yaml": "Lettura YAML corrotta da {resource:s} (motivo: {error:s})", "corrupted_yaml": "Lettura YAML corrotta da {ressource} (motivo: {error})",
"error_writing_file": "Errore durante la scrittura del file {file:s}: {error:s}", "error_writing_file": "Errore durante la scrittura del file {file}: {error}",
"error_removing": "Errore durante la rimozione {path:s}: {error:s}", "error_removing": "Errore durante la rimozione {path}: {error}",
"error_changing_file_permissions": "Errore durante il cambio di permessi per {path:s}: {error:s}", "error_changing_file_permissions": "Errore durante il cambio di permessi per {path}: {error}",
"invalid_url": "URL non valido {url:s} (il sito esiste?)", "invalid_url": "URL non valido {url} (il sito esiste?)",
"download_ssl_error": "Errore SSL durante la connessione a {url:s}", "download_ssl_error": "Errore SSL durante la connessione a {url}",
"download_timeout": "{url:s} ci ha messo troppo a rispondere, abbandonato.", "download_timeout": "{url} ci ha messo troppo a rispondere, abbandonato.",
"download_unknown_error": "Errore durante il download di dati da {url:s} : {error:s}", "download_unknown_error": "Errore durante il download di dati da {url} : {error}",
"download_bad_status_code": "{url:s} ha restituito il codice di stato {code:s}", "download_bad_status_code": "{url} ha restituito il codice di stato {code}",
"command_unknown": "Comando '{command:s}' sconosciuto?",
"info": "Info:", "info": "Info:",
"warn_the_user_that_lock_is_acquired": "L'altro comando è appena completato, ora avvio questo comando", "warn_the_user_that_lock_is_acquired": "L'altro comando è appena completato, ora avvio questo comando",
"warn_the_user_about_waiting_lock_again": "Sto ancora aspettando ...", "warn_the_user_about_waiting_lock_again": "Sto ancora aspettando ...",
"warn_the_user_about_waiting_lock": "Un altro comando YunoHost è in esecuzione in questo momento, stiamo aspettando che finisca prima di eseguire questo", "warn_the_user_about_waiting_lock": "Un altro comando YunoHost è in esecuzione in questo momento, stiamo aspettando che finisca prima di eseguire questo",
"corrupted_toml": "TOML corrotto da {ressource:s} (motivo: {errore:s})", "corrupted_toml": "TOML corrotto da {ressource} (motivo: {error})",
"invalid_token": "Token non valido: autenticare", "invalid_token": "Token non valido: autenticare",
"session_expired": "La sessione è terminata. Sei pregato di autenticarti nuovamente.", "session_expired": "La sessione è terminata. Sei pregato di autenticarti nuovamente.",
"ldap_server_is_down_restart_it": "Il servizio LDAP è terminato, provo a riavviarlo..." "ldap_server_is_down_restart_it": "Il servizio LDAP è terminato, provo a riavviarlo..."

View file

@ -4,7 +4,7 @@
"websocket_request_expected": "Forventet en WebSocket-forespørsel", "websocket_request_expected": "Forventet en WebSocket-forespørsel",
"warning": "Advarsel:", "warning": "Advarsel:",
"values_mismatch": "Verdiene samsvarer ikke", "values_mismatch": "Verdiene samsvarer ikke",
"unknown_user": "Ukjent '{group}' bruker", "unknown_user": "Ukjent '{user}' bruker",
"unknown_group": "Ukjent '{group}' gruppe", "unknown_group": "Ukjent '{group}' gruppe",
"unable_authenticate": "Kunne ikke identitetsbekrefte", "unable_authenticate": "Kunne ikke identitetsbekrefte",
"success": "Vellykket.", "success": "Vellykket.",
@ -13,7 +13,6 @@
"logged_in": "Innlogget", "logged_in": "Innlogget",
"invalid_password": "Ugyldig passord", "invalid_password": "Ugyldig passord",
"info": "Info:", "info": "Info:",
"file_exists": "Filen finnes allerede: '{path}'",
"error": "Feil:", "error": "Feil:",
"confirm": "Bekreft {prompt}", "confirm": "Bekreft {prompt}",
"colon": "{}: ", "colon": "{}: ",

View file

@ -1,16 +1,12 @@
{ {
"argument_required": "Argument {argument} is vereist", "argument_required": "Argument {argument} is vereist",
"authentication_profile_required": "Authenticatie tot profiel '{profile}' is vereist",
"authentication_required": "Aanmelding vereist", "authentication_required": "Aanmelding vereist",
"authentication_required_long": "Aanmelding is vereist om deze actie uit te voeren", "authentication_required_long": "Aanmelding is vereist om deze actie uit te voeren",
"colon": "{}: ", "colon": "{}: ",
"confirm": "Bevestig {prompt}", "confirm": "Bevestig {prompt}",
"error": "Fout:", "error": "Fout:",
"error_see_log": "Er is een fout opgetreden, zie logboek voor meer informatie. Je kan deze vinden in /var/log/yunohost/.",
"file_exists": "Kan '{path}' niet aanmaken: bestand bestaat al",
"file_not_exist": "Bestand bestaat niet: '{path}'", "file_not_exist": "Bestand bestaat niet: '{path}'",
"folder_exists": "Deze map bestaat al: '{path}'", "folder_exists": "Deze map bestaat al: '{path}'",
"folder_not_exist": "Map bestaat niet",
"instance_already_running": "Er is al een instantie actief, bedankt om te wachten tot deze afgesloten is alvorens een andere te starten.", "instance_already_running": "Er is al een instantie actief, bedankt om te wachten tot deze afgesloten is alvorens een andere te starten.",
"invalid_argument": "Ongeldig argument '{argument}': {error}", "invalid_argument": "Ongeldig argument '{argument}': {error}",
"invalid_password": "Ongeldig wachtwoord", "invalid_password": "Ongeldig wachtwoord",
@ -23,7 +19,6 @@
"operation_interrupted": "Operatie onderbroken", "operation_interrupted": "Operatie onderbroken",
"password": "Wachtwoord", "password": "Wachtwoord",
"pattern_not_match": "Past niet in het patroon", "pattern_not_match": "Past niet in het patroon",
"permission_denied": "Toegang geweigerd",
"root_required": "Je moet root zijn om deze actie uit te voeren", "root_required": "Je moet root zijn om deze actie uit te voeren",
"server_already_running": "Er is al een server actief op die poort", "server_already_running": "Er is al een server actief op die poort",
"success": "Succes!", "success": "Succes!",
@ -36,24 +31,23 @@
"deprecated_command_alias": "'{prog} {old}' is verouderd en wordt binnenkort verwijderd, gebruik in de plaats '{prog} {new}'", "deprecated_command_alias": "'{prog} {old}' is verouderd en wordt binnenkort verwijderd, gebruik in de plaats '{prog} {new}'",
"unknown_group": "Groep '{group}' is onbekend", "unknown_group": "Groep '{group}' is onbekend",
"unknown_user": "Gebruiker '{user}' is onbekend", "unknown_user": "Gebruiker '{user}' is onbekend",
"cannot_open_file": "Niet mogelijk om bestand {file:s} te openen (reden: {error:s})", "cannot_open_file": "Niet mogelijk om bestand {file} te openen (reden: {error})",
"cannot_write_file": "Niet gelukt om bestand {file:s} te schrijven (reden: {error:s})", "cannot_write_file": "Niet gelukt om bestand {file} te schrijven (reden: {error})",
"unknown_error_reading_file": "Ongekende fout tijdens het lezen van bestand {file:s} (cause:{error:s})", "unknown_error_reading_file": "Ongekende fout tijdens het lezen van bestand {file} (cause:{error})",
"corrupted_json": "Corrupte json gelezen van {ressource:s} (reden: {error:s})", "corrupted_json": "Corrupte json gelezen van {ressource} (reden: {error})",
"error_writing_file": "Fout tijdens het schrijven van bestand {file:s}: {error:s}", "error_writing_file": "Fout tijdens het schrijven van bestand {file}: {error}",
"error_removing": "Fout tijdens het verwijderen van {path:s}: {error:s}", "error_removing": "Fout tijdens het verwijderen van {path}: {error}",
"error_changing_file_permissions": "Fout tijdens het veranderen van machtiging voor {path:s}: {error:s}", "error_changing_file_permissions": "Fout tijdens het veranderen van machtiging voor {path}: {error}",
"invalid_url": "Ongeldige URL {url:s} (bestaat deze website?)", "invalid_url": "Ongeldige URL {url} (bestaat deze website?)",
"download_ssl_error": "SSL fout gedurende verbinding met {url:s}", "download_ssl_error": "SSL fout gedurende verbinding met {url}",
"download_timeout": "{url:s} neemt te veel tijd om te antwoorden, we geven het op.", "download_timeout": "{url} neemt te veel tijd om te antwoorden, we geven het op.",
"download_unknown_error": "Fout tijdens het downloaden van data van {url:s}: {error:s}", "download_unknown_error": "Fout tijdens het downloaden van data van {url}: {error}",
"download_bad_status_code": "{url:s} stuurt status code {code:s}", "download_bad_status_code": "{url} stuurt status code {code}",
"command_unknown": "Opdracht '{command:s}' ongekend ?",
"warn_the_user_that_lock_is_acquired": "de andere opdracht is zojuist voltooid en start nu deze opdracht", "warn_the_user_that_lock_is_acquired": "de andere opdracht is zojuist voltooid en start nu deze opdracht",
"warn_the_user_about_waiting_lock_again": "Nog steeds aan het wachten...", "warn_the_user_about_waiting_lock_again": "Nog steeds aan het wachten...",
"warn_the_user_about_waiting_lock": "Een ander YunoHost commando wordt uitgevoerd, we wachten tot het gedaan is alovrens dit te starten", "warn_the_user_about_waiting_lock": "Een ander YunoHost commando wordt uitgevoerd, we wachten tot het gedaan is alovrens dit te starten",
"corrupted_toml": "Ongeldige TOML werd gelezen op {ressource:s} (reason: {error:s})", "corrupted_toml": "Ongeldige TOML werd gelezen op {ressource} (reason: {error})",
"corrupted_yaml": "Ongeldig YAML bestand op {ressource:s} (reason: {error:s})", "corrupted_yaml": "Ongeldig YAML bestand op {ressource} (reason: {error})",
"invalid_token": "Ongeldig token - gelieve in te loggen", "invalid_token": "Ongeldig token - gelieve in te loggen",
"info": "Ter info:" "info": "Ter info:"
} }

View file

@ -1,6 +1,5 @@
{ {
"argument_required": "Largument {argument} es requesit", "argument_required": "Largument {argument} es requesit",
"authentication_profile_required": "Lidentificacion del perfil {profile} es requesida",
"authentication_required": "Autentificacion requesida", "authentication_required": "Autentificacion requesida",
"authentication_required_long": "Una autentificacion es requesida per acomplir aquesta accion", "authentication_required_long": "Una autentificacion es requesida per acomplir aquesta accion",
"logged_in": "Connectat", "logged_in": "Connectat",
@ -11,18 +10,14 @@
"deprecated_command": "« {prog} {command} » es despreciat e serà lèu suprimit", "deprecated_command": "« {prog} {command} » es despreciat e serà lèu suprimit",
"deprecated_command_alias": "« {prog} {old} » es despreciat e serà lèu suprimit, utilizatz « {prog} {new} » allòc", "deprecated_command_alias": "« {prog} {old} » es despreciat e serà lèu suprimit, utilizatz « {prog} {new} » allòc",
"error": "Error:", "error": "Error:",
"error_see_log": "Una error ses producha. Mercés de consultar los jornals per mai detalhs, son plaçats dins /var/log/yunohost/.",
"file_exists": "Lo fichièr existís ja: « {path} »",
"file_not_exist": "Lo fichièr « {path} » existís pas", "file_not_exist": "Lo fichièr « {path} » existís pas",
"folder_exists": "Lo repertòri existís ja: « {path} »", "folder_exists": "Lo repertòri existís ja: « {path} »",
"folder_not_exist": "Lo repertòri existís pas",
"instance_already_running": "I a ja una operacion de YunoHost en cors. Mercés desperar que sacabe abans de ne lançar una mai.", "instance_already_running": "I a ja una operacion de YunoHost en cors. Mercés desperar que sacabe abans de ne lançar una mai.",
"invalid_argument": "Argument « {argument} » incorrècte: {error}", "invalid_argument": "Argument « {argument} » incorrècte: {error}",
"invalid_password": "Senhal incorrècte", "invalid_password": "Senhal incorrècte",
"ldap_server_down": "Impossible daténher lo servidor LDAP", "ldap_server_down": "Impossible daténher lo servidor LDAP",
"not_logged_in": "Cap de session començada", "not_logged_in": "Cap de session començada",
"pattern_not_match": "Correspond pas al patron", "pattern_not_match": "Correspond pas al patron",
"permission_denied": "Permission refusada",
"root_required": "Cal èsser root per realizar aquesta accion", "root_required": "Cal èsser root per realizar aquesta accion",
"unable_retrieve_session": "Recuperacion impossibla de la session a causa de « {exception} »", "unable_retrieve_session": "Recuperacion impossibla de la session a causa de « {exception} »",
"unknown_group": "Grop « {group} » desconegut", "unknown_group": "Grop « {group} » desconegut",
@ -36,22 +31,21 @@
"success": "Capitada!", "success": "Capitada!",
"unable_authenticate": "Impossible de vos autentificar", "unable_authenticate": "Impossible de vos autentificar",
"websocket_request_expected": "Una requèsta WebSocket èra esperada", "websocket_request_expected": "Una requèsta WebSocket èra esperada",
"cannot_open_file": "Impossible de dobrir lo fichièr {file:s} (rason: {error:s})", "cannot_open_file": "Impossible de dobrir lo fichièr {file} (rason: {error})",
"cannot_write_file": "Escritura impossibla del fichièr {file:s} (rason: {error:s})", "cannot_write_file": "Escritura impossibla del fichièr {file} (rason: {error})",
"unknown_error_reading_file": "Error desconeguda en ensajar de legir lo fichièr {file:s} (rason: {error:s})", "unknown_error_reading_file": "Error desconeguda en ensajar de legir lo fichièr {file} (rason: {error})",
"error_writing_file": "Error en escriure lo fichièr {file:s}: {error:s}", "error_writing_file": "Error en escriure lo fichièr {file}: {error}",
"error_removing": "Error en suprimir {path:s}: {error:s}", "error_removing": "Error en suprimir {path}: {error}",
"error_changing_file_permissions": "Error en modificar las permissions per {path:s}: {error:s}", "error_changing_file_permissions": "Error en modificar las permissions per {path}: {error}",
"invalid_url": "Url invalida {url:s} (existís aqueste site?)", "invalid_url": "Url invalida {url} (existís aqueste site?)",
"download_ssl_error": "Error SSL en se connectant a {url:s}", "download_ssl_error": "Error SSL en se connectant a {url}",
"download_timeout": "{url:s} a trigat per respondre, avèm quitat desperar.", "download_timeout": "{url} a trigat per respondre, avèm quitat desperar.",
"download_unknown_error": "Error en telecargar de donadas de {url:s}: {error:s}", "download_unknown_error": "Error en telecargar de donadas de {url}: {error}",
"download_bad_status_code": "{url:s} tòrna lo còdi destat {code:s}", "download_bad_status_code": "{url} tòrna lo còdi destat {code}",
"command_unknown": "Comanda « {command:s} » desconeguda?", "corrupted_json": "Fichièr Json corromput legit de {ressource} (rason: {error})",
"corrupted_json": "Fichièr Json corromput legit de {ressource:s} (rason: {error:s})", "corrupted_yaml": "Fichièr YAML corromput legit de {ressource} (rason: {error})",
"corrupted_yaml": "Fichièr YAML corromput legit de {ressource:s} (rason: {error:s})",
"info": "Info:", "info": "Info:",
"corrupted_toml": "Fichièr TOML corromput en lectura de {ressource:s} estant (rason: {error:s})", "corrupted_toml": "Fichièr TOML corromput en lectura de {ressource} estant (rason: {error})",
"warn_the_user_about_waiting_lock": "Una autra comanda YunoHost es en execucion, sèm a esperar quacabe abans daviar aquesta daquí", "warn_the_user_about_waiting_lock": "Una autra comanda YunoHost es en execucion, sèm a esperar quacabe abans daviar aquesta daquí",
"warn_the_user_about_waiting_lock_again": "Encara en espèra…", "warn_the_user_about_waiting_lock_again": "Encara en espèra…",
"warn_the_user_that_lock_is_acquired": "lautra comanda ven dacabar, ara lançament daquesta comanda", "warn_the_user_that_lock_is_acquired": "lautra comanda ven dacabar, ara lançament daquesta comanda",

View file

@ -4,21 +4,20 @@
"warn_the_user_that_lock_is_acquired": "Inne polecenie właśnie się zakończyło, teraz uruchamiam to polecenie", "warn_the_user_that_lock_is_acquired": "Inne polecenie właśnie się zakończyło, teraz uruchamiam to polecenie",
"warn_the_user_about_waiting_lock_again": "Wciąż czekam...", "warn_the_user_about_waiting_lock_again": "Wciąż czekam...",
"warn_the_user_about_waiting_lock": "Kolejne polecenie YunoHost jest teraz uruchomione, czekamy na jego zakończenie przed uruchomieniem tego", "warn_the_user_about_waiting_lock": "Kolejne polecenie YunoHost jest teraz uruchomione, czekamy na jego zakończenie przed uruchomieniem tego",
"command_unknown": "Polecenie '{command:s}' jest nieznane?", "download_bad_status_code": "{url} zwrócił kod stanu {code}",
"download_bad_status_code": "{url:s} zwrócił kod stanu {code:s}", "download_unknown_error": "Błąd podczas pobierania danych z {url}: {error}",
"download_unknown_error": "Błąd podczas pobierania danych z {url:s}: {error:s}", "download_timeout": "{url} odpowiedział zbyt długo, poddał się.",
"download_timeout": "{url:s} odpowiedział zbyt długo, poddał się.", "download_ssl_error": "Błąd SSL podczas łączenia z {url}",
"download_ssl_error": "Błąd SSL podczas łączenia z {url:s}", "invalid_url": "Nieprawidłowy adres URL {url} (czy ta strona istnieje?)",
"invalid_url": "Nieprawidłowy adres URL {url:s} (czy ta strona istnieje?)", "error_changing_file_permissions": "Błąd podczas zmiany uprawnień dla {path}: {error}",
"error_changing_file_permissions": "Błąd podczas zmiany uprawnień dla {path:s}: {error:s}", "error_removing": "Błąd podczas usuwania {path}: {error}",
"error_removing": "Błąd podczas usuwania {path:s}: {error:s}", "error_writing_file": "Błąd podczas zapisywania pliku {file}: {error}",
"error_writing_file": "Błąd podczas zapisywania pliku {file:s}: {error:s}", "corrupted_toml": "Uszkodzony TOML z {ressource: s} (reason: {error})",
"corrupted_toml": "Uszkodzony TOML z {ressource: s} (reason: {error:s})", "corrupted_yaml": "Uszkodzony YAML odczytany z {ressource} (reason: {error})",
"corrupted_yaml": "Uszkodzony YAML odczytany z {ressource:s} (reason: {error:s})", "corrupted_json": "Uszkodzony JSON odczytany z {ressource} (reason: {error})",
"corrupted_json": "Uszkodzony JSON odczytany z {ressource:s} (reason: {error:s})", "unknown_error_reading_file": "Nieznany błąd podczas próby odczytania pliku {file} (przyczyna: {error})",
"unknown_error_reading_file": "Nieznany błąd podczas próby odczytania pliku {file:s} (przyczyna: {error:s})", "cannot_write_file": "Nie można zapisać pliku {file} (przyczyna: {error})",
"cannot_write_file": "Nie można zapisać pliku {file:s} (przyczyna: {error:s})", "cannot_open_file": "Nie można otworzyć pliku {file} (przyczyna: {error})",
"cannot_open_file": "Nie można otworzyć pliku {file:s} (przyczyna: {error:s})",
"websocket_request_expected": "Oczekiwano żądania WebSocket", "websocket_request_expected": "Oczekiwano żądania WebSocket",
"warning": "Ostrzeżenie:", "warning": "Ostrzeżenie:",
"values_mismatch": "Wartości nie pasują", "values_mismatch": "Wartości nie pasują",
@ -41,11 +40,8 @@
"invalid_argument": "Nieprawidłowy argument „{argument}”: {error}", "invalid_argument": "Nieprawidłowy argument „{argument}”: {error}",
"instance_already_running": "Trwa już operacja YunoHost. Zaczekaj na zakończenie, zanim uruchomisz kolejny.", "instance_already_running": "Trwa już operacja YunoHost. Zaczekaj na zakończenie, zanim uruchomisz kolejny.",
"info": "Informacje:", "info": "Informacje:",
"folder_not_exist": "Folder nie istnieje",
"folder_exists": "Folder już istnieje: „{path}”", "folder_exists": "Folder już istnieje: „{path}”",
"file_not_exist": "Plik nie istnieje: „{path}”", "file_not_exist": "Plik nie istnieje: „{path}”",
"file_exists": "Plik już istnieje: „{path}”",
"error_see_log": "Wystąpił błąd. Szczegółowe informacje można znaleźć w dziennikach, znajdują się one w katalogu /var/log/yunohost/.",
"error": "Błąd:", "error": "Błąd:",
"deprecated_command_alias": "„{prog} {old}” jest przestarzałe i zostanie usunięte w przyszłości, zamiast tego użyj „{prog} {new}”", "deprecated_command_alias": "„{prog} {old}” jest przestarzałe i zostanie usunięte w przyszłości, zamiast tego użyj „{prog} {new}”",
"deprecated_command": "„{prog} {command}” jest przestarzałe i zostanie usunięte w przyszłości", "deprecated_command": "„{prog} {command}” jest przestarzałe i zostanie usunięte w przyszłości",

View file

@ -1,15 +1,12 @@
{ {
"argument_required": "O argumento {argument} é obrigatório", "argument_required": "O argumento '{argument}' é obrigatório",
"authentication_profile_required": "Autenticação requerida para o perfil '{profile}'",
"authentication_required": "Autenticação obrigatória", "authentication_required": "Autenticação obrigatória",
"authentication_required_long": "É preciso autenticar-se para realizar esta ação", "authentication_required_long": "É preciso autenticar-se para realizar esta ação",
"colon": "{}: ", "colon": "{}: ",
"confirm": "Confirmar {prompt}", "confirm": "Confirmar {prompt}",
"error": "Erro:", "error": "Erro:",
"file_exists": "A pasta já existe: '{path}'",
"file_not_exist": "O ficheiro não existe: '{path}'", "file_not_exist": "O ficheiro não existe: '{path}'",
"folder_exists": "A pasta já existe: '{path}'", "folder_exists": "A pasta já existe: '{path}'",
"folder_not_exist": "A pasta não existe",
"instance_already_running": "Já existe uma operação YunoHost em execução. Aguarde o término antes de executar outro.", "instance_already_running": "Já existe uma operação YunoHost em execução. Aguarde o término antes de executar outro.",
"invalid_argument": "Argumento inválido '{argument}': {error}", "invalid_argument": "Argumento inválido '{argument}': {error}",
"invalid_password": "Senha incorreta", "invalid_password": "Senha incorreta",
@ -22,7 +19,6 @@
"operation_interrupted": "Operação cancelada", "operation_interrupted": "Operação cancelada",
"password": "Senha", "password": "Senha",
"pattern_not_match": "Não corresponde ao motivo", "pattern_not_match": "Não corresponde ao motivo",
"permission_denied": "Permissão revogada",
"root_required": "Deve ser root (administrador) para realizar esta ação", "root_required": "Deve ser root (administrador) para realizar esta ação",
"server_already_running": "Existe um servidor ativo nessa porta", "server_already_running": "Existe um servidor ativo nessa porta",
"success": "Sucesso!", "success": "Sucesso!",
@ -33,27 +29,25 @@
"websocket_request_expected": "Esperado um pedido a WebSocket", "websocket_request_expected": "Esperado um pedido a WebSocket",
"deprecated_command": "'{prog} {command}' está obsoleto e será removido no futuro", "deprecated_command": "'{prog} {command}' está obsoleto e será removido no futuro",
"deprecated_command_alias": "'{prog} {old}' está obsoleto e será removido no futuro, em vez disso, usa '{prog} {new}'", "deprecated_command_alias": "'{prog} {old}' está obsoleto e será removido no futuro, em vez disso, usa '{prog} {new}'",
"error_see_log": "Ocorreu um erro . Por favor, veja os logs para maiores detalhes, eles estão localizados em /var/log/yunohost/.",
"unknown_group": "Grupo '{group}' desconhecido", "unknown_group": "Grupo '{group}' desconhecido",
"unknown_user": "Nome de utilizador '{user}' desconhecido", "unknown_user": "Nome de utilizador '{user}' desconhecido",
"cannot_open_file": "Não foi possível abrir o arquivo {file:s} (reason: {error:s})", "cannot_open_file": "Não foi possível abrir o arquivo {file} (reason: {error})",
"cannot_write_file": "Não foi possível abrir o arquivo {file:s} (reason: {error:s})", "cannot_write_file": "Não foi possível abrir o arquivo {file} (reason: {error})",
"unknown_error_reading_file": "Erro desconhecido ao tentar ler o arquivo {file:s} (motivo: {error:s})", "unknown_error_reading_file": "Erro desconhecido ao tentar ler o arquivo {file} (motivo: {error})",
"error_writing_file": "Erro ao gravar arquivo {file:s}: {error:s}", "error_writing_file": "Erro ao gravar arquivo {file}: {error}",
"error_removing": "Erro ao remover {path:s}: {error:s}", "error_removing": "Erro ao remover {path}: {error}",
"error_changing_file_permissions": "Erro ao alterar as permissões para {path:s}: {error:s}", "error_changing_file_permissions": "Erro ao alterar as permissões para {path}: {error}",
"invalid_url": "URL inválida {url:s} (Esse site existe ?)", "invalid_url": "URL inválida {url} (Esse site existe ?)",
"download_ssl_error": "Erro de SSL ao conectar-se a {url:s}", "download_ssl_error": "Erro de SSL ao conectar-se a {url}",
"download_timeout": "{url:s} demorou muito para responder, desistiu.", "download_timeout": "{url} demorou muito para responder, desistiu.",
"download_unknown_error": "Erro quando baixando os dados de {url:s} : {error:s}", "download_unknown_error": "Erro quando baixando os dados de {url} : {error}",
"download_bad_status_code": "{url:s} retornou o código de status {code:s}", "download_bad_status_code": "{url} retornou o código de status {code}",
"command_unknown": "Comando '{command:s}' desconhecido ?", "corrupted_json": "JSON corrompido lido do {ressource} (motivo: {error})",
"corrupted_json": "JSON corrompido lido do {ressource:s} (motivo: {error:s})", "corrupted_yaml": "YAML corrompido lido do {ressource} (motivo: {error})",
"corrupted_yaml": "YAML corrompido lido do {ressource:s} (motivo: {error:s})",
"warn_the_user_that_lock_is_acquired": "O outro comando acabou de concluir, agora iniciando este comando", "warn_the_user_that_lock_is_acquired": "O outro comando acabou de concluir, agora iniciando este comando",
"warn_the_user_about_waiting_lock_again": "Ainda esperando...", "warn_the_user_about_waiting_lock_again": "Ainda esperando...",
"warn_the_user_about_waiting_lock": "Outro comando YunoHost está sendo executado agora, estamos aguardando o término antes de executar este", "warn_the_user_about_waiting_lock": "Outro comando YunoHost está sendo executado agora, estamos aguardando o término antes de executar este",
"corrupted_toml": "TOML corrompido lido em {ressource:s} (motivo: {error:s})", "corrupted_toml": "TOML corrompido lido em {ressource} (motivo: {error})",
"invalid_token": "Token inválido - autentique", "invalid_token": "Token inválido - autentique",
"info": "Informações:", "info": "Informações:",
"ldap_server_is_down_restart_it": "O serviço LDAP esta caído, tentando reiniciá-lo...", "ldap_server_is_down_restart_it": "O serviço LDAP esta caído, tentando reiniciá-lo...",

View file

@ -1,6 +1,5 @@
{ {
"argument_required": "Требуется'{argument}' аргумент", "argument_required": "Требуется'{argument}' аргумент",
"authentication_profile_required": "Для доступа к '{profile}' требуется аутентификация",
"authentication_required": "Требуется аутентификация", "authentication_required": "Требуется аутентификация",
"authentication_required_long": "Для этого действия требуется аутентификация", "authentication_required_long": "Для этого действия требуется аутентификация",
"colon": "{}: ", "colon": "{}: ",
@ -8,11 +7,8 @@
"deprecated_command": "'{prog} {command}' устарела и будет удалена", "deprecated_command": "'{prog} {command}' устарела и будет удалена",
"deprecated_command_alias": "'{prog} {old}' устарела и будет удалена, вместо неё используйте '{prog} {new}'", "deprecated_command_alias": "'{prog} {old}' устарела и будет удалена, вместо неё используйте '{prog} {new}'",
"error": "Ошибка:", "error": "Ошибка:",
"error_see_log": "Произошла ошибка. Пожалуйста, смотри подробности в логах, находящихся /var/log/yunohost/.",
"file_exists": "Файл уже существует: '{path}'",
"file_not_exist": "Файл не существует: '{path}'", "file_not_exist": "Файл не существует: '{path}'",
"folder_exists": "Каталог уже существует: '{path}'", "folder_exists": "Каталог уже существует: '{path}'",
"folder_not_exist": "Каталог не существует",
"invalid_argument": "Неправильный аргумент '{argument}': {error}", "invalid_argument": "Неправильный аргумент '{argument}': {error}",
"invalid_password": "Неправильный пароль", "invalid_password": "Неправильный пароль",
"ldap_attribute_already_exists": "Атрибут '{attribute}' уже существует со значением '{value}'", "ldap_attribute_already_exists": "Атрибут '{attribute}' уже существует со значением '{value}'",
@ -30,26 +26,25 @@
"values_mismatch": "Неверные значения", "values_mismatch": "Неверные значения",
"warning": "Внимание :", "warning": "Внимание :",
"websocket_request_expected": "Ожидается запрос WebSocket", "websocket_request_expected": "Ожидается запрос WebSocket",
"cannot_open_file": "Не могу открыть файл {file:s} (причина: {error:s})", "cannot_open_file": "Не могу открыть файл {file} (причина: {error})",
"cannot_write_file": "Не могу записать файл {file:s} (причина: {error:s})", "cannot_write_file": "Не могу записать файл {file} (причина: {error})",
"unknown_error_reading_file": "Неизвестная ошибка при попытке прочитать файл {file:s} (причина: {error:s})", "unknown_error_reading_file": "Неизвестная ошибка при попытке прочитать файл {file} (причина: {error})",
"corrupted_yaml": "Повреждённой yaml получен от {ressource:s} (причина: {error:s})", "corrupted_yaml": "Повреждённой yaml получен от {ressource} (причина: {error})",
"error_writing_file": "Ошибка при записи файла {file:s}: {error:s}", "error_writing_file": "Ошибка при записи файла {file}: {error}",
"error_removing": "Ошибка при удалении {path:s}: {error:s}", "error_removing": "Ошибка при удалении {path}: {error}",
"invalid_url": "Неправильный url {url:s} (этот сайт существует ?)", "invalid_url": "Неправильный url {url} (этот сайт существует ?)",
"download_ssl_error": "Ошибка SSL при соединении с {url:s}", "download_ssl_error": "Ошибка SSL при соединении с {url}",
"download_timeout": "Превышено время ожидания ответа от {url:s}.", "download_timeout": "Превышено время ожидания ответа от {url}.",
"download_unknown_error": "Ошибка при загрузке данных с {url:s} : {error:s}", "download_unknown_error": "Ошибка при загрузке данных с {url} : {error}",
"instance_already_running": "Операция YunoHost уже запущена. Пожалуйста, подождите, пока он закончится, прежде чем запускать другой.", "instance_already_running": "Операция YunoHost уже запущена. Пожалуйста, подождите, пока он закончится, прежде чем запускать другой.",
"root_required": "Чтобы выполнить это действие, вы должны иметь права root", "root_required": "Чтобы выполнить это действие, вы должны иметь права root",
"corrupted_json": "Повреждённый json получен от {ressource:s} (причина: {error:s})", "corrupted_json": "Повреждённый json получен от {ressource} (причина: {error})",
"command_unknown": "Команда '{command:s}' неизвестна ?",
"warn_the_user_that_lock_is_acquired": "другая команда только что завершилась, теперь запускает эту команду", "warn_the_user_that_lock_is_acquired": "другая команда только что завершилась, теперь запускает эту команду",
"warn_the_user_about_waiting_lock_again": "Все еще жду...", "warn_the_user_about_waiting_lock_again": "Все еще жду...",
"warn_the_user_about_waiting_lock": "Сейчас запускается еще одна команда YunoHost, мы ждем ее завершения, прежде чем запустить эту", "warn_the_user_about_waiting_lock": "Сейчас запускается еще одна команда YunoHost, мы ждем ее завершения, прежде чем запустить эту",
"download_bad_status_code": "{url:s} вернул код состояния {code:s}", "download_bad_status_code": "{url} вернул код состояния {code}",
"error_changing_file_permissions": "Ошибка при изменении разрешений для {path:s}: {error:s}", "error_changing_file_permissions": "Ошибка при изменении разрешений для {path}: {error}",
"corrupted_toml": "Поврежденный том, прочитанный из {ressource:s} (причина: {error:s})", "corrupted_toml": "Поврежденный том, прочитанный из {ressource} (причина: {error})",
"unable_retrieve_session": "Невозможно получить сеанс, так как '{exception}'", "unable_retrieve_session": "Невозможно получить сеанс, так как '{exception}'",
"ldap_server_down": "Невозможно связаться с сервером LDAP", "ldap_server_down": "Невозможно связаться с сервером LDAP",
"invalid_usage": "Неправильное использование, передайте --help, чтобы увидеть помощь", "invalid_usage": "Неправильное использование, передайте --help, чтобы увидеть помощь",

View file

@ -1,10 +1,10 @@
{ {
"warn_the_user_about_waiting_lock_again": "Väntar fortfarande …", "warn_the_user_about_waiting_lock_again": "Väntar fortfarande …",
"download_bad_status_code": "{url:s} svarade med statuskod {code:s}", "download_bad_status_code": "{url} svarade med statuskod {code}",
"download_timeout": "Gav upp eftersom {url:s} tog för lång tid på sig att svara.", "download_timeout": "Gav upp eftersom {url} tog för lång tid på sig att svara.",
"download_ssl_error": "Ett SSL-fel påträffades vid anslutning till {url:s}", "download_ssl_error": "Ett SSL-fel påträffades vid anslutning till {url}",
"cannot_write_file": "Kunde inte skriva till filen {file:s} (orsak: {error:s})", "cannot_write_file": "Kunde inte skriva till filen {file} (orsak: {error})",
"cannot_open_file": "Kunde inte öppna filen {file:s} (orsak: {error:s})", "cannot_open_file": "Kunde inte öppna filen {file} (orsak: {error})",
"websocket_request_expected": "Förväntade en WebSocket-förfrågan", "websocket_request_expected": "Förväntade en WebSocket-förfrågan",
"warning": "Varning:", "warning": "Varning:",
"values_mismatch": "Värdena stämmer inte överens", "values_mismatch": "Värdena stämmer inte överens",
@ -22,11 +22,8 @@
"invalid_argument": "Ogiltig parameter '{argument}': {error}", "invalid_argument": "Ogiltig parameter '{argument}': {error}",
"logged_out": "Utloggad", "logged_out": "Utloggad",
"info": "Info:", "info": "Info:",
"folder_not_exist": "Katalogen finns inte",
"folder_exists": "Katalogen finns redan: '{path}'", "folder_exists": "Katalogen finns redan: '{path}'",
"file_not_exist": "Filen finns inte: '{path}'", "file_not_exist": "Filen finns inte: '{path}'",
"file_exists": "Filen finns redan: '{path}'",
"error_see_log": "Ett fel har inträffat. Kolla gärna i loggfilerna för mer information, de finns i /var/log/yunohost/.",
"error": "Fel:", "error": "Fel:",
"deprecated_command_alias": "'{prog} {old}' rekommenderas inte längre och kommer tas bort i framtiden, använd '{prog} {new}' istället", "deprecated_command_alias": "'{prog} {old}' rekommenderas inte längre och kommer tas bort i framtiden, använd '{prog} {new}' istället",
"deprecated_command": "'{prog} {command}' rekommenderas inte längre och kommer tas bort i framtiden", "deprecated_command": "'{prog} {command}' rekommenderas inte längre och kommer tas bort i framtiden",
@ -36,16 +33,15 @@
"password": "Lösenord", "password": "Lösenord",
"warn_the_user_that_lock_is_acquired": "det andra kommandot har bara slutförts, nu startar du det här kommandot", "warn_the_user_that_lock_is_acquired": "det andra kommandot har bara slutförts, nu startar du det här kommandot",
"warn_the_user_about_waiting_lock": "Ett annat YunoHost-kommando körs just nu, vi väntar på att det ska slutföras innan det här körs", "warn_the_user_about_waiting_lock": "Ett annat YunoHost-kommando körs just nu, vi väntar på att det ska slutföras innan det här körs",
"command_unknown": "Kommando '{command:s}' okänd?", "download_unknown_error": "Fel vid nedladdning av data från {url}: {error}",
"download_unknown_error": "Fel vid nedladdning av data från {url:s}: {error:s}", "invalid_url": "Ogiltig url {url} (finns den här webbplatsen?)",
"invalid_url": "Ogiltig url {url:s} (finns den här webbplatsen?)", "error_changing_file_permissions": "Fel vid ändring av behörigheter för {path}: {error}",
"error_changing_file_permissions": "Fel vid ändring av behörigheter för {path:s}: {error:s}", "error_removing": "Fel vid borttagning av {path}: {error}",
"error_removing": "Fel vid borttagning av {path:s}: {error:s}", "error_writing_file": "Fel vid skrivning av fil {file}: {error}",
"error_writing_file": "Fel vid skrivning av fil {file:s}: {error:s}", "corrupted_toml": "Korrupt toml läst från {ressource} (anledning: {error})",
"corrupted_toml": "Korrupt toml läst från {ressource:s} (anledning: {error:s})", "corrupted_yaml": "Skadad yaml läst från {ressource} (anledning: {error})",
"corrupted_yaml": "Skadad yaml läst från {ressource:s} (anledning: {error:s})", "corrupted_json": "Skadad json läst från {ressource} (anledning: {error})",
"corrupted_json": "Skadad json läst från {ressource:s} (anledning: {error:s})", "unknown_error_reading_file": "Okänt fel vid försök att läsa filen {file} (anledning: {error})",
"unknown_error_reading_file": "Okänt fel vid försök att läsa filen {file:s} (anledning: {error:s})",
"unable_retrieve_session": "Det gick inte att hämta sessionen eftersom '{exception}'", "unable_retrieve_session": "Det gick inte att hämta sessionen eftersom '{exception}'",
"unable_authenticate": "Det går inte att verifiera", "unable_authenticate": "Det går inte att verifiera",
"ldap_server_down": "Det går inte att nå LDAP-servern", "ldap_server_down": "Det går inte att nå LDAP-servern",

View file

@ -1,12 +1,10 @@
{ {
"argument_required": "{argument} argümanı gerekli", "argument_required": "{argument} argümanı gerekli",
"authentication_profile_required": "'{profile}' profili için yetkilendirme gerekli",
"authentication_required": "Yetklendirme gerekli", "authentication_required": "Yetklendirme gerekli",
"authentication_required_long": "Bu işlemi yapmak içi yetkilendirme gerekli", "authentication_required_long": "Bu işlemi yapmak içi yetkilendirme gerekli",
"colon": "{}: ", "colon": "{}: ",
"confirm": "{prompt}'i doğrulayın", "confirm": "{prompt}'i doğrulayın",
"error": "Hata:", "error": "Hata:",
"error_see_log": "Bir hata oluştu. Ayrıntılar için lütfen günlüklere bakın, bunlar /var/log/yunohost/ dizinindedir.",
"instance_already_running": "Halihazırda bir YunoHost operasyonu var. Lütfen başka bir tane çalıştırmadan önce bitmesini bekleyin.", "instance_already_running": "Halihazırda bir YunoHost operasyonu var. Lütfen başka bir tane çalıştırmadan önce bitmesini bekleyin.",
"invalid_argument": "Geçersiz argüman '{argument}': {error}", "invalid_argument": "Geçersiz argüman '{argument}': {error}",
"invalid_password": "Geçersiz parola", "invalid_password": "Geçersiz parola",
@ -18,7 +16,6 @@
"operation_interrupted": "İşlem yarıda kesildi", "operation_interrupted": "İşlem yarıda kesildi",
"password": "Parola", "password": "Parola",
"pattern_not_match": "İstenen biçimle uyuşmuyor", "pattern_not_match": "İstenen biçimle uyuşmuyor",
"permission_denied": "Erişim reddedildi",
"root_required": "Bu işlemi yapmak için root olmalısınız", "root_required": "Bu işlemi yapmak için root olmalısınız",
"server_already_running": "Bu portta zaten çalışan bir sunucu var", "server_already_running": "Bu portta zaten çalışan bir sunucu var",
"success": "İşlem Başarılı!", "success": "İşlem Başarılı!",
@ -30,30 +27,27 @@
"warn_the_user_that_lock_is_acquired": "diğer komut şimdi tamamlandı, şimdi bu komutu başlatıyor", "warn_the_user_that_lock_is_acquired": "diğer komut şimdi tamamlandı, şimdi bu komutu başlatıyor",
"warn_the_user_about_waiting_lock_again": "Hala bekliyor...", "warn_the_user_about_waiting_lock_again": "Hala bekliyor...",
"warn_the_user_about_waiting_lock": "Başka bir YunoHost komutu şu anda çalışıyor, bunu çalıştırmadan önce bitmesini bekliyoruz", "warn_the_user_about_waiting_lock": "Başka bir YunoHost komutu şu anda çalışıyor, bunu çalıştırmadan önce bitmesini bekliyoruz",
"command_unknown": "'{Command:s}' komutu bilinmiyor mu?", "download_bad_status_code": "{url} döndürülen durum kodu {code}",
"download_bad_status_code": "{url:s} döndürülen durum kodu {code:s}", "download_unknown_error": "{url} adresinden veri indirilirken hata oluştu: {error}",
"download_unknown_error": "{url:s} adresinden veri indirilirken hata oluştu: {error:s}", "download_timeout": "{url} yanıtlaması çok uzun sürdü, pes etti.",
"download_timeout": "{url:s} yanıtlaması çok uzun sürdü, pes etti.", "download_ssl_error": "{url} ağına bağlanırken SSL hatası",
"download_ssl_error": "{url:s} ağına bağlanırken SSL hatası", "invalid_url": "Geçersiz url {url} (bu site var mı?)",
"invalid_url": "Geçersiz url {url:s} (bu site var mı?)", "error_changing_file_permissions": "{path} için izinler değiştirilirken hata oluştu: {error}",
"error_changing_file_permissions": "{Path:s} için izinler değiştirilirken hata oluştu: {error:s}", "error_removing": "{path} kaldırılırken hata oluştu: {error}",
"error_removing": "{Path:s} kaldırılırken hata oluştu: {error:s}", "error_writing_file": "{file} dosyası yazılırken hata oluştu: {error}",
"error_writing_file": "{File:s} dosyası yazılırken hata oluştu: {error:s}", "corrupted_toml": "{ressource} kaynağından okunan bozuk toml (nedeni: {error})",
"corrupted_toml": "{Ressource:s} kaynağından okunan bozuk toml (nedeni: {hata:s})", "corrupted_yaml": "{ressource} kaynağından bozuk yaml okunuyor (nedeni: {error})",
"corrupted_yaml": "{Ressource:s} kaynağından bozuk yaml okunuyor (nedeni: {error:s})", "corrupted_json": "{ressource} adresinden okunan bozuk json (nedeni: {error})",
"corrupted_json": "{Ressource:s} adresinden okunan bozuk json (nedeni: {error:s})", "unknown_error_reading_file": "{file} dosyasını okumaya çalışırken bilinmeyen hata (nedeni: {error})",
"unknown_error_reading_file": "{File:s} dosyasını okumaya çalışırken bilinmeyen hata (nedeni: {error:s})", "cannot_write_file": "{file} dosyası yazılamadı (nedeni: {error})",
"cannot_write_file": "{File:s} dosyası yazılamadı (nedeni: {error:s})", "cannot_open_file": "{file} dosyasıılamadı (nedeni: {error})",
"cannot_open_file": "{File:s} dosyasıılamadı (nedeni: {error:s})",
"unknown_user": "Bilinmeyen '{user}' kullanıcı", "unknown_user": "Bilinmeyen '{user}' kullanıcı",
"unknown_group": "Bilinmeyen '{group}' grubu", "unknown_group": "Bilinmeyen '{group}' grubu",
"invalid_usage": "Geçersiz kullanım, yardım görmek için --help iletin", "invalid_usage": "Geçersiz kullanım, yardım görmek için --help iletin",
"invalid_token": "Geçersiz simge - lütfen kimlik doğrulaması yapın", "invalid_token": "Geçersiz simge - lütfen kimlik doğrulaması yapın",
"info": "Bilgi:", "info": "Bilgi:",
"folder_not_exist": "Klasör mevcut değil",
"folder_exists": "Klasör zaten var: '{path}'", "folder_exists": "Klasör zaten var: '{path}'",
"file_not_exist": "Dosya mevcut değil: '{path}'", "file_not_exist": "Dosya mevcut değil: '{path}'",
"file_exists": "Dosya zaten var: '{path}'",
"deprecated_command_alias": "'{prog} {old}' kullanımdan kaldırıldı ve gelecekte kaldırılacak, bunun yerine '{prog} {new}' kullanın", "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" "deprecated_command": "'{prog} {command}' kullanımdan kaldırıldı ve gelecekte kaldırılacak"
} }

47
locales/uk.json Normal file
View file

@ -0,0 +1,47 @@
{
"password": "Пароль",
"logged_out": "Ви вийшли з системи",
"invalid_url": "Помилка з'єднання із {url}... можливо, служба не працює, або ви неправильно під'єднані до Інтернету в IPv4/IPv6.",
"warn_the_user_that_lock_is_acquired": "Інша команда щойно завершилася, тепер запускаємо цю команду",
"warn_the_user_about_waiting_lock_again": "Досі очікуємо...",
"warn_the_user_about_waiting_lock": "Зараз запускається ще одна команда YunoHost, ми чекаємо її завершення, перш ніж запустити цю",
"download_bad_status_code": "{url} повернув код стану {code}",
"download_unknown_error": "Помилка під час завантаження даних з {url}: {error}",
"download_timeout": "Перевищено час очікування відповіді від {url}.",
"download_ssl_error": "Помилка SSL під час з'єднання з {url}",
"error_changing_file_permissions": "Помилка під час зміни дозволів для {path}: {error}",
"error_removing": "Помилка під час видалення {path}: {error}",
"error_writing_file": "Помилка під час запису файлу {file}: {error}",
"corrupted_toml": "Пошкоджений TOML, зчитаний з {ressource} (причина: {error})",
"corrupted_yaml": "Пошкоджений YAML, зчитаний з {ressource} (причина: {error})",
"corrupted_json": "Пошкоджений JSON, зчитаний з {ressource} (причина: {error})",
"unknown_error_reading_file": "Невідома помилка під час спроби прочитати файл {file} (причина: {error})",
"cannot_write_file": "Не можу записати файл {file} (причина: {error})",
"cannot_open_file": "Не можу відкрити файл {file} (причина: {error})",
"websocket_request_expected": "Очікується запит WebSocket",
"warning": "Попередження:",
"values_mismatch": "Неприпустимі значення",
"unknown_user": "Невідомий користувач '{user}'",
"unknown_group": "Невідома група '{group}'",
"unable_authenticate": "Автентифікація неможлива",
"success": "Успішно!",
"server_already_running": "Сервер вже запущений на цьому порті",
"root_required": "Щоб виконати цю дію, ви повинні мати кореневі права (root)",
"pattern_not_match": "Не відповідає зразку",
"operation_interrupted": "Операцію перервано",
"not_logged_in": "Ви не увійшли в систему",
"logged_in": "Ви увійшли в систему",
"invalid_usage": "Неправильне використання, передайте --help для перегляду довідки",
"invalid_argument": "Неправильний аргумент '{argument}': {error}",
"instance_already_running": "Операція YunoHost вже запущена. Будь ласка, зачекайте, поки вона закінчиться, перш ніж запускати іншу.",
"info": "Відомості:",
"folder_exists": "Каталог вже існує: '{path}'",
"file_not_exist": "Файл не існує: '{path}'",
"error": "Помилка:",
"deprecated_command_alias": "'{prog} {old}' застаріла і буде видалена, замість неї використовуйте '{prog} {new}'",
"deprecated_command": "'{prog} {command}' застаріла і буде видалена",
"confirm": "Підтвердити {prompt}",
"colon": "{}: ",
"authentication_required": "Потрібна автентифікація",
"argument_required": "Потрібен аргумент '{argument}'"
}

View file

@ -2,10 +2,9 @@
from moulinette.core import ( from moulinette.core import (
MoulinetteError, MoulinetteError,
MoulinetteSignals,
Moulinette18n, Moulinette18n,
env,
) )
from moulinette.globals import init_moulinette_env
__title__ = "moulinette" __title__ = "moulinette"
__author__ = ["Yunohost Contributors"] __author__ = ["Yunohost Contributors"]
@ -26,23 +25,35 @@ __credits__ = """
You should have received a copy of the GNU Affero General Public License You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses along with this program; if not, see http://www.gnu.org/licenses
""" """
__all__ = [ __all__ = ["init", "api", "cli", "m18n", "MoulinetteError", "Moulinette"]
"init",
"api",
"cli",
"m18n",
"msignals",
"env",
"init_interface",
"MoulinetteError",
]
msignals = MoulinetteSignals()
msettings = dict()
m18n = Moulinette18n() 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 # Package functions
@ -67,7 +78,7 @@ def init(logging_config=None, **kwargs):
configure_logging(logging_config) configure_logging(logging_config)
# Add library directory to python path # Add library directory to python path
sys.path.insert(0, init_moulinette_env()["LIB_DIR"]) sys.path.insert(0, env["LIB_DIR"])
# Easy access to interfaces # Easy access to interfaces
@ -125,8 +136,3 @@ def cli(args, top_parser, output_as=None, timeout=None):
logging.getLogger("moulinette").error(e.strerror) logging.getLogger("moulinette").error(e.strerror)
return 1 return 1
return 0 return 0
def env():
"""Initialise moulinette specific configuration."""
return init_moulinette_env()

View file

@ -3,7 +3,6 @@
import os import os
import re import re
import logging import logging
import yaml
import glob import glob
import pickle as pickle import pickle as pickle
@ -11,17 +10,16 @@ from time import time
from collections import OrderedDict from collections import OrderedDict
from importlib import import_module from importlib import import_module
from moulinette import m18n, msignals from moulinette import m18n, Moulinette
from moulinette.cache import open_cachefile
from moulinette.globals import init_moulinette_env
from moulinette.core import ( from moulinette.core import (
MoulinetteError, MoulinetteError,
MoulinetteLock, MoulinetteLock,
MoulinetteAuthenticationError,
MoulinetteValidationError, MoulinetteValidationError,
env,
) )
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 from moulinette.utils.log import start_action_logging
from moulinette.utils.filesystem import read_yaml
logger = logging.getLogger("moulinette.actionsmap") logger = logging.getLogger("moulinette.actionsmap")
@ -42,7 +40,6 @@ class _ExtraParameter(object):
""" """
def __init__(self, iface): def __init__(self, iface):
# TODO: Add conn argument which contains authentification object
self.iface = iface self.iface = iface
# Required variables # Required variables
@ -98,7 +95,7 @@ class CommentParameter(_ExtraParameter):
def __call__(self, message, arg_name, arg_value): def __call__(self, message, arg_name, arg_value):
if arg_value is None: if arg_value is None:
return return
return msignals.display(m18n.n(message)) return Moulinette.display(m18n.n(message))
@classmethod @classmethod
def validate(klass, value, arg_name): def validate(klass, value, arg_name):
@ -135,7 +132,7 @@ class AskParameter(_ExtraParameter):
try: try:
# Ask for the argument value # Ask for the argument value
return msignals.prompt(m18n.n(message)) return Moulinette.prompt(m18n.n(message))
except NotImplementedError: except NotImplementedError:
return arg_value return arg_value
@ -173,7 +170,7 @@ class PasswordParameter(AskParameter):
try: try:
# Ask for the password # Ask for the password
return msignals.prompt(m18n.n(message), True, True) return Moulinette.prompt(m18n.n(message), True, True)
except NotImplementedError: except NotImplementedError:
return arg_value return arg_value
@ -225,7 +222,7 @@ class PatternParameter(_ExtraParameter):
"expecting a list as extra parameter 'pattern' of " "argument '%s'", "expecting a list as extra parameter 'pattern' of " "argument '%s'",
arg_name, arg_name,
) )
value = [value, "pattern_not_match"] value = [value, "pattern_not_match"] # i18n: pattern_not_match
elif not isinstance(value, list) or len(value) != 2: elif not isinstance(value, list) or len(value) != 2:
raise TypeError("parameter value must be a list, got %r" % value) raise TypeError("parameter value must be a list, got %r" % value)
return value return value
@ -284,7 +281,7 @@ class ExtraArgumentParser(object):
def __init__(self, iface): def __init__(self, iface):
self.iface = iface self.iface = iface
self.extra = OrderedDict() self.extra = OrderedDict()
self._extra_params = {GLOBAL_SECTION: {}} self._extra_params = {"_global": {}}
# Append available extra parameters for the current interface # Append available extra parameters for the current interface
for klass in extraparameters_list: for klass in extraparameters_list:
@ -326,7 +323,7 @@ class ExtraArgumentParser(object):
Add extra parameters to apply on an action argument Add extra parameters to apply on an action argument
Keyword arguments: 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 for global extra parameters
- arg_name -- The argument name - arg_name -- The argument name
- parameters -- A dict of extra parameters with their values - parameters -- A dict of extra parameters with their values
@ -349,7 +346,7 @@ class ExtraArgumentParser(object):
- args -- A dict of argument name associated to their value - 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, {})) extra_args.update(self._extra_params.get(tid, {}))
# Iterate over action arguments with extra parameters # Iterate over action arguments with extra parameters
@ -383,17 +380,6 @@ class ExtraArgumentParser(object):
# Main class ---------------------------------------------------------- # Main class ----------------------------------------------------------
def ordered_yaml_load(stream):
class OrderedLoader(yaml.Loader):
pass
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
lambda loader, node: OrderedDict(loader.construct_pairs(node)),
)
return yaml.load(stream, OrderedLoader)
class ActionsMap(object): class ActionsMap(object):
"""Validate and process actions defined into an actions map """Validate and process actions defined into an actions map
@ -421,9 +407,8 @@ class ActionsMap(object):
"Invalid parser class '%s'" % top_parser.__class__.__name__ "Invalid parser class '%s'" % top_parser.__class__.__name__
) )
moulinette_env = init_moulinette_env() DATA_DIR = env["DATA_DIR"]
DATA_DIR = moulinette_env["DATA_DIR"] CACHE_DIR = env["CACHE_DIR"]
CACHE_DIR = moulinette_env["CACHE_DIR"]
actionsmaps = OrderedDict() actionsmaps = OrderedDict()
@ -441,6 +426,29 @@ class ActionsMap(object):
actionsmap_yml_stat.st_mtime, actionsmap_yml_stat.st_mtime,
) )
def generate_cache():
# Iterate over actions map namespaces
logger.debug("generating cache for actions map namespace '%s'", n)
# Read actions map from yaml file
actionsmap = read_yaml(actionsmap_yml)
# Delete old cache files
for old_cache in glob.glob("%s/actionsmap/%s-*.pkl" % (CACHE_DIR, n)):
os.remove(old_cache)
# at installation, cachedir might not exists
dir_ = os.path.dirname(actionsmap_pkl)
if not os.path.isdir(dir_):
os.makedirs(dir_)
# Cache actions map into pickle file
with open(actionsmap_pkl, "wb") as f:
pickle.dump(actionsmap, f)
return actionsmap
if os.path.exists(actionsmap_pkl): if os.path.exists(actionsmap_pkl):
try: try:
# Attempt to load cache # Attempt to load cache
@ -450,9 +458,9 @@ class ActionsMap(object):
self.from_cache = True self.from_cache = True
# TODO: Switch to python3 and catch proper exception # TODO: Switch to python3 and catch proper exception
except (IOError, EOFError): except (IOError, EOFError):
actionsmaps[n] = self.generate_cache(n) actionsmaps[n] = generate_cache()
else: # cache file doesn't exists else: # cache file doesn't exists
actionsmaps[n] = self.generate_cache(n) actionsmaps[n] = generate_cache()
# If load_only_category is set, and *if* the target category # If load_only_category is set, and *if* the target category
# is in the actionsmap, we'll load only that one. # is in the actionsmap, we'll load only that one.
@ -472,39 +480,35 @@ class ActionsMap(object):
self.extraparser = ExtraArgumentParser(top_parser.interface) self.extraparser = ExtraArgumentParser(top_parser.interface)
self.parser = self._construct_parser(actionsmaps, top_parser) 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 if auth_method == "default":
try: auth_method = self.default_authentication
auth_conf = self.parser.global_conf["authenticator"][auth_profile]
except KeyError:
raise ValueError("Unknown authenticator profile '%s'" % auth_profile)
# Load and initialize the authenticator module # 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: try:
mod = import_module("moulinette.authenticators.%s" % auth_conf["vendor"]) mod = import_module(auth_module)
except ImportError: except ImportError as e:
error_message = ( import traceback
"unable to load authenticator vendor module 'moulinette.authenticators.%s'"
% auth_conf["vendor"] 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: 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 return
authenticator = self.get_authenticator_for_profile(auth_profile) authenticator = self.get_authenticator(auth_method)
auth = msignals.authenticate(authenticator) Moulinette.interface.authenticate(authenticator)
if not auth.is_authenticated:
raise MoulinetteAuthenticationError("authentication_required_long")
def process(self, args, timeout=None, **kwargs): def process(self, args, timeout=None, **kwargs):
""" """
@ -613,12 +617,11 @@ class ActionsMap(object):
""" """
namespaces = [] namespaces = []
moulinette_env = init_moulinette_env() DATA_DIR = env["DATA_DIR"]
DATA_DIR = moulinette_env["DATA_DIR"]
# This var is ['*'] by default but could be set for example to # This var is ['*'] by default but could be set for example to
# ['yunohost', 'yml_*'] # ['yunohost', 'yml_*']
NAMESPACE_PATTERNS = moulinette_env["NAMESPACES"] NAMESPACE_PATTERNS = env["NAMESPACES"]
# Look for all files that match the given patterns in the actionsmap dir # Look for all files that match the given patterns in the actionsmap dir
for namespace_pattern in NAMESPACE_PATTERNS: for namespace_pattern in NAMESPACE_PATTERNS:
@ -631,43 +634,6 @@ class ActionsMap(object):
return namespaces return namespaces
@classmethod
def generate_cache(klass, namespace):
"""
Generate cache for the actions map's file(s)
Keyword arguments:
- namespace -- The namespace to generate cache for
Returns:
The action map for the namespace
"""
moulinette_env = init_moulinette_env()
CACHE_DIR = moulinette_env["CACHE_DIR"]
DATA_DIR = moulinette_env["DATA_DIR"]
# Iterate over actions map namespaces
logger.debug("generating cache for actions map namespace '%s'", namespace)
# Read actions map from yaml file
am_file = "%s/actionsmap/%s.yml" % (DATA_DIR, namespace)
with open(am_file, "r") as f:
actionsmap = ordered_yaml_load(f)
# at installation, cachedir might not exists
for old_cache in glob.glob("%s/actionsmap/%s-*.pkl" % (CACHE_DIR, namespace)):
os.remove(old_cache)
# Cache actions map into pickle file
am_file_stat = os.stat(am_file)
pkl = "%s-%d-%d.pkl" % (namespace, am_file_stat.st_size, am_file_stat.st_mtime)
with open_cachefile(pkl, "wb", subdir="actionsmap") as f:
pickle.dump(actionsmap, f)
return actionsmap
# Private methods # Private methods
def _construct_parser(self, actionsmaps, top_parser): def _construct_parser(self, actionsmaps, top_parser):
@ -688,6 +654,8 @@ class ActionsMap(object):
logger.debug("building parser...") logger.debug("building parser...")
start = time() start = time()
interface_type = top_parser.interface
# If loading from cache, extra were already checked when cache was # If loading from cache, extra were already checked when cache was
# loaded ? Not sure about this ... old code is a bit mysterious... # loaded ? Not sure about this ... old code is a bit mysterious...
validate_extra = not self.from_cache validate_extra = not self.from_cache
@ -701,25 +669,31 @@ class ActionsMap(object):
# Retrieve global parameters # Retrieve global parameters
_global = actionsmap.pop("_global", {}) _global = actionsmap.pop("_global", {})
# Set the global configuration to use for the parser. if _global:
top_parser.set_global_conf(_global["configuration"]) 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(): if top_parser.has_global_parser():
top_parser.add_global_arguments(_global["arguments"]) 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_name is stuff like "user", "domain", "hooks"...
# category_values is the values of this category (like actions) # category_values is the values of this category (like actions)
for category_name, category_values in actionsmap.items(): for category_name, category_values in actionsmap.items():
if "actions" in category_values: actions = category_values.pop("actions", {})
actions = category_values.pop("actions") subcategories = category_values.pop("subcategories", {})
else:
actions = {}
if "subcategories" in category_values:
subcategories = category_values.pop("subcategories")
else:
subcategories = {}
# Get category parser # Get category parser
category_parser = top_parser.add_category_parser( category_parser = top_parser.add_category_parser(
@ -730,6 +704,7 @@ class ActionsMap(object):
# action_options are the values # action_options are the values
for action_name, action_options in actions.items(): for action_name, action_options in actions.items():
arguments = action_options.pop("arguments", {}) arguments = action_options.pop("arguments", {})
authentication = action_options.pop("authentication", {})
tid = (namespace, category_name, action_name) tid = (namespace, category_name, action_name)
# Get action parser # Get action parser
@ -749,8 +724,9 @@ class ActionsMap(object):
validate_extra=validate_extra, validate_extra=validate_extra,
) )
if "configuration" in action_options: action_parser.authentication = self.default_authentication
category_parser.set_conf(tid, action_options["configuration"]) if interface_type in authentication:
action_parser.authentication = authentication[interface_type]
# subcategory_name is like "cert" in "domain cert status" # subcategory_name is like "cert" in "domain cert status"
# subcategory_values is the values of this subcategory (like actions) # subcategory_values is the values of this subcategory (like actions)
@ -767,6 +743,7 @@ class ActionsMap(object):
# action_options are the values # action_options are the values
for action_name, action_options in actions.items(): for action_name, action_options in actions.items():
arguments = action_options.pop("arguments", {}) arguments = action_options.pop("arguments", {})
authentication = action_options.pop("authentication", {})
tid = (namespace, category_name, subcategory_name, action_name) tid = (namespace, category_name, subcategory_name, action_name)
try: try:
@ -790,10 +767,11 @@ class ActionsMap(object):
validate_extra=validate_extra, validate_extra=validate_extra,
) )
if "configuration" in action_options: action_parser.authentication = self.default_authentication
category_parser.set_conf( if interface_type in authentication:
tid, action_options["configuration"] action_parser.authentication = authentication[
) interface_type
]
logger.debug("building parser took %.3fs", time() - start) logger.debug("building parser took %.3fs", time() - start)
return top_parser return top_parser

View file

@ -0,0 +1,42 @@
# -*- coding: utf-8 -*-
import logging
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):
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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -1,51 +0,0 @@
# -*- coding: utf-8 -*-
import os
from moulinette.globals import init_moulinette_env
def get_cachedir(subdir="", make_dir=True):
"""Get the path to a cache directory
Return the path to the cache directory from an optional
subdirectory and create it if needed.
Keyword arguments:
- subdir -- A cache subdirectory
- make_dir -- False to not make directory if it not exists
"""
CACHE_DIR = init_moulinette_env()["CACHE_DIR"]
path = os.path.join(CACHE_DIR, subdir)
if make_dir and not os.path.isdir(path):
os.makedirs(path)
return path
def open_cachefile(filename, mode="r", subdir=""):
"""Open a cache file and return a stream
Attempt to open in 'mode' the cache file 'filename' from the
default cache directory and in the subdirectory 'subdir' if
given. Directories are created if needed and a stream is
returned if the file can be written.
Keyword arguments:
- filename -- The cache filename
- mode -- The mode in which the file is opened
- **kwargs -- Optional arguments for get_cachedir
"""
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)

View file

@ -6,10 +6,24 @@ import json
import logging import logging
import moulinette import moulinette
from moulinette.globals import init_moulinette_env
logger = logging.getLogger("moulinette.core") logger = logging.getLogger("moulinette.core")
env = {
"DATA_DIR": "/usr/share/moulinette",
"LIB_DIR": "/usr/lib/moulinette",
"LOCALES_DIR": "/usr/share/moulinette/locale",
"CACHE_DIR": "/var/cache/moulinette",
"NAMESPACES": "*", # By default we'll load every namespace we find
}
for key in env.keys():
value_from_environ = os.environ.get(f"MOULINETTE_{key}")
if value_from_environ:
env[key] = value_from_environ
env["NAMESPACES"] = env["NAMESPACES"].split()
def during_unittests_run(): def during_unittests_run():
return "TESTS_RUN" in os.environ return "TESTS_RUN" in os.environ
@ -195,8 +209,7 @@ class Moulinette18n(object):
self.default_locale = default_locale self.default_locale = default_locale
self.locale = default_locale self.locale = default_locale
moulinette_env = init_moulinette_env() self.locales_dir = env["LOCALES_DIR"]
self.locales_dir = moulinette_env["LOCALES_DIR"]
# Init global translator # Init global translator
self._global = Translator(self.locales_dir, default_locale) self._global = Translator(self.locales_dir, default_locale)
@ -217,7 +230,7 @@ class Moulinette18n(object):
""" """
if namespace not in self._namespaces: if namespace not in self._namespaces:
# Create new Translator object # Create new Translator object
lib_dir = init_moulinette_env()["LIB_DIR"] lib_dir = env["LIB_DIR"]
translator = Translator( translator = Translator(
"%s/%s/locales" % (lib_dir, namespace), self.default_locale "%s/%s/locales" % (lib_dir, namespace), self.default_locale
) )
@ -270,113 +283,6 @@ class Moulinette18n(object):
return self._namespaces[self._current_namespace].key_exists(key) 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"):
"""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 ---------------------------------------------- # Moulinette core classes ----------------------------------------------
@ -408,10 +314,6 @@ class MoulinetteAuthenticationError(MoulinetteError):
http_code = 401 http_code = 401
class MoulinetteLdapIsDownError(MoulinetteError):
"""Used when ldap is down"""
class MoulinetteLock(object): class MoulinetteLock(object):
"""Locker for a moulinette instance """Locker for a moulinette instance

View file

@ -1,17 +0,0 @@
"""Moulinette global configuration core."""
from os import environ
def init_moulinette_env():
return {
"DATA_DIR": environ.get("MOULINETTE_DATA_DIR", "/usr/share/moulinette"),
"LIB_DIR": environ.get("MOULINETTE_LIB_DIR", "/usr/lib/moulinette"),
"LOCALES_DIR": environ.get(
"MOULINETTE_LOCALES_DIR", "/usr/share/moulinette/locale"
),
"CACHE_DIR": environ.get("MOULINETTE_CACHE_DIR", "/var/cache/moulinette"),
"NAMESPACES": environ.get(
"MOULINETTE_NAMESPACES", "*"
).split(), # By default we'll load every namespace we find
}

View file

@ -4,14 +4,16 @@ import re
import logging import logging
import argparse import argparse
import copy import copy
import datetime
from collections import deque, OrderedDict from collections import deque, OrderedDict
from json.encoder import JSONEncoder
from moulinette import msettings, m18n from moulinette import m18n
from moulinette.core import MoulinetteError from moulinette.core import MoulinetteError
logger = logging.getLogger("moulinette.interface") logger = logging.getLogger("moulinette.interface")
GLOBAL_SECTION = "_global" # FIXME : are these even used for anything useful ...
TO_RETURN_PROP = "_to_return" TO_RETURN_PROP = "_to_return"
CALLBACKS_PROP = "_callbacks" CALLBACKS_PROP = "_callbacks"
@ -35,15 +37,8 @@ class BaseActionsMapParser(object):
""" """
def __init__(self, parent=None, **kwargs): def __init__(self, parent=None, **kwargs):
if parent: if not parent:
self._o = parent
else:
logger.debug("initializing base actions map parser for %s", self.interface) 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 # Virtual properties
# Each parser classes must implement these properties. # Each parser classes must implement these properties.
@ -121,7 +116,7 @@ class BaseActionsMapParser(object):
"derived class '%s' must override this method" % self.__class__.__name__ "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 """Check if authentication is required to run the requested action
Keyword arguments: Keyword arguments:
@ -163,7 +158,7 @@ class BaseActionsMapParser(object):
): ):
raise MoulinetteError("invalid_usage") raise MoulinetteError("invalid_usage")
elif not tid: elif not tid:
tid = GLOBAL_SECTION tid = "_global"
# Prepare namespace # Prepare namespace
if namespace is None: if namespace is None:
@ -172,151 +167,6 @@ class BaseActionsMapParser(object):
return namespace 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 ------------------------------------------------------ # Argument parser ------------------------------------------------------
@ -712,3 +562,40 @@ class PositionalsFirstHelpFormatter(argparse.HelpFormatter):
# prefix with 'usage:' # prefix with 'usage:'
return "%s%s\n\n" % (prefix, usage) return "%s%s\n\n" % (prefix, usage)
class JSONExtendedEncoder(JSONEncoder):
"""Extended JSON encoder
Extend default JSON encoder to recognize more types and classes. It will
never raise an exception if the object can't be encoded and return its repr
instead.
The following objects and types are supported:
- set: converted into list
"""
def default(self, o):
import pytz # Lazy loading, this takes like 3+ sec on a RPi2 ?!
"""Return a serializable object"""
# Convert compatible containers into list
if isinstance(o, set) or (hasattr(o, "__iter__") and hasattr(o, "next")):
return list(o)
# Display the date in its iso format ISO-8601 Internet Profile (RFC 3339)
if isinstance(o, datetime.date):
if o.tzinfo is None:
o = o.replace(tzinfo=pytz.utc)
return o.isoformat()
# Return the repr for object that json can't encode
logger.warning(
"cannot properly encode in JSON the object %s, " "returned repr is: %r",
type(o),
o,
)
return repr(o)

View file

@ -4,31 +4,39 @@ import re
import errno import errno
import logging import logging
import argparse import argparse
from json import dumps as json_encode from json import dumps as json_encode
from tempfile import mkdtemp
from shutil import rmtree
from gevent import sleep from gevent import sleep
from gevent.queue import Queue from gevent.queue import Queue
from geventwebsocket import WebSocketError from geventwebsocket import WebSocketError
from bottle import request, response, Bottle, HTTPResponse from bottle import request, response, Bottle, HTTPResponse, FileUpload
from bottle import abort from bottle import abort
from moulinette import msignals, m18n, env from moulinette import m18n, Moulinette
from moulinette.actionsmap import ActionsMap from moulinette.actionsmap import ActionsMap
from moulinette.core import MoulinetteError, MoulinetteValidationError from moulinette.core import (
MoulinetteError,
MoulinetteValidationError,
MoulinetteAuthenticationError,
)
from moulinette.interfaces import ( from moulinette.interfaces import (
BaseActionsMapParser, BaseActionsMapParser,
BaseInterface,
ExtendedArgumentParser, ExtendedArgumentParser,
JSONExtendedEncoder,
) )
from moulinette.utils import log from moulinette.utils import log
from moulinette.utils.serialize import JSONExtendedEncoder
from moulinette.utils.text import random_ascii from moulinette.utils.text import random_ascii
logger = log.getLogger("moulinette.interface.api") logger = log.getLogger("moulinette.interface.api")
# API helpers ---------------------------------------------------------- # API helpers ----------------------------------------------------------
# We define a global variable to manage in a dirty way the upload...
UPLOAD_DIR = None
CSRF_TYPES = set( CSRF_TYPES = set(
["text/plain", "application/x-www-form-urlencoded", "multipart/form-data"] ["text/plain", "application/x-www-form-urlencoded", "multipart/form-data"]
@ -62,7 +70,7 @@ def filter_csrf(callback):
class LogQueues(dict): class LogQueues(dict):
"""Map of session id to queue.""" """Map of session ids to queue."""
pass pass
@ -79,9 +87,9 @@ class APIQueueHandler(logging.Handler):
self.queues = LogQueues() self.queues = LogQueues()
def emit(self, record): def emit(self, record):
sid = request.get_cookie("session.id") s_id = Session.get_infos(raise_if_no_session_exists=False)["id"]
try: try:
queue = self.queues[sid] queue = self.queues[s_id]
except KeyError: except KeyError:
# Session is not initialized, abandon. # Session is not initialized, abandon.
return return
@ -111,6 +119,7 @@ class _HTTPArgumentParser(object):
self._positional = [] # list(arg_name) self._positional = [] # list(arg_name)
self._optional = {} # dict({arg_name: option_strings}) self._optional = {} # dict({arg_name: option_strings})
self._upload_dir = None
def set_defaults(self, **kwargs): def set_defaults(self, **kwargs):
return self._parser.set_defaults(**kwargs) return self._parser.set_defaults(**kwargs)
@ -145,9 +154,9 @@ class _HTTPArgumentParser(object):
# Append newly created action # Append newly created action
if len(action.option_strings) == 0: if len(action.option_strings) == 0:
self._positional.append(action.dest) self._positional.append(action)
else: else:
self._optional[action.dest] = action.option_strings self._optional[action.dest] = action
return action return action
@ -155,11 +164,26 @@ class _HTTPArgumentParser(object):
arg_strings = [] arg_strings = []
# Append an argument to the current one # Append an argument to the current one
def append(arg_strings, value, option_string=None): def append(arg_strings, value, action):
if isinstance(value, bool): option_string = None
if len(action.option_strings) > 0:
option_string = action.option_strings[0]
if isinstance(value, bool) or isinstance(action.const, bool):
# Append the option string only # Append the option string only
if option_string is not None and value != 0:
arg_strings.append(option_string)
elif isinstance(value, FileUpload) and (
isinstance(action.type, argparse.FileType) or action.type == open
):
# Upload the file in a temp directory
global UPLOAD_DIR
if UPLOAD_DIR is None:
UPLOAD_DIR = mkdtemp(prefix="moulinette_upload_")
value.save(UPLOAD_DIR)
if option_string is not None: if option_string is not None:
arg_strings.append(option_string) arg_strings.append(option_string)
arg_strings.append(UPLOAD_DIR + "/" + value.filename)
elif isinstance(value, str): elif isinstance(value, str):
if option_string is not None: if option_string is not None:
arg_strings.append(option_string) arg_strings.append(option_string)
@ -192,14 +216,14 @@ class _HTTPArgumentParser(object):
return arg_strings return arg_strings
# Iterate over positional arguments # Iterate over positional arguments
for dest in self._positional: for action in self._positional:
if dest in args: if action.dest in args:
arg_strings = append(arg_strings, args[dest]) arg_strings = append(arg_strings, args[action.dest], action)
# Iterate over optional arguments # Iterate over optional arguments
for dest, opt in self._optional.items(): for dest, action in self._optional.items():
if dest in args: if dest in args:
arg_strings = append(arg_strings, args[dest], opt[0]) arg_strings = append(arg_strings, args[dest], action)
return self._parser.parse_args(arg_strings, namespace) return self._parser.parse_args(arg_strings, namespace)
@ -210,6 +234,46 @@ class _HTTPArgumentParser(object):
raise MoulinetteValidationError(message, raw_msg=True) 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,
httponly=True,
# samesite="strict", # Bottle 0.12 doesn't support samesite, to be added in next versions
)
def get_infos(raise_if_no_session_exists=True):
try:
infos = request.get_cookie(
f"session.{Session.actionsmap_name}", secret=Session.secret, default={}
)
except Exception:
if not raise_if_no_session_exists:
return {"id": random_ascii()}
raise MoulinetteAuthenticationError("unable_authenticate")
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)
response.delete_cookie(f"session.{Session.actionsmap_name}")
class _ActionsMapPlugin(object): class _ActionsMapPlugin(object):
"""Actions map Bottle Plugin """Actions map Bottle Plugin
@ -226,14 +290,10 @@ class _ActionsMapPlugin(object):
api = 2 api = 2
def __init__(self, actionsmap, log_queues={}): 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.actionsmap = actionsmap
self.log_queues = log_queues self.log_queues = log_queues
# TODO: Save and load secrets? Session.actionsmap_name = actionsmap.name
self.secrets = {}
def setup(self, app): def setup(self, app):
"""Setup plugin on the application """Setup plugin on the application
@ -244,28 +304,6 @@ class _ActionsMapPlugin(object):
- app -- The application instance - 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 # Append authentication routes
app.route( app.route(
@ -274,7 +312,6 @@ class _ActionsMapPlugin(object):
method="POST", method="POST",
callback=self.login, callback=self.login,
skip=["actionsmap"], skip=["actionsmap"],
apply=_login,
) )
app.route( app.route(
"/logout", "/logout",
@ -282,7 +319,6 @@ class _ActionsMapPlugin(object):
method="GET", method="GET",
callback=self.logout, callback=self.logout,
skip=["actionsmap"], skip=["actionsmap"],
apply=_logout,
) )
# Append messages route # Append messages route
@ -319,8 +355,12 @@ class _ActionsMapPlugin(object):
# Format boolean params # Format boolean params
for a in args: for a in args:
params[a] = True params[a] = True
# Append other request params # Append other request params
for k, v in dict(request.params.decode()).items(): req_params = list(request.params.decode().dict.items())
# TODO test special chars in filename
req_params += list(request.files.dict.items())
for k, v in req_params:
v = _format(v) v = _format(v)
if k not in params.keys(): if k not in params.keys():
params[k] = v params[k] = v
@ -343,101 +383,72 @@ class _ActionsMapPlugin(object):
# Routes callbacks # Routes callbacks
def login(self, password, profile): def login(self):
"""Log in to an authenticator profile """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 register it with the current session - a new one will be created
if needed. if needed.
Keyword arguments:
- password -- A clear text password
- profile -- The authenticator profile name to log in
""" """
# Retrieve session values
try: credentials = request.POST.credentials
s_id = request.get_cookie("session.id") or random_ascii() # Apparently even if the key doesn't exists, request.POST.foobar just returns empty string...
except: if not credentials:
# Super rare case where there are super weird cookie / cache issue raise HTTPResponse("Missing credentials parameter", 400)
# Previous line throws a CookieError that creates a 500 error ...
# So let's catch it and just use a fresh ID then... profile = request.POST.profile
s_id = random_ascii() if not profile:
profile = self.actionsmap.default_authentication
authenticator = self.actionsmap.get_authenticator(profile)
try: try:
s_secret = self.secrets[s_id] auth_info = authenticator.authenticate_credentials(credentials)
except KeyError: session_infos = Session.get_infos(raise_if_no_session_exists=False)
s_tokens = {} session_infos[profile] = auth_info
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))
except MoulinetteError as e: except MoulinetteError as e:
if len(s_tokens) > 0: try:
try: self.logout()
self.logout(profile) except Exception:
except: pass
pass
raise HTTPResponse(e.strerror, 401) raise HTTPResponse(e.strerror, 401)
else: else:
# Update dicts with new values Session.set_infos(session_infos)
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
)
return m18n.g("logged_in") return m18n.g("logged_in")
def logout(self, profile): # This is called before each time a route is going to be processed
"""Log out from an authenticator profile 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: try:
s_secret = self.secrets[s_id] session_infos = Session.get_infos()[authenticator.name]
# Here, maybe we want to re-authenticate the session via the authenticator
# For example to check that the username authenticated is still in the admin group...
except Exception:
msg = m18n.g("authentication_required")
raise HTTPResponse(msg, 401)
return session_infos
def logout(self):
try:
Session.get_infos()
except KeyError: 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) raise HTTPResponse(m18n.g("not_logged_in"), 401)
else: 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 # Delete cookie and clean the session
response.set_cookie("session.tokens", "", max_age=-1) Session.delete_infos()
return m18n.g("logged_out") return m18n.g("logged_out")
def messages(self): def messages(self):
"""Listen to the messages WebSocket stream """Listen to the messages WebSocket stream
Retrieve the WebSocket stream and send to it each messages displayed by Retrieve the WebSocket stream and send to it each messages displayed by
the core.MoulinetteSignals.display signal. They are JSON encoded as a the display method. They are JSON encoded as a dict { style: message }.
dict { style: message }.
""" """
s_id = request.get_cookie("session.id") s_id = Session.get_infos()["id"]
try: try:
queue = self.log_queues[s_id] queue = self.log_queues[s_id]
except KeyError: except KeyError:
@ -480,6 +491,7 @@ class _ActionsMapPlugin(object):
- arguments -- A dict of arguments for the route - arguments -- A dict of arguments for the route
""" """
try: try:
ret = self.actionsmap.process(arguments, timeout=30, route=_route) ret = self.actionsmap.process(arguments, timeout=30, route=_route)
except MoulinetteError as e: except MoulinetteError as e:
@ -495,41 +507,26 @@ class _ActionsMapPlugin(object):
else: else:
return format_for_response(ret) return format_for_response(ret)
finally: finally:
# Clean upload directory
# FIXME do that in a better way
global UPLOAD_DIR
if UPLOAD_DIR is not None:
rmtree(UPLOAD_DIR, True)
UPLOAD_DIR = None
# Close opened WebSocket by putting StopIteration in the queue # Close opened WebSocket by putting StopIteration in the queue
try: try:
queue = self.log_queues[request.get_cookie("session.id")] s_id = Session.get_infos()["id"]
queue = self.log_queues[s_id]
except KeyError: except KeyError:
pass pass
else: else:
queue.put(StopIteration) queue.put(StopIteration)
# Signals handlers def display(self, message, style="info"):
def _do_authenticate(self, authenticator): s_id = Session.get_infos(raise_if_no_session_exists=False)["id"]
"""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")
try: try:
queue = self.log_queues[s_id] queue = self.log_queues[s_id]
except KeyError: except KeyError:
@ -542,6 +539,9 @@ class _ActionsMapPlugin(object):
# populate the new message in the queue # populate the new message in the queue
sleep(0) sleep(0)
def prompt(self, *args, **kwargs):
raise NotImplementedError("Prompt is not implemented for this interface")
# HTTP Responses ------------------------------------------------------- # HTTP Responses -------------------------------------------------------
@ -663,31 +663,17 @@ class ActionsMapParser(BaseActionsMapParser):
# Return the created parser # Return the created parser
return parser return parser
def auth_required(self, args, **kwargs): def auth_method(self, _, route):
try: try:
# Retrieve the tid for the route # Retrieve the tid for the route
tid, _ = self._parsers[kwargs.get("route")] _, parser = self._parsers[route]
except KeyError as e: except KeyError as e:
error_message = "no argument parser found for route '%s': %s" % ( error_message = "no argument parser found for route '%s': %s" % (route, e)
kwargs.get("route"),
e,
)
logger.error(error_message) logger.error(error_message)
raise MoulinetteValidationError(error_message, raw_msg=True) raise MoulinetteValidationError(error_message, raw_msg=True)
if self.get_conf(tid, "authenticate"): return parser.authentication
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
def parse_args(self, args, route, **kwargs): def parse_args(self, args, route, **kwargs):
"""Parse arguments """Parse arguments
@ -733,7 +719,7 @@ class ActionsMapParser(BaseActionsMapParser):
return key return key
class Interface(BaseInterface): class Interface:
"""Application Programming Interface for the moulinette """Application Programming Interface for the moulinette
@ -748,15 +734,16 @@ class Interface(BaseInterface):
""" """
def __init__(self, routes={}, log_queues=None): type = "api"
def __init__(self, routes={}):
actionsmap = ActionsMap(ActionsMapParser()) actionsmap = ActionsMap(ActionsMapParser())
# Attempt to retrieve log queues from an APIQueueHandler # Attempt to retrieve log queues from an APIQueueHandler
if log_queues is None: handler = log.getHandlersByClass(APIQueueHandler, limit=1)
handler = log.getHandlersByClass(APIQueueHandler, limit=1) if handler:
if handler: log_queues = handler.queues
log_queues = handler.queues
# TODO: Return OK to 'OPTIONS' xhr requests (l173) # TODO: Return OK to 'OPTIONS' xhr requests (l173)
app = Bottle(autojson=True) app = Bottle(autojson=True)
@ -785,11 +772,12 @@ class Interface(BaseInterface):
app.install(filter_csrf) app.install(filter_csrf)
app.install(apiheader) app.install(apiheader)
app.install(api18n) app.install(api18n)
app.install(_ActionsMapPlugin(actionsmap, log_queues)) actionsmapplugin = _ActionsMapPlugin(actionsmap, log_queues)
app.install(actionsmapplugin)
# Append default routes self.authenticate = actionsmapplugin.authenticate
# app.route(['/api', '/api/<category:re:[a-z]+>'], method='GET', self.display = actionsmapplugin.display
# callback=self.doc, skip=['actionsmap']) self.prompt = actionsmapplugin.prompt
# Append additional routes # Append additional routes
# TODO: Add optional authentication to those routes? # TODO: Add optional authentication to those routes?
@ -798,6 +786,8 @@ class Interface(BaseInterface):
self._app = app self._app = app
Moulinette._interface = self
def run(self, host="localhost", port=80): def run(self, host="localhost", port=80):
"""Run the moulinette """Run the moulinette
@ -809,6 +799,7 @@ class Interface(BaseInterface):
- port -- Server port to bind to - port -- Server port to bind to
""" """
logger.debug( logger.debug(
"starting the server instance in %s:%d", "starting the server instance in %s:%d",
host, host,
@ -831,25 +822,3 @@ class Interface(BaseInterface):
if e.args[0] == errno.EADDRINUSE: if e.args[0] == errno.EADDRINUSE:
raise MoulinetteError("server_already_running") raise MoulinetteError("server_already_running")
raise MoulinetteError(error_message) 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

View file

@ -5,19 +5,17 @@ import sys
import getpass import getpass
import locale import locale
import logging import logging
from argparse import SUPPRESS import argparse
from collections import OrderedDict from collections import OrderedDict
from datetime import date, datetime from datetime import date, datetime
import argcomplete from moulinette import m18n, Moulinette
from moulinette import msignals, m18n
from moulinette.actionsmap import ActionsMap from moulinette.actionsmap import ActionsMap
from moulinette.core import MoulinetteError, MoulinetteValidationError from moulinette.core import MoulinetteError, MoulinetteValidationError
from moulinette.interfaces import ( from moulinette.interfaces import (
BaseActionsMapParser, BaseActionsMapParser,
BaseInterface,
ExtendedArgumentParser, ExtendedArgumentParser,
JSONExtendedEncoder,
) )
from moulinette.utils import log from moulinette.utils import log
@ -33,17 +31,15 @@ from moulinette.utils import log
# But it display instead: # But it display instead:
# Error: unable to parse arguments 'firewall' because: sequence item 0: expected str instance, NoneType found # Error: unable to parse arguments 'firewall' because: sequence item 0: expected str instance, NoneType found
import argparse
def monkey_get_action_name(argument): def monkey_get_action_name(argument):
if argument is None: if argument is None:
return None return None
elif argument.option_strings: elif argument.option_strings:
return "/".join(argument.option_strings) return "/".join(argument.option_strings)
elif argument.metavar not in (None, SUPPRESS): elif argument.metavar not in (None, argparse.SUPPRESS):
return argument.metavar return argument.metavar
elif argument.dest not in (None, SUPPRESS): elif argument.dest not in (None, argparse.SUPPRESS):
return argument.dest return argument.dest
elif argument.choices: elif argument.choices:
return "{" + ",".join(argument.choices) + "}" return "{" + ",".join(argument.choices) + "}"
@ -308,7 +304,7 @@ class ActionsMapParser(BaseActionsMapParser):
# Append each top parser action to the global group # Append each top parser action to the global group
for action in top_parser._actions: for action in top_parser._actions:
action.dest = SUPPRESS action.dest = argparse.SUPPRESS
self.global_parser._add_action(action) self.global_parser._add_action(action)
# Implement virtual properties # Implement virtual properties
@ -356,7 +352,7 @@ class ActionsMapParser(BaseActionsMapParser):
type_="subcategory", type_="subcategory",
description=subcategory_help, description=subcategory_help,
help=subcategory_help, help=subcategory_help,
**kwargs **kwargs,
) )
return self.__class__(self, parser, {"title": "actions", "required": True}) return self.__class__(self, parser, {"title": "actions", "required": True})
@ -367,7 +363,7 @@ class ActionsMapParser(BaseActionsMapParser):
action_help=None, action_help=None,
deprecated=False, deprecated=False,
deprecated_alias=[], deprecated_alias=[],
**kwargs **kwargs,
): ):
"""Add a parser for an action """Add a parser for an action
@ -398,7 +394,7 @@ class ActionsMapParser(BaseActionsMapParser):
self.global_parser.add_argument(*names, **argument_options) 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 # FIXME? idk .. this try/except is duplicated from parse_args below
# Just to be able to obtain the tid # Just to be able to obtain the tid
try: try:
@ -414,19 +410,23 @@ class ActionsMapParser(BaseActionsMapParser):
raise MoulinetteValidationError(error_message, raw_msg=True) raise MoulinetteValidationError(error_message, raw_msg=True)
tid = getattr(ret, "_tid", None) tid = getattr(ret, "_tid", None)
if self.get_conf(tid, "authenticate"):
authenticator = self.get_conf(tid, "authenticator")
# If several authenticator, use the default one # Ugh that's for yunohost --version ...
if isinstance(authenticator, dict): if tid is None:
if "default" in authenticator: return None
authenticator = "default"
else: # We go down in the subparser tree until we find the leaf
# TODO which one should we use? # corresponding to the tid with a defined authentication
pass # (yeah it's a mess because the datastructure is a mess..)
return authenticator _p = self._subparsers
else: for word in tid[1:]:
return False _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): def parse_args(self, args, **kwargs):
try: try:
@ -446,7 +446,7 @@ class ActionsMapParser(BaseActionsMapParser):
return ret return ret
class Interface(BaseInterface): class Interface:
"""Command-line Interface for the moulinette """Command-line Interface for the moulinette
@ -458,22 +458,20 @@ class Interface(BaseInterface):
""" """
type = "cli"
def __init__(self, top_parser=None, load_only_category=None): def __init__(self, top_parser=None, load_only_category=None):
# Set user locale # Set user locale
m18n.set_locale(get_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( self.actionsmap = ActionsMap(
ActionsMapParser(top_parser=top_parser), ActionsMapParser(top_parser=top_parser),
load_only_category=load_only_category, load_only_category=load_only_category,
) )
Moulinette._interface = self
def run(self, args, output_as=None, timeout=None): def run(self, args, output_as=None, timeout=None):
"""Run the moulinette """Run the moulinette
@ -489,15 +487,10 @@ 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 - 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"]: if output_as and output_as not in ["json", "plain", "none"]:
raise MoulinetteValidationError("invalid_usage") raise MoulinetteValidationError("invalid_usage")
# auto-complete
argcomplete.autocomplete(self.actionsmap.parser._parser)
# Set handler for authentication
msignals.set_handler("authenticate", self._do_authenticate)
try: try:
ret = self.actionsmap.process(args, timeout=timeout) ret = self.actionsmap.process(args, timeout=timeout)
except (KeyboardInterrupt, EOFError): except (KeyboardInterrupt, EOFError):
@ -510,7 +503,6 @@ class Interface(BaseInterface):
if output_as: if output_as:
if output_as == "json": if output_as == "json":
import json import json
from moulinette.utils.serialize import JSONExtendedEncoder
print(json.dumps(ret, cls=JSONExtendedEncoder)) print(json.dumps(ret, cls=JSONExtendedEncoder))
else: else:
@ -520,32 +512,28 @@ class Interface(BaseInterface):
else: else:
print(ret) print(ret)
# Signals handlers def authenticate(self, authenticator):
def _do_authenticate(self, authenticator):
"""Process the authentication
Handle the core.MoulinetteSignals.authenticate signal.
"""
# Hmpf we have no-use case in yunohost anymore where we need to auth # Hmpf we have no-use case in yunohost anymore where we need to auth
# because everything is run as root ... # because everything is run as root ...
# I guess we could imagine some yunohost-independant use-case where # 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 # moulinette is used to create a CLI for non-root user that needs to
# auth somehow but hmpf -.- # auth somehow but hmpf -.-
help = authenticator.extra.get("help") msg = m18n.g("password")
msg = m18n.n(help) if help else m18n.g("password") credentials = self.prompt(msg, True, False, color="yellow")
return authenticator(password=self._do_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 """Prompt for a value
Handle the core.MoulinetteSignals.prompt signal.
Keyword arguments: Keyword arguments:
- color -- The color to use for prompting message - 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: if is_password:
prompt = lambda m: getpass.getpass(colorize(m18n.g("colon", m), color)) prompt = lambda m: getpass.getpass(colorize(m18n.g("colon", m), color))
else: else:
@ -559,12 +547,8 @@ class Interface(BaseInterface):
return value return value
def _do_display(self, message, style): def display(self, message, style="info"): # i18n: info
"""Display a message """Display a message"""
Handle the core.MoulinetteSignals.display signal.
"""
if style == "success": if style == "success":
print("{} {}".format(colorize(m18n.g("success"), "green"), message)) print("{} {}".format(colorize(m18n.g("success"), "green"), message))
elif style == "warning": elif style == "warning":

View file

@ -107,41 +107,6 @@ def read_toml(file_path):
return loaded_toml 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"): def write_to_file(file_path, data, file_mode="w"):
""" """
Write a single string or a list of string to a text file. Write a single string or a list of string to a text file.

View file

@ -2,6 +2,7 @@ import subprocess
import os import os
import threading import threading
import queue import queue
import logging
# This import is unused in this file. It will be deleted in future (W0611 PEP8), # This import is unused in this file. It will be deleted in future (W0611 PEP8),
# but for the momment we keep it due to yunohost moulinette script that used # but for the momment we keep it due to yunohost moulinette script that used
@ -12,7 +13,7 @@ quote # This line is here to avoid W0611 PEP8 error (see comments above)
# Prevent to import subprocess only for common classes # Prevent to import subprocess only for common classes
CalledProcessError = subprocess.CalledProcessError CalledProcessError = subprocess.CalledProcessError
logger = logging.getLogger("moulinette.utils.process")
# Alternative subprocess methods --------------------------------------- # Alternative subprocess methods ---------------------------------------
@ -70,6 +71,11 @@ def call_async_output(args, callback, **kwargs):
kwargs["env"] = os.environ kwargs["env"] = os.environ
kwargs["env"]["YNH_STDINFO"] = str(stdinfo.fdWrite) kwargs["env"]["YNH_STDINFO"] = str(stdinfo.fdWrite)
if "env" in kwargs and not all(isinstance(v, str) for v in kwargs["env"].values()):
logger.warning(
"While trying to call call_async_output: env contained non-string values, probably gonna cause issue in Popen(...)"
)
try: try:
p = subprocess.Popen(args, **kwargs) p = subprocess.Popen(args, **kwargs)

View file

@ -1,45 +0,0 @@
import logging
from json.encoder import JSONEncoder
import datetime
logger = logging.getLogger("moulinette.utils.serialize")
# JSON utilities -------------------------------------------------------
class JSONExtendedEncoder(JSONEncoder):
"""Extended JSON encoder
Extend default JSON encoder to recognize more types and classes. It will
never raise an exception if the object can't be encoded and return its repr
instead.
The following objects and types are supported:
- set: converted into list
"""
def default(self, o):
import pytz # Lazy loading, this takes like 3+ sec on a RPi2 ?!
"""Return a serializable object"""
# Convert compatible containers into list
if isinstance(o, set) or (hasattr(o, "__iter__") and hasattr(o, "next")):
return list(o)
# Display the date in its iso format ISO-8601 Internet Profile (RFC 3339)
if isinstance(o, datetime.date):
if o.tzinfo is None:
o = o.replace(tzinfo=pytz.utc)
return o.isoformat()
# Return the repr for object that json can't encode
logger.warning(
"cannot properly encode in JSON the object %s, " "returned repr is: %r",
type(o),
o,
)
return repr(o)

View file

@ -3,57 +3,56 @@
import os import os
import sys import sys
from setuptools import setup, find_packages from setuptools import setup, find_packages
from moulinette.globals import init_moulinette_env from moulinette import env
LOCALES_DIR = init_moulinette_env()['LOCALES_DIR'] LOCALES_DIR = env["LOCALES_DIR"]
# Extend installation # Extend installation
locale_files = [] locale_files = []
if "install" in sys.argv: if "install" in sys.argv:
# Evaluate locale files # Evaluate locale files
for f in os.listdir('locales'): for f in os.listdir("locales"):
if f.endswith('.json'): if f.endswith(".json"):
locale_files.append('locales/%s' % f) locale_files.append("locales/%s" % f)
install_deps = [ install_deps = [
'argcomplete', "psutil",
'psutil', "pytz",
'pytz', "pyyaml",
'pyyaml', "toml",
'toml', "gevent-websocket",
'python-ldap', "bottle",
'gevent-websocket',
'bottle',
] ]
test_deps = [ test_deps = [
'pytest', "pytest",
'pytest-cov', "pytest-cov",
'pytest-env', "pytest-env",
'pytest-mock', "pytest-mock",
'requests', "requests",
'requests-mock', "requests-mock",
'webtest' "webtest",
] ]
extras = { extras = {
'install': install_deps, "install": install_deps,
'tests': test_deps, "tests": test_deps,
} }
setup(name='Moulinette', setup(
version='2.0.0', name="Moulinette",
description='Prototype interfaces quickly and easily', version="2.0.0",
author='Yunohost Team', description="Prototype interfaces quickly and easily",
author_email='yunohost@yunohost.org', author="Yunohost Team",
url='http://yunohost.org', author_email="yunohost@yunohost.org",
license='AGPL', url="http://yunohost.org",
packages=find_packages(exclude=['test']), license="AGPL",
data_files=[(LOCALES_DIR, locale_files)], packages=find_packages(exclude=["test"]),
python_requires='>=3.7.*, <3.8', data_files=[(LOCALES_DIR, locale_files)],
install_requires=install_deps, python_requires=">=3.7.*, <3.8",
tests_require=test_deps, install_requires=install_deps,
extras_require=extras, tests_require=test_deps,
) extras_require=extras,
)

View file

@ -3,23 +3,10 @@
# Global parameters # # Global parameters #
############################# #############################
_global: _global:
configuration: name: moulitest
authenticate: authentication:
- all api: dummy
authenticator: cli: dummy
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
arguments: arguments:
-v: -v:
full: --version full: --version
@ -43,37 +30,30 @@ testauth:
actions: actions:
none: none:
api: GET /test-auth/none api: GET /test-auth/none
configuration: authentication:
authenticate: false api: null
cli: null
default: default:
api: GET /test-auth/default api: GET /test-auth/default
only-api: only-api:
api: GET /test-auth/only-api api: GET /test-auth/only-api
configuration: authentication:
authenticate: api: dummy
- api cli: null
only-cli: only-cli:
api: GET /test-auth/only-cli api: GET /test-auth/only-cli
configuration: authentication:
authenticate: api: null
- cli cli: dummy
other-profile: other-profile:
api: GET /test-auth/other-profile api: GET /test-auth/other-profile
configuration: authentication:
authenticate: api: yoloswag
- all cli: yoloswag
authenticator: yoloswag
ldap:
api: GET /test-auth/ldap
configuration:
authenticate:
- all
authenticator: ldap
with_arg: with_arg:
api: GET /test-auth/with_arg/<super_arg> api: GET /test-auth/with_arg/<super_arg>
@ -103,21 +83,21 @@ testauth:
actions: actions:
none: none:
api: GET /test-auth/subcat/none api: GET /test-auth/subcat/none
configuration: authentication:
authenticate: false api: null
cli: null
default: default:
api: GET /test-auth/subcat/default api: GET /test-auth/subcat/default
post: post:
api: POST /test-auth/subcat/post api: POST /test-auth/subcat/post
configuration: authentication:
authenticate: api: dummy
- all cli: dummy
authenticator: default
other-profile: other-profile:
api: GET /test-auth/subcat/other-profile api: GET /test-auth/subcat/other-profile
configuration: authentication:
authenticator: yoloswag api: yoloswag
cli: yoloswag

View file

@ -7,8 +7,6 @@ import os
import shutil import shutil
import pytest import pytest
from .src.ldap_server import LDAPServer
def patch_init(moulinette): def patch_init(moulinette):
"""Configure moulinette to use the YunoHost namespace.""" """Configure moulinette to use the YunoHost namespace."""
@ -95,9 +93,9 @@ def moulinette(tmp_path_factory):
tmp_cache = str(tmp_path_factory.mktemp("cache")) tmp_cache = str(tmp_path_factory.mktemp("cache"))
tmp_data = str(tmp_path_factory.mktemp("data")) tmp_data = str(tmp_path_factory.mktemp("data"))
tmp_lib = str(tmp_path_factory.mktemp("lib")) tmp_lib = str(tmp_path_factory.mktemp("lib"))
os.environ["MOULINETTE_CACHE_DIR"] = tmp_cache moulinette.env["CACHE_DIR"] = tmp_cache
os.environ["MOULINETTE_DATA_DIR"] = tmp_data moulinette.env["DATA_DIR"] = tmp_data
os.environ["MOULINETTE_LIB_DIR"] = tmp_lib moulinette.env["LIB_DIR"] = tmp_lib
shutil.copytree("./test/actionsmap", "%s/actionsmap" % tmp_data) shutil.copytree("./test/actionsmap", "%s/actionsmap" % tmp_data)
shutil.copytree("./test/src", "%s/%s" % (tmp_lib, namespace)) shutil.copytree("./test/src", "%s/%s" % (tmp_lib, namespace))
shutil.copytree("./test/locales", "%s/%s/locales" % (tmp_lib, namespace)) shutil.copytree("./test/locales", "%s/%s/locales" % (tmp_lib, namespace))
@ -182,25 +180,6 @@ def test_toml(tmp_path):
return test_file 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 @pytest.fixture
def user(): def user():
return os.getlogin() return os.getlogin()
@ -209,11 +188,3 @@ def user():
@pytest.fixture @pytest.fixture
def test_url(): def test_url():
return "https://some.test.url/yolo.txt" return "https://some.test.url/yolo.txt"
@pytest.fixture
def ldap_server():
server = LDAPServer()
server.start()
yield server
server.stop()

View file

@ -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"

View file

@ -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

View file

@ -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 )
)

View file

@ -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 )
)

View file

@ -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 ) )

View file

@ -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 )
)

View file

@ -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 ) )

View file

@ -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

View file

@ -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

View file

@ -0,0 +1,25 @@
import json
import glob
from collections import OrderedDict
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())
for locale_file in locale_files:
print(locale_file)
this_locale = json.loads(
open(locale_folder + locale_file).read(), object_pairs_hook=OrderedDict
)
this_locale_fixed = {k: v for k, v in this_locale.items() if k in reference}
json.dump(
this_locale_fixed,
open(locale_folder + locale_file, "w"),
indent=4,
ensure_ascii=False,
)

View 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", raw_msg=True)
return

View 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", raw_msg=True)
return

View file

@ -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)

View file

@ -34,10 +34,6 @@ def testauth_only_cli():
return "some_data_from_only_cli" return "some_data_from_only_cli"
def testauth_ldap():
return "some_data_from_ldap"
def testauth_with_arg(super_arg): def testauth_with_arg(super_arg):
return super_arg return super_arg

View file

@ -10,15 +10,17 @@ from moulinette.actionsmap import (
ActionsMap, ActionsMap,
) )
from moulinette.interfaces import GLOBAL_SECTION
from moulinette.interfaces import BaseActionsMapParser
from moulinette.core import MoulinetteError from moulinette.core import MoulinetteError
from moulinette import m18n from moulinette import m18n, Moulinette
@pytest.fixture @pytest.fixture
def iface(): def iface():
return "iface" class DummyInterface:
def prompt():
pass
return DummyInterface()
def test_comment_parameter_bad_bool_value(iface, caplog): def test_comment_parameter_bad_bool_value(iface, caplog):
@ -68,10 +70,11 @@ def test_ask_parameter(iface, mocker):
arg = ask("foobar", "a", "a") arg = ask("foobar", "a", "a")
assert arg == "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(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) arg = ask("foobar", "a", None)
assert arg == "awesome_test" assert arg == "awesome_test"
@ -81,10 +84,11 @@ def test_password_parameter(iface, mocker):
arg = ask("foobar", "a", "a") arg = ask("foobar", "a", "a")
assert arg == "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(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) arg = ask("foobar", "a", None)
assert arg == "awesome_test" assert arg == "awesome_test"
@ -157,14 +161,14 @@ def test_required_paremeter_missing_value(iface, caplog):
def test_actions_map_unknown_authenticator(monkeypatch, tmp_path): 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()) from moulinette.interfaces.api import ActionsMapParser
with pytest.raises(ValueError) as exception:
amap.get_authenticator_for_profile("unknown") amap = ActionsMap(ActionsMapParser())
assert "Unknown authenticator" in str(exception)
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): 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" assert extra_argument_parse._extra_params["Test"]["foo"]["ask"] == "lol"
extra_argument_parse = ExtraArgumentParser(iface) extra_argument_parse = ExtraArgumentParser(iface)
extra_argument_parse.add_argument(GLOBAL_SECTION, "foo", {"ask": "lol"}) extra_argument_parse.add_argument("_global", "foo", {"ask": "lol"})
assert GLOBAL_SECTION in extra_argument_parse._extra_params assert "_global" in extra_argument_parse._extra_params
assert "foo" in extra_argument_parse._extra_params[GLOBAL_SECTION] assert "foo" in extra_argument_parse._extra_params["_global"]
assert "ask" in extra_argument_parse._extra_params[GLOBAL_SECTION]["foo"] assert "ask" in extra_argument_parse._extra_params["_global"]["foo"]
assert extra_argument_parse._extra_params[GLOBAL_SECTION]["foo"]["ask"] == "lol" assert extra_argument_parse._extra_params["_global"]["foo"]["ask"] == "lol"
def test_extra_argument_parser_add_argument_bad_arg(iface): def test_extra_argument_parser_add_argument_bad_arg(iface):
extra_argument_parse = ExtraArgumentParser(iface) extra_argument_parse = ExtraArgumentParser(iface)
with pytest.raises(MoulinetteError) as exception: 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" % ( expected_msg = "unable to validate extra parameter '%s' for argument '%s': %s" % (
"ask", "ask",
@ -196,23 +200,23 @@ def test_extra_argument_parser_add_argument_bad_arg(iface):
assert expected_msg in str(exception) assert expected_msg in str(exception)
extra_argument_parse = ExtraArgumentParser(iface) 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 "_global" in extra_argument_parse._extra_params
assert "foo" in extra_argument_parse._extra_params[GLOBAL_SECTION] assert "foo" in extra_argument_parse._extra_params["_global"]
assert not len(extra_argument_parse._extra_params[GLOBAL_SECTION]["foo"]) assert not len(extra_argument_parse._extra_params["_global"]["foo"])
def test_extra_argument_parser_parse_args(iface, mocker): def test_extra_argument_parser_parse_args(iface, mocker):
extra_argument_parse = ExtraArgumentParser(iface) extra_argument_parse = ExtraArgumentParser(iface)
extra_argument_parse.add_argument(GLOBAL_SECTION, "foo", {"ask": "lol"}) extra_argument_parse.add_argument("_global", "foo", {"ask": "lol"})
extra_argument_parse.add_argument(GLOBAL_SECTION, "foo2", {"ask": "lol2"}) extra_argument_parse.add_argument("_global", "foo2", {"ask": "lol2"})
extra_argument_parse.add_argument( extra_argument_parse.add_argument(
GLOBAL_SECTION, "bar", {"password": "lul", "ask": "lul"} "_global", "bar", {"password": "lul", "ask": "lul"}
) )
args = extra_argument_parse.parse_args( 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 assert "foo" in args
@ -228,23 +232,17 @@ def test_extra_argument_parser_parse_args(iface, mocker):
def test_actions_map_api(): def test_actions_map_api():
from moulinette.interfaces.api import ActionsMapParser from moulinette.interfaces.api import ActionsMapParser
amap = ActionsMap(ActionsMapParser()) parser = ActionsMapParser()
amap = ActionsMap(parser)
assert amap.parser.global_conf["authenticate"] == "all" assert amap.main_namespace == "moulitest"
assert "default" in amap.parser.global_conf["authenticator"] assert amap.default_authentication == "dummy"
assert "yoloswag" in amap.parser.global_conf["authenticator"]
assert ("GET", "/test-auth/default") in amap.parser.routes assert ("GET", "/test-auth/default") in amap.parser.routes
assert ("POST", "/test-auth/subcat/post") in amap.parser.routes assert ("POST", "/test-auth/subcat/post") in amap.parser.routes
amap.generate_cache("moulitest") assert parser.auth_method(None, ("GET", "/test-auth/default")) == "dummy"
assert parser.auth_method(None, ("GET", "/test-auth/only-api")) == "dummy"
amap = ActionsMap(ActionsMapParser()) assert parser.auth_method(None, ("GET", "/test-auth/only-cli")) is None
assert amap.parser.global_conf["authenticate"] == "all"
assert "default" in amap.parser.global_conf["authenticator"]
assert "yoloswag" in amap.parser.global_conf["authenticator"]
assert ("GET", "/test-auth/default") in amap.parser.routes
assert ("POST", "/test-auth/subcat/post") in amap.parser.routes
def test_actions_map_import_error(mocker): def test_actions_map_import_error(mocker):
@ -280,18 +278,19 @@ def test_actions_map_cli():
from moulinette.interfaces.cli import ActionsMapParser from moulinette.interfaces.cli import ActionsMapParser
import argparse import argparse
parser = argparse.ArgumentParser(add_help=False) top_parser = argparse.ArgumentParser(add_help=False)
parser.add_argument( top_parser.add_argument(
"--debug", "--debug",
action="store_true", action="store_true",
default=False, default=False,
help="Log and print debug messages", help="Log and print debug messages",
) )
amap = ActionsMap(ActionsMapParser(top_parser=parser))
assert amap.parser.global_conf["authenticate"] == "all" parser = ActionsMapParser(top_parser=top_parser)
assert "default" in amap.parser.global_conf["authenticator"] amap = ActionsMap(parser)
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 "testauth" in amap.parser._subparsers.choices
assert "none" in amap.parser._subparsers.choices["testauth"]._actions[1].choices assert "none" in amap.parser._subparsers.choices["testauth"]._actions[1].choices
assert "subcat" in amap.parser._subparsers.choices["testauth"]._actions[1].choices assert "subcat" in amap.parser._subparsers.choices["testauth"]._actions[1].choices
@ -304,21 +303,6 @@ def test_actions_map_cli():
.choices .choices
) )
amap.generate_cache("moulitest") assert parser.auth_method(["testauth", "default"]) == "dummy"
assert parser.auth_method(["testauth", "only-api"]) is None
amap = ActionsMap(ActionsMapParser(top_parser=parser)) assert parser.auth_method(["testauth", "only-cli"]) == "dummy"
assert amap.parser.global_conf["authenticate"] == "all"
assert "default" in amap.parser.global_conf["authenticator"]
assert "yoloswag" in amap.parser.global_conf["authenticator"]
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
assert (
"default"
in amap.parser._subparsers.choices["testauth"]
._actions[1]
.choices["subcat"]
._actions[1]
.choices
)

View file

@ -1,13 +1,15 @@
import os
import pytest import pytest
from moulinette import MoulinetteError from moulinette import MoulinetteError
from moulinette import m18n
class TestAuthAPI: class TestAuthAPI:
def login(self, webapi, csrf=False, profile=None, status=200, password="default"): def login(self, webapi, csrf=False, profile=None, status=200, password=None):
data = {"password": password} if password is None:
password = "dummy"
data = {"credentials": password}
if profile: if profile:
data["profile"] = profile data["profile"] = profile
@ -64,22 +66,15 @@ class TestAuthAPI:
def test_login(self, moulinette_webapi): def test_login(self, moulinette_webapi):
assert self.login(moulinette_webapi).text == "Logged in" assert self.login(moulinette_webapi).text == "Logged in"
assert "session.id" in moulinette_webapi.cookies assert "session.moulitest" 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
)
def test_login_bad_password(self, moulinette_webapi): def test_login_bad_password(self, moulinette_webapi):
assert ( assert (
self.login(moulinette_webapi, password="Bad Password", status=401).text self.login(moulinette_webapi, password="Bad Password", status=401).text
== "Invalid password" == "invalid_password"
) )
assert "session.id" not in moulinette_webapi.cookies assert "session.moulitest" not in moulinette_webapi.cookies
assert "session.tokens" not in moulinette_webapi.cookies
def test_login_csrf_attempt(self, moulinette_webapi): def test_login_csrf_attempt(self, moulinette_webapi):
# C.f. # C.f.
@ -90,8 +85,9 @@ class TestAuthAPI:
"CSRF protection" "CSRF protection"
in self.login(moulinette_webapi, csrf=True, status=403).text 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(
assert not any(c.name == "session.tokens" for c in moulinette_webapi.cookiejar) c.name == "session.moulitest" for c in moulinette_webapi.cookiejar
)
def test_login_then_legit_request_without_cookies(self, moulinette_webapi): def test_login_then_legit_request_without_cookies(self, moulinette_webapi):
self.login(moulinette_webapi) self.login(moulinette_webapi)
@ -103,6 +99,8 @@ class TestAuthAPI:
def test_login_then_legit_request(self, moulinette_webapi): def test_login_then_legit_request(self, moulinette_webapi):
self.login(moulinette_webapi) self.login(moulinette_webapi)
assert "session.moulitest" in moulinette_webapi.cookies
assert ( assert (
moulinette_webapi.get("/test-auth/default", status=200).text moulinette_webapi.get("/test-auth/default", status=200).text
== '"some_data_from_default"' == '"some_data_from_default"'
@ -118,11 +116,6 @@ class TestAuthAPI:
moulinette_webapi.get("/logout", status=200) 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 ( assert (
moulinette_webapi.get("/test-auth/default", status=401).text moulinette_webapi.get("/test-auth/default", status=401).text
== "Authentication required" == "Authentication required"
@ -131,15 +124,7 @@ class TestAuthAPI:
def test_login_other_profile(self, moulinette_webapi): def test_login_other_profile(self, moulinette_webapi):
self.login(moulinette_webapi, profile="yoloswag", password="yoloswag") self.login(moulinette_webapi, profile="yoloswag", password="yoloswag")
assert "session.id" in moulinette_webapi.cookies assert "session.moulitest" 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
)
def test_login_wrong_profile(self, moulinette_webapi): def test_login_wrong_profile(self, moulinette_webapi):
self.login(moulinette_webapi) self.login(moulinette_webapi)
@ -158,18 +143,6 @@ class TestAuthAPI:
== "Authentication required" == "Authentication required"
) )
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): def test_request_with_arg(self, moulinette_webapi, capsys):
self.login(moulinette_webapi) self.login(moulinette_webapi)
@ -214,7 +187,8 @@ class TestAuthAPI:
class TestAuthCLI: class TestAuthCLI:
def test_login(self, moulinette_cli, capsys, mocker): 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") moulinette_cli.run(["testauth", "default"], output_as="plain")
message = capsys.readouterr() message = capsys.readouterr()
@ -226,29 +200,30 @@ class TestAuthCLI:
assert "some_data_from_default" in message.out assert "some_data_from_default" in message.out
def test_login_bad_password(self, moulinette_cli, capsys, mocker): 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") mocker.patch("getpass.getpass", return_value="Bad Password")
with pytest.raises(MoulinetteError): with pytest.raises(MoulinetteError):
moulinette_cli.run(["testauth", "default"], output_as="plain") moulinette_cli.run(["testauth", "default"], output_as="plain")
mocker.patch("os.isatty", return_value=True)
mocker.patch("getpass.getpass", return_value="Bad Password") mocker.patch("getpass.getpass", return_value="Bad Password")
with pytest.raises(MoulinetteError): with pytest.raises(MoulinetteError):
moulinette_cli.run(["testauth", "default"], output_as="plain") moulinette_cli.run(["testauth", "default"], output_as="plain")
def test_login_wrong_profile(self, moulinette_cli, mocker): 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: with pytest.raises(MoulinetteError) as exception:
moulinette_cli.run(["testauth", "other-profile"], output_as="none") moulinette_cli.run(["testauth", "other-profile"], output_as="none")
translation = m18n.g("invalid_password") assert "invalid_password" in str(exception)
expected_msg = translation.format()
assert expected_msg in str(exception)
mocker.patch("os.isatty", return_value=True)
mocker.patch("getpass.getpass", return_value="yoloswag") mocker.patch("getpass.getpass", return_value="yoloswag")
with pytest.raises(MoulinetteError) as exception: with pytest.raises(MoulinetteError) as exception:
moulinette_cli.run(["testauth", "default"], output_as="none") moulinette_cli.run(["testauth", "default"], output_as="none")
expected_msg = translation.format() assert "invalid_password" in str(exception)
assert expected_msg in str(exception)
def test_request_no_auth_needed(self, capsys, moulinette_cli): def test_request_no_auth_needed(self, capsys, moulinette_cli):
moulinette_cli.run(["testauth", "none"], output_as="plain") moulinette_cli.run(["testauth", "none"], output_as="plain")
@ -263,7 +238,8 @@ class TestAuthCLI:
assert "some_data_from_only_api" in message.out assert "some_data_from_only_api" in message.out
def test_request_only_cli(self, capsys, moulinette_cli, mocker): 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") moulinette_cli.run(["testauth", "only-cli"], output_as="plain")
message = capsys.readouterr() message = capsys.readouterr()
@ -271,6 +247,7 @@ class TestAuthCLI:
assert "some_data_from_only_cli" in message.out assert "some_data_from_only_cli" in message.out
def test_request_not_logged_only_cli(self, capsys, moulinette_cli, mocker): def test_request_not_logged_only_cli(self, capsys, moulinette_cli, mocker):
mocker.patch("os.isatty", return_value=True)
mocker.patch("getpass.getpass") mocker.patch("getpass.getpass")
with pytest.raises(MoulinetteError) as exception: with pytest.raises(MoulinetteError) as exception:
moulinette_cli.run(["testauth", "only-cli"], output_as="plain") moulinette_cli.run(["testauth", "only-cli"], output_as="plain")
@ -278,12 +255,11 @@ class TestAuthCLI:
message = capsys.readouterr() message = capsys.readouterr()
assert "some_data_from_only_cli" not in message.out assert "some_data_from_only_cli" not in message.out
translation = m18n.g("invalid_password") assert "invalid_password" in str(exception)
expected_msg = translation.format()
assert expected_msg in str(exception)
def test_request_with_callback(self, moulinette_cli, capsys, mocker): 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") moulinette_cli.run(["--version"], output_as="plain")
message = capsys.readouterr() message = capsys.readouterr()
@ -301,14 +277,16 @@ class TestAuthCLI:
assert "cannot get value from callback method" in message.err assert "cannot get value from callback method" in message.err
def test_request_with_arg(self, moulinette_cli, capsys, mocker): 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") moulinette_cli.run(["testauth", "with_arg", "yoloswag"], output_as="plain")
message = capsys.readouterr() message = capsys.readouterr()
assert "yoloswag" in message.out assert "yoloswag" in message.out
def test_request_arg_with_extra(self, moulinette_cli, capsys, mocker): 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( moulinette_cli.run(
["testauth", "with_extra_str_only", "YoLoSwAg"], output_as="plain" ["testauth", "with_extra_str_only", "YoLoSwAg"], output_as="plain"
) )
@ -327,7 +305,8 @@ class TestAuthCLI:
assert "doesn't match pattern" in message.err assert "doesn't match pattern" in message.err
def test_request_arg_with_type(self, moulinette_cli, capsys, mocker): 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") moulinette_cli.run(["testauth", "with_type_int", "12345"], output_as="plain")
message = capsys.readouterr() message = capsys.readouterr()

View file

@ -1,12 +0,0 @@
import os.path
def test_open_cachefile_creates(monkeypatch, tmp_path):
monkeypatch.setenv("MOULINETTE_CACHE_DIR", str(tmp_path))
from moulinette.cache import open_cachefile
handle = open_cachefile("foo.cache", mode="w")
assert handle.mode == "w"
assert handle.name == os.path.join(str(tmp_path), "foo.cache")

View file

@ -12,7 +12,6 @@ from moulinette.utils.filesystem import (
read_json, read_json,
read_yaml, read_yaml,
read_toml, read_toml,
read_ldif,
rm, rm,
write_to_file, write_to_file,
write_to_json, write_to_json,
@ -117,46 +116,6 @@ def test_read_toml_cannot_read(test_toml, mocker):
assert expected_msg in str(exception) 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): def test_write_to_existing_file(test_file):
write_to_file(str(test_file), "yolo\nswag") write_to_file(str(test_file), "yolo\nswag")
assert read_file(str(test_file)) == "yolo\nswag" assert read_file(str(test_file)) == "yolo\nswag"

View 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))

79
test/test_i18n_keys.py Normal file
View file

@ -0,0 +1,79 @@
# -*- coding: utf-8 -*-
import re
import glob
import json
###############################################################################
# Find used keys in python code #
###############################################################################
def find_expected_string_keys():
# Try to find :
# m18n.g( "foo"
# MoulinetteError("foo"
# # i18n: "some_key"
p1 = re.compile(r"m18n\.g\(\s*[\"\'](\w+)[\"\']")
p2 = re.compile(r"Moulinette[a-zA-Z]+\(\s*[\'\"](\w+)[\'\"]")
p3 = re.compile(r"# i18n: [\'\"]?(\w+)[\'\"]?")
python_files = glob.glob("moulinette/*.py")
python_files.extend(glob.glob("moulinette/*/*.py"))
for python_file in python_files:
content = open(python_file).read()
for m in p1.findall(content):
if m.endswith("_"):
continue
yield m
for m in p2.findall(content):
if m.endswith("_"):
continue
yield m
for m in p3.findall(content):
if m.endswith("_"):
continue
yield m
###############################################################################
# Load en locale json keys #
###############################################################################
def keys_defined_for_en():
return json.loads(open("locales/en.json").read()).keys()
###############################################################################
# Compare keys used and keys defined #
###############################################################################
expected_string_keys = set(find_expected_string_keys())
keys_defined = set(keys_defined_for_en())
def test_undefined_i18n_keys():
undefined_keys = expected_string_keys.difference(keys_defined)
undefined_keys = sorted(undefined_keys)
if undefined_keys:
raise Exception(
"Those i18n keys should be defined in en.json:\n"
" - " + "\n - ".join(undefined_keys)
)
def test_unused_i18n_keys():
unused_keys = keys_defined.difference(expected_string_keys)
unused_keys = sorted(unused_keys)
if unused_keys:
raise Exception(
"Those i18n keys appears unused:\n" " - " + "\n - ".join(unused_keys)
)

View file

@ -1,414 +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": {},
}
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
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
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
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
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
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
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$")
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$")
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]
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"]
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"]
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)
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)
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)
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]
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"]
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"]
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"]
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"]
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)
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)
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)
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
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"})

View file

@ -1,5 +1,5 @@
from datetime import datetime as dt from datetime import datetime as dt
from moulinette.utils.serialize import JSONExtendedEncoder from moulinette.interfaces import JSONExtendedEncoder
def test_json_extended_encoder(caplog): def test_json_extended_encoder(caplog):

View 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))

View file

@ -1,6 +1,6 @@
[tox] [tox]
envlist = envlist =
py37-{pytest,lint} py37-{pytest,lint,invalidcode}
format format
format-check format-check
docs docs
@ -13,9 +13,16 @@ extras = tests
deps = deps =
py37-pytest: .[tests] py37-pytest: .[tests]
py37-lint: flake8 py37-lint: flake8
py37-invalidcode: flake8
commands = commands =
py37-pytest: pytest {posargs} -c pytest.ini py37-pytest: pytest {posargs} -c pytest.ini
py37-lint: flake8 moulinette test py37-lint: flake8 moulinette test
py37-invalidcode: flake8 moulinette test --select F
[gh-actions]
python =
3.7: py37
3.9: py39
[testenv:format] [testenv:format]
basepython = python3 basepython = python3