build: subpackages implementation (#164)

* migrate to hatch

* reorder tests

* generic fixtures

* straight forward conftest

* fix docs generation

* fix tox environments

* reformat tomls

* cleanup pyproject

* some play with renaming

* move root conftest into pytest plugins

* fix setup script

* move fixtures to __init__.py

* remove duplicate fixtures

* disable pylint warning

* simplify configuration fixture

* remove empty conftest

* remove crap from local pyprojects
This commit is contained in:
arcanis authored and GitHub committed 2026-07-17 14:00:20 +03:00
1 parent f12278a31d
commit 700893ecac
815 files changed
+833 -638

No files matched your search

@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,118 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import argparse
from collections.abc import Iterator
from pathlib import Path
from ahriman.application.handlers.handler import Handler, SubParserAction
from ahriman.core.configuration import Configuration
from ahriman.core.spawn import Spawn
from ahriman.core.triggers import TriggerLoader
from ahriman.models.repository_id import RepositoryId
from ahriman.web.web import run_server, setup_server
class Web(Handler):
"""
web server handler
"""
ALLOW_MULTI_ARCHITECTURE_RUN = False # system-wide action
@classmethod
def run(cls, args: argparse.Namespace, repository_id: RepositoryId, configuration: Configuration, *,
report: bool) -> None:
"""
callback for command line
Args:
args(argparse.Namespace): command line args
repository_id(RepositoryId): repository unique identifier
configuration(Configuration): configuration instance
report(bool): force enable or disable reporting
"""
spawner_args = Web.extract_arguments(args, configuration)
spawner = Spawn(args.parser(), list(spawner_args))
spawner.start()
triggers = TriggerLoader.load(repository_id, configuration)
triggers.on_start()
dummy_args = argparse.Namespace(
architecture=None,
configuration=args.configuration,
repository=None,
repository_id=None,
)
repositories = Web.repositories_extract(dummy_args)
application = setup_server(configuration, spawner, repositories)
run_server(application)
# terminate spawn process at the last
spawner.stop()
spawner.join()
@staticmethod
def _set_web_parser(root: SubParserAction) -> argparse.ArgumentParser:
"""
add parser for web subcommand
Args:
root(SubParserAction): subparsers for the commands
Returns:
argparse.ArgumentParser: created argument parser
"""
parser = root.add_parser("web", help="web server", description="start web server")
parser.set_defaults(architecture="", lock=Path("ahriman-web.pid"), report=False, repository="")
return parser
@staticmethod
def extract_arguments(args: argparse.Namespace, configuration: Configuration) -> Iterator[str]:
"""
extract list of arguments used for current command, except for command specific ones
Args:
args(argparse.Namespace): command line args
configuration(Configuration): configuration instance
Yields:
str: command line arguments which were used for this specific command
"""
# read configuration path from current settings
if (configuration_path := configuration.path) is not None:
yield from ["--configuration", str(configuration_path)]
# arguments from command line
if args.force:
yield "--force"
if args.log_handler is not None:
yield from ["--log-handler", args.log_handler.value]
if args.quiet:
yield "--quiet"
if args.unsafe:
yield "--unsafe"
# arguments from configuration
if (wait_timeout := configuration.getint("web", "wait_timeout", fallback=None)) is not None:
yield from ["--wait-timeout", str(wait_timeout)]
arguments = [_set_web_parser]
@@ -0,0 +1,20 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.core.auth.auth import Auth
+138
View File
@@ -0,0 +1,138 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import annotations
from ahriman.core.configuration import Configuration
from ahriman.core.database import SQLite
from ahriman.core.log import LazyLogging
from ahriman.models.auth_settings import AuthSettings
from ahriman.models.user_access import UserAccess
class Auth(LazyLogging):
"""
helper to deal with user authorization
Attributes:
enabled(bool): indicates if authorization is enabled
max_age(int): session age in seconds. It will be used for both client side and server side checks
allow_read_only(bool): allow read only access to APIs
"""
def __init__(self, configuration: Configuration, provider: AuthSettings = AuthSettings.Disabled) -> None:
"""
Args:
configuration(Configuration): configuration instance
provider(AuthSettings, optional): authorization type definition (Default value = AuthSettings.Disabled)
"""
self.allow_read_only = configuration.getboolean("auth", "allow_read_only")
self.enabled = provider.is_enabled
self.max_age = configuration.getint("auth", "max_age", fallback=7 * 24 * 3600)
@property
def auth_control(self) -> str:
"""
This workaround is required to make different behavior for login interface.
In case of internal authentication it must provide an interface (modal form) to log in with button sends POST
request. But for an external providers behavior can be different: e.g. OAuth provider requires sending GET
request to external resource
Returns:
str: login control as HTML code to insert
"""
return "<button type=\"button\" class=\"btn btn-link\" data-bs-toggle=\"modal\" data-bs-target=\"#login-modal\" style=\"text-decoration: none\"><i class=\"bi bi-box-arrow-in-right\"></i> login</button>"
@property
def is_external(self) -> bool:
"""
check if the provider is external (e.g. OAuth)
Returns:
bool: ``True`` in case if external provider is used and ``False`` otherwise
"""
return False
@staticmethod
def load(configuration: Configuration, database: SQLite) -> Auth:
"""
load authorization module from settings
Args:
configuration(Configuration): configuration instance
database(SQLite): database instance
Returns:
Auth: authorization module according to current settings
"""
match AuthSettings.from_option(configuration.get("auth", "target", fallback="disabled")):
case AuthSettings.Configuration:
from ahriman.core.auth.mapping import Mapping
return Mapping(configuration, database)
case AuthSettings.OAuth:
from ahriman.core.auth.oauth import OAuth
return OAuth(configuration, database)
case AuthSettings.PAM:
from ahriman.core.auth.pam import PAM
return PAM(configuration, database)
case _:
return Auth(configuration)
async def check_credentials(self, username: str, password: str | None) -> bool:
"""
validate user password
Args:
username(str): username
password(str | None): entered password
Returns:
bool: ``True`` in case if password matches, ``False`` otherwise
"""
del username, password
return True
async def known_username(self, username: str) -> bool:
"""
check if user is known
Args:
username(str): username
Returns:
bool: ``True`` in case if user is known and can be authorized and ``False`` otherwise
"""
del username
return True
async def verify_access(self, username: str, required: UserAccess, context: str | None) -> bool:
"""
validate if user has access to requested resource
Args:
username(str): username
required(UserAccess): required access level
context(str | None): URI request path
Returns:
bool: ``True`` in case if user is allowed to do this request and ``False`` otherwise
"""
del username, required, context
return True
@@ -0,0 +1,119 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
try:
import aiohttp_security
except ImportError:
aiohttp_security = None # type: ignore[assignment]
try:
import aiohttp_session
except ImportError:
aiohttp_session = None # type: ignore[assignment]
from typing import Any
__all__ = [
"authorized_userid",
"check_authorized",
"forget",
"get_session",
"remember",
]
async def authorized_userid(*args: Any, **kwargs: Any) -> Any:
"""
handle aiohttp security methods
Args:
*args(Any): argument list as provided by authorized_userid function
**kwargs(Any): named argument list as provided by authorized_userid function
Returns:
Any: ``None`` in case if no aiohttp_security module found and function call otherwise
"""
if aiohttp_security is not None:
return await aiohttp_security.authorized_userid(*args, **kwargs) # pylint: disable=no-value-for-parameter
return None
async def check_authorized(*args: Any, **kwargs: Any) -> Any:
"""
handle aiohttp security methods
Args:
*args(Any): argument list as provided by check_authorized function
**kwargs(Any): named argument list as provided by check_authorized function
Returns:
Any: ``None`` in case if no aiohttp_security module found and function call otherwise
"""
if aiohttp_security is not None:
return await aiohttp_security.check_authorized(*args, **kwargs) # pylint: disable=no-value-for-parameter
return None
async def forget(*args: Any, **kwargs: Any) -> Any:
"""
handle aiohttp security methods
Args:
*args(Any): argument list as provided by forget function
**kwargs(Any): named argument list as provided by forget function
Returns:
Any: ``None`` in case if no aiohttp_security module found and function call otherwise
"""
if aiohttp_security is not None:
return await aiohttp_security.forget(*args, **kwargs) # pylint: disable=no-value-for-parameter
return None
async def get_session(*args: Any, **kwargs: Any) -> Any:
"""
handle aiohttp session methods
Args:
*args(Any): argument list as provided by get_session function
**kwargs(Any): named argument list as provided by get_session function
Returns:
Any: empty dictionary in case if no aiohttp_session module found and function call otherwise
"""
if aiohttp_session is not None:
return await aiohttp_session.get_session(*args, **kwargs)
return {}
async def remember(*args: Any, **kwargs: Any) -> Any:
"""
handle disabled auth
Args:
*args(Any): argument list as provided by remember function
**kwargs(Any): named argument list as provided by remember function
Returns:
Any: ``None`` in case if no aiohttp_security module found and function call otherwise
"""
if aiohttp_security is not None:
return await aiohttp_security.remember(*args, **kwargs) # pylint: disable=no-value-for-parameter
return None
@@ -0,0 +1,102 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.core.auth import Auth
from ahriman.core.configuration import Configuration
from ahriman.core.database import SQLite
from ahriman.models.auth_settings import AuthSettings
from ahriman.models.user import User
from ahriman.models.user_access import UserAccess
class Mapping(Auth):
"""
user authorization based on mapping from configuration file
Attributes:
salt(str): random generated string to salted password
database(SQLite): database instance
"""
def __init__(self, configuration: Configuration, database: SQLite,
provider: AuthSettings = AuthSettings.Configuration) -> None:
"""
Args:
configuration(Configuration): configuration instance
database(SQLite): database instance
provider(AuthSettings, optional): authorization type definition (Default value = AuthSettings.Configuration)
"""
Auth.__init__(self, configuration, provider)
self.database = database
self.salt = configuration.get("auth", "salt", fallback="")
async def check_credentials(self, username: str, password: str | None) -> bool:
"""
validate user password
Args:
username(str): username
password(str | None): entered password
Returns:
bool: ``True`` in case if password matches, ``False`` otherwise
"""
if password is None:
return False # invalid data supplied
user = await self.get_user(username)
return user is not None and user.check_credentials(password, self.salt)
async def get_user(self, username: str) -> User | None:
"""
retrieve user from in-memory mapping
Args:
username(str): username
Returns:
User | None: user descriptor if username is known and ``None`` otherwise
"""
return self.database.user_get(username)
async def known_username(self, username: str) -> bool:
"""
check if user is known
Args:
username(str): username
Returns:
bool: ``True`` in case if user is known and can be authorized and ``False`` otherwise
"""
return username is not None and await self.get_user(username) is not None
async def verify_access(self, username: str, required: UserAccess, context: str | None) -> bool:
"""
validate if user has access to requested resource
Args:
username(str): username
required(UserAccess): required access level
context(str | None): URI request path
Returns:
bool: ``True`` in case if user is allowed to do this request and ``False`` otherwise
"""
user = await self.get_user(username)
return user is not None and user.verify_access(required)
+153
View File
@@ -0,0 +1,153 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import aioauth_client
from typing import Any
from ahriman.core.auth.mapping import Mapping
from ahriman.core.configuration import Configuration
from ahriman.core.database import SQLite
from ahriman.core.exceptions import OptionError
from ahriman.models.auth_settings import AuthSettings
class OAuth(Mapping):
"""
User authorization implementation via OAuth. It is required to create application first and put application
credentials.
Attributes:
client_id(str): application client id
client_secret(str): application client secret key
provider(aioauth_client.OAuth2Client): provider class, should be one of aiohttp-client provided classes
redirect_uri(str): redirect URI registered in provider
scopes(str): list of scopes required by the application
"""
def __init__(self, configuration: Configuration, database: SQLite,
provider: AuthSettings = AuthSettings.OAuth) -> None:
"""
Args:
configuration(Configuration): configuration instance
database(SQLite): database instance
provider(AuthSettings, optional): authorization type definition (Default value = AuthSettings.OAuth)
"""
Mapping.__init__(self, configuration, database, provider)
self.client_id = configuration.get("auth", "client_id")
self.client_secret = configuration.get("auth", "client_secret")
# in order to use OAuth feature the service must be publicity available
# thus we expect that address is set
self.redirect_uri = f"{configuration.get("web", "address")}/api/v1/login"
self.provider = self.get_provider(configuration.get("auth", "oauth_provider"))
# it is list, but we will have to convert to string it anyway
self.scopes = configuration.get("auth", "oauth_scopes")
@property
def auth_control(self) -> str:
"""
get authorization HTML control
Returns:
str: login control as HTML code to insert
"""
return "<a class=\"nav-link\" href=\"/api/v1/login\" title=\"login via OAuth2\"><i class=\"bi bi-box-arrow-in-right\"></i> login</a>"
@property
def is_external(self) -> bool:
"""
check if the provider is external (e.g. OAuth)
Returns:
bool: ``True`` in case if external provider is used and ``False`` otherwise
"""
return True
@staticmethod
def get_provider(name: str) -> type[aioauth_client.OAuth2Client]:
"""
load OAuth2 provider by name
Args:
name(str): name of the provider. Must be valid class defined in aioauth-client library
Returns:
type[aioauth_client.OAuth2Client]: loaded provider type
Raises:
OptionError: in case if invalid OAuth provider name supplied
"""
provider: type = getattr(aioauth_client, name, type(None))
try:
is_oauth2_client = issubclass(provider, aioauth_client.OAuth2Client)
except TypeError: # what if it is random string?
is_oauth2_client = False
if not is_oauth2_client:
raise OptionError(name)
return provider
def get_client(self) -> aioauth_client.OAuth2Client:
"""
load client from parameters
Returns:
aioauth_client.OAuth2Client: generated client according to current settings
"""
return self.provider(client_id=self.client_id, client_secret=self.client_secret)
def get_oauth_url(self, state: str) -> str:
"""
get authorization URI for the specified settings
Args:
state(str): CSRF token to pass to OAuth2 provider
Returns:
str: authorization URI as a string
"""
client = self.get_client()
uri: str = client.get_authorize_url(scope=self.scopes, redirect_uri=self.redirect_uri, state=state)
return uri
async def get_oauth_username(self, code: str, state: str | None, session: dict[str, Any]) -> str | None:
"""
extract OAuth username from remote
Args:
code(str): authorization code provided by external service
state(str | None): CSRF token returned by external service
session(dict[str, Any]): current session instance
Returns:
str | None: username as is in OAuth provider
"""
if state is None or state != session.get("state"):
return None
try:
client = self.get_client()
access_token, _ = await client.get_access_token(code, redirect_uri=self.redirect_uri)
client.access_token = access_token
user, _ = await client.user_info()
username: str = user.email or user.username # type: ignore[attr-defined]
return username
except Exception:
self.logger.exception("got exception while performing request")
return None
+129
View File
@@ -0,0 +1,129 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from grp import getgrnam
from pwd import getpwnam
from ahriman.core.auth.mapping import Mapping
from ahriman.core.configuration import Configuration
from ahriman.core.database import SQLite
from ahriman.core.exceptions import CalledProcessError
from ahriman.core.utils import check_output
from ahriman.models.auth_settings import AuthSettings
from ahriman.models.user_access import UserAccess
class PAM(Mapping):
"""
User authorization implementation by using default PAM
Attributes:
full_access_group(str): group name users of which have full access
permit_root_login(bool): permit login as root
"""
def __init__(self, configuration: Configuration, database: SQLite,
provider: AuthSettings = AuthSettings.PAM) -> None:
"""
Args:
configuration(Configuration): configuration instance
database(SQLite): database instance
provider(AuthSettings, optional): authorization type definition (Default value = AuthSettings.PAM)
"""
Mapping.__init__(self, configuration, database, provider)
self.full_access_group = configuration.get("auth", "full_access_group")
self.permit_root_login = configuration.getboolean("auth", "permit_root_login", fallback=False)
@staticmethod
def group_members(group_name: str) -> list[str]:
"""
extract current group members
Args:
group_name(str): group name
Returns:
list[str]: list of users which belong to the specified group. In case if group wasn't found, the empty list
will be returned
"""
try:
group = getgrnam(group_name)
except KeyError:
return []
return group.gr_mem
async def check_credentials(self, username: str, password: str | None) -> bool:
"""
validate user password
Args:
username(str): username
password(str | None): entered password
Returns:
bool: ``True`` in case if password matches, ``False`` otherwise
"""
if password is None:
return False # invalid data supplied
if not self.permit_root_login and username == "root":
return False # login as root is not allowed
# the reason why do we call su here is that python-pam actually read shadow file
# and hence requires root privileges
try:
check_output("su", "--command", "true", "-", username, input_data=password)
return True
except CalledProcessError:
return await Mapping.check_credentials(self, username, password)
async def known_username(self, username: str) -> bool:
"""
check if user is known
Args:
username(str): username
Returns:
bool: ``True`` in case if user is known and can be authorized and ``False`` otherwise
"""
try:
_ = getpwnam(username)
return True
except KeyError:
return await Mapping.known_username(self, username)
async def verify_access(self, username: str, required: UserAccess, context: str | None) -> bool:
"""
validate if user has access to requested resource
Args:
username(str): username
required(UserAccess): required access level
context(str | None): URI request path
Returns:
bool: ``True`` in case if user is allowed to do this request and ``False`` otherwise
"""
# this method is basically inverted, first we check overrides in database and then fallback to the PAM logic
if (user := await self.get_user(username)) is not None:
return user.verify_access(required)
# if username is in admin group, then we treat it as full access
if username in self.group_members(self.full_access_group):
return UserAccess.Full.permits(required)
# fallback to read-only accounts
return UserAccess.Read.permits(required)
+19
View File
@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,32 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
try:
import aiohttp_apispec # type: ignore[import-untyped]
from marshmallow import Schema, fields
except ImportError:
from unittest.mock import Mock
Schema = Mock # type: ignore[misc]
aiohttp_apispec = None
fields = Mock()
__all__ = ["Schema", "aiohttp_apispec", "fields"]
@@ -0,0 +1,149 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPException
from collections.abc import Callable
from typing import Any
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec import Schema, aiohttp_apispec
from ahriman.web.schemas import AuthSchema, ErrorSchema
__all__ = ["apidocs"]
def _response_schema(response: Schema | type[Schema] | None, response_code: type[HTTPException] | None = None,
error_400_enabled: bool = False, error_403_enabled: bool = True,
error_404_description: str | None = None) -> dict[int, Any]:
"""
render response schema specification
Args:
response(Schema | type[Schema] | None): response schema type, set ``None`` for empty responses
response_code(type[HTTPException] | None, optional): code for the success response. If none set it will be
defined automatically (Default value = None)
error_400_enabled(bool, optional): include response for 404 codes (Default value = False)
error_403_enabled(bool, optional): include response for 403 codes (Default value = False)
error_404_description(str | None, optional): description for 404 codes if available (Default value = None)
Returns:
dict[int, Any]: response schema in apispec format
"""
schema = {
401: {"description": "Authorization required", "schema": ErrorSchema},
500: {"description": "Internal server error", "schema": ErrorSchema},
}
match response_code:
case None if response is None:
code = 204
case None:
code = 200
case exception:
code = exception.status_code
schema[code] = {"description": "Success response"}
if response is not None:
schema[code]["schema"] = response
if error_400_enabled:
schema[400] = {"description": "Bad request", "schema": ErrorSchema}
if error_403_enabled:
schema[403] = {"description": "Access is forbidden", "schema": ErrorSchema}
if error_404_description is not None:
schema[404] = {"description": error_404_description, "schema": ErrorSchema}
return schema
def apidocs(*,
tags: list[str],
summary: str,
description: str,
permission: UserAccess,
response_code: type[HTTPException] | None = None,
error_400_enabled: bool = False,
error_404_description: str | None = None,
schema: Schema | type[Schema] | None = None,
match_schema: Schema | type[Schema] | None = None,
query_schema: Schema | type[Schema] | None = None,
body_schema: Schema | type[Schema] | None = None,
body_location: str = "json",
) -> Callable[..., Any]:
"""
wrapper around :mod:`aiohttp_apispec` to decorate HTTP methods
Args:
tags(list[str]): list of tags for the endpoint
summary(str): summary for the endpoint
description(str): long description for the endpoint
permission(UserAccess): permission to access endpoint
response_code(type[HTTPException] | None, optional): code for the success response. If none set it will be
defined automatically (Default value = None)
error_400_enabled(bool, optional): include response for 404 codes (Default value = False)
error_404_description(str | None, optional): description for 404 codes if available (Default value = None)
schema(Schema | type[Schema] | None): response schema type, set ``None`` for empty responses
(Default value = None)
match_schema(Schema | type[Schema] | None): schema for uri matcher if used (Default value = None)
query_schema(Schema | type[Schema] | None): query string schema type, set ``None`` if not applicable
(Default value = None)
body_schema(Schema | type[Schema] | None): body schema type, set ``None`` if not applicable
(Default value = None)
body_location(str, optional): body location name (Default value = "json")
Returns:
Callable[..., Any]: decorated function
"""
authorization_required = permission != UserAccess.Unauthorized
def wrapper(handler: Callable[..., Any]) -> Callable[..., Any]:
if aiohttp_apispec is None:
return handler # apispec is disabled
responses = _response_schema(
response=schema,
response_code=response_code,
error_400_enabled=error_400_enabled,
error_403_enabled=authorization_required,
error_404_description=error_404_description,
)
handler = aiohttp_apispec.docs(
tags=tags,
summary=summary,
description=description,
responses=responses,
security=[{"token": [permission]}],
)(handler)
# request schemas
if authorization_required:
handler = aiohttp_apispec.cookies_schema(AuthSchema)(handler)
if match_schema is not None:
handler = aiohttp_apispec.match_info_schema(match_schema)(handler)
if query_schema is not None:
handler = aiohttp_apispec.querystring_schema(query_schema)(handler)
if body_schema is not None:
handler = aiohttp_apispec.request_schema(
body_schema, locations=[body_location], put_into=body_location)(handler)
return handler
return wrapper
+123
View File
@@ -0,0 +1,123 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import Application
from typing import Any
from ahriman import __version__
from ahriman.web.apispec import aiohttp_apispec
from ahriman.web.keys import ConfigurationKey
__all__ = ["setup_apispec"]
def _info() -> dict[str, Any]:
"""
create info object for swagger docs
Returns:
dict[str, Any]: info object as per openapi specification
"""
return {
"title": "ahriman",
"description": """Wrapper for managing custom repository inspired by [repo-scripts](https://github.com/arcan1s/repo-scripts).
## Features
* Install-configure-forget manager for the very own repository.
* Multi-architecture support.
* Dependency manager.
* VCS packages support.
* Official repository support.
* Ability to patch AUR packages and even create package from local PKGBUILDs.
* Various rebuild options with ability to automatically bump package version.
* Sign support with gpg (repository, package), multiple packagers support.
* Triggers for repository updates, e.g. synchronization to remote services (rsync, s3 and github) and report generation (email, html, telegram).
* Repository status interface with optional authorization and control options.
<security-definitions />
""",
"license": {
"name": "GPL3",
"url": "https://raw.githubusercontent.com/arcan1s/ahriman/master/COPYING",
},
"version": __version__,
}
def _security() -> list[dict[str, Any]]:
"""
get security definitions
Returns:
list[dict[str, Any]]: generated security definition
"""
return [{
"token": {
"type": "apiKey", # as per specification we are using api key
"name": "AHRIMAN",
"in": "cookie",
}
}]
def _servers(application: Application) -> list[dict[str, Any]]:
"""
get list of defined addresses for server
Args:
application(Application): web application instance
Returns:
list[dict[str, Any]]: list (actually only one) of defined web urls
"""
configuration = application[ConfigurationKey]
address = configuration.get("web", "address", fallback=None)
if not address:
host = configuration.get("web", "host")
port = configuration.getint("web", "port")
address = f"http://{host}:{port}"
return [{
"url": address,
}]
def setup_apispec(application: Application) -> Any:
"""
setup swagger api specification
Args:
application(Application): web application instance
Returns:
Any: created specification instance if module is available
"""
if aiohttp_apispec is None:
return None
return aiohttp_apispec.setup_aiohttp_apispec(
application,
url="/api-docs/swagger.json",
openapi_version="3.0.2",
info=_info(),
servers=_servers(application),
security=_security(),
)
+56
View File
@@ -0,0 +1,56 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import aiohttp_cors
from aiohttp.web import Application
from ahriman.core.configuration import Configuration
__all__ = ["setup_cors"]
def setup_cors(application: Application, configuration: Configuration) -> aiohttp_cors.CorsConfig:
"""
setup CORS for the web application
Args:
application(Application): web application instance
configuration(Configuration): configuration instance
Returns:
aiohttp_cors.CorsConfig: generated CORS configuration
"""
allow_headers = configuration.getlist("web", "cors_allow_headers", fallback=[]) or "*"
allow_methods = configuration.getlist("web", "cors_allow_methods", fallback=[]) or "*"
expose_headers = configuration.getlist("web", "cors_expose_headers", fallback=[]) or "*"
cors = aiohttp_cors.setup(application, defaults={
origin: aiohttp_cors.ResourceOptions( # type: ignore[no-untyped-call]
expose_headers=expose_headers,
allow_headers=allow_headers,
allow_methods=allow_methods,
)
for origin in configuration.getlist("web", "cors_allow_origins", fallback=["*"])
})
for route in application.router.routes():
cors.add(route)
return cors
+43
View File
@@ -0,0 +1,43 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import AppKey
from ahriman.core.auth import Auth
from ahriman.core.configuration import Configuration
from ahriman.core.distributed import WorkersCache
from ahriman.core.spawn import Spawn
from ahriman.core.status.watcher import Watcher
from ahriman.models.repository_id import RepositoryId
__all__ = [
"AuthKey",
"ConfigurationKey",
"SpawnKey",
"WatcherKey",
"WorkersKey",
]
AuthKey = AppKey("validator", Auth)
ConfigurationKey = AppKey("configuration", Configuration)
SpawnKey = AppKey("spawn", Spawn)
WatcherKey = AppKey("watcher", dict[RepositoryId, Watcher])
WorkersKey = AppKey("workers", WorkersCache)
@@ -0,0 +1,24 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import Request, StreamResponse
from collections.abc import Awaitable, Callable
HandlerType = Callable[[Request], Awaitable[StreamResponse]]
@@ -0,0 +1,167 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import aiohttp_security
import socket
import types
from aiohttp.typedefs import Middleware
from aiohttp.web import Application, Request, StaticResource, StreamResponse, middleware
from aiohttp_session import setup as setup_session
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from cryptography import fernet
from enum import Enum
from ahriman.core.auth import Auth
from ahriman.core.configuration import Configuration
from ahriman.models.user_access import UserAccess
from ahriman.web.middlewares import HandlerType
__all__ = ["setup_auth"]
class _AuthorizationPolicy(aiohttp_security.AbstractAuthorizationPolicy):
"""
authorization policy implementation
Attributes:
validator(Auth): validator instance
"""
def __init__(self, validator: Auth) -> None:
"""
Args:
validator(Auth): authorization module instance
"""
aiohttp_security.AbstractAuthorizationPolicy.__init__(self)
self.validator = validator
async def authorized_userid(self, identity: str) -> str | None:
"""
retrieve authenticated username
Args:
identity(str): username
Returns:
str | None: user identity (username) in case if user exists and ``None`` otherwise
"""
return identity if await self.validator.known_username(identity) else None
async def permits(self, identity: str | None, permission: str | Enum, context: str | None = None) -> bool:
"""
check user permissions
Args:
identity(str | None): username
permission(str | Enum): requested permission level
context(str | None, optional): URI request path (Default value = None)
Returns:
bool: ``True`` in case if user is allowed to perform this request and ``False`` otherwise
"""
# some methods for type checking and parent class compatibility
if identity is None or not isinstance(permission, UserAccess):
return False # no identity provided or invalid access rights requested
return await self.validator.verify_access(identity, permission, context)
def _auth_handler(allow_read_only: bool) -> Middleware:
"""
authorization and authentication middleware
Args:
allow_read_only: allow
Returns:
Middleware: built middleware
"""
@middleware
async def handle(request: Request, handler: HandlerType) -> StreamResponse:
if (unix_socket := request.get_extra_info("socket")) is not None and unix_socket.family == socket.AF_UNIX:
# special case for unix sockets. We need to extract socket which is used for the request
# and check its address family
permission = UserAccess.Unauthorized
elif (permission_method := getattr(handler, "get_permission", None)) is not None:
permission = await permission_method(request)
elif isinstance(handler, types.MethodType): # additional wrapper for static resources
handler_instance = getattr(handler, "__self__", None)
permission = UserAccess.Unauthorized if isinstance(handler_instance, StaticResource) else UserAccess.Full
else:
permission = UserAccess.Full
if permission == UserAccess.Unauthorized: # explicit if elif else for better code coverage
pass
elif allow_read_only and UserAccess.Read.permits(permission):
pass
else:
await aiohttp_security.check_permission(request, permission, request.path)
return await handler(request)
return handle
def _cookie_secret_key(configuration: Configuration) -> fernet.Fernet:
"""
extract cookie secret key from configuration if set or generate new one
Args:
configuration(Configuration): configuration instance
Returns:
fernet.Fernet: fernet key instance
"""
if (secret_key := configuration.get("auth", "cookie_secret_key", fallback=None)) is not None:
return fernet.Fernet(secret_key)
secret_key = fernet.Fernet.generate_key()
return fernet.Fernet(secret_key)
def setup_auth(application: Application, configuration: Configuration, validator: Auth) -> Application:
"""
setup authorization policies for the application
Args:
application(Application): web application instance
configuration(Configuration): configuration instance
validator(Auth): authorization module instance
Returns:
Application: configured web application
"""
secret_key = _cookie_secret_key(configuration)
storage = EncryptedCookieStorage(
secret_key,
cookie_name="AHRIMAN",
max_age=validator.max_age,
httponly=True,
samesite="Lax",
)
setup_session(application, storage)
authorization_policy = _AuthorizationPolicy(validator)
identity_policy = aiohttp_security.SessionIdentityPolicy("SESSION")
aiohttp_security.setup(application, identity_policy, authorization_policy)
application.middlewares.append(_auth_handler(validator.allow_read_only))
return application
@@ -0,0 +1,61 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import hashlib
from aiohttp import ETag
from aiohttp.typedefs import Middleware
from aiohttp.web import HTTPNotModified, Request, Response, StreamResponse, middleware
from ahriman.web.middlewares import HandlerType
__all__ = ["etag_handler"]
def etag_handler() -> Middleware:
"""
middleware to handle ETag header for conditional requests. It computes ETag from the response body
and returns 304 Not Modified if the client sends a matching ``If-None-Match`` header
Returns:
Middleware: built middleware
Raises:
HTTPNotModified: if content matches ``If-None-Match`` header sent
"""
@middleware
async def handle(request: Request, handler: HandlerType) -> StreamResponse:
response = await handler(request)
if not isinstance(response, Response) or not isinstance(response.body, bytes):
return response
if request.method not in ("GET", "HEAD"):
return response
etag = ETag(value=hashlib.md5(response.body, usedforsecurity=False).hexdigest())
response.etag = etag
if request.if_none_match is not None and etag in request.if_none_match:
raise HTTPNotModified(headers={"ETag": response.headers["ETag"]})
return response
return handle
@@ -0,0 +1,101 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import aiohttp_jinja2
import logging
from aiohttp.typedefs import Middleware
from aiohttp.web import (
HTTPClientError,
HTTPException,
HTTPMethodNotAllowed,
HTTPNoContent,
HTTPServerError,
HTTPUnauthorized,
Request,
StreamResponse,
json_response,
middleware,
)
from ahriman.web.middlewares import HandlerType
__all__ = ["exception_handler"]
def _is_templated_unauthorized(request: Request) -> bool:
"""
check if the request is eligible for rendering HTML template
Args:
request(Request): source request to check
Returns:
bool: ``True`` in case if response should be rendered as HTML and ``False`` otherwise
"""
return request.path in ("/api/v1/login", "/api/v1/logout") \
and "application/json" not in request.headers.getall("accept", [])
def exception_handler(logger: logging.Logger) -> Middleware:
"""
exception handler middleware. Just log any exception (except for client ones)
Args:
logger(logging.Logger): class logger
Returns:
Middleware: built middleware
Raises:
HTTPNoContent: OPTIONS method response
"""
@middleware
async def handle(request: Request, handler: HandlerType) -> StreamResponse:
try:
return await handler(request)
except HTTPUnauthorized as ex:
if _is_templated_unauthorized(request):
context = {"code": ex.status_code, "reason": ex.reason}
return aiohttp_jinja2.render_template("error.jinja2", request, context, status=ex.status_code)
return json_response(data={"error": ex.reason}, status=ex.status_code)
except HTTPMethodNotAllowed as ex:
if ex.method == "OPTIONS":
# automatically handle OPTIONS method, idea comes from
# https://github.com/arcan1s/ffxivbis/blob/master/src/main/scala/me/arcanis/ffxivbis/http/api/v1/HttpHandler.scala#L32
raise HTTPNoContent(headers={"Allow": ",".join(sorted(ex.allowed_methods))})
if ex.method == "HEAD":
# since we have special autogenerated HEAD method, we need to remove it from list of available
ex.allowed_methods = {method for method in ex.allowed_methods if method != "HEAD"}
ex.headers["Allow"] = ",".join(sorted(ex.allowed_methods))
raise ex
raise
except HTTPClientError as ex:
return json_response(data={"error": ex.reason}, status=ex.status_code)
except HTTPServerError as ex:
logger.exception("server exception during performing request to %s", request.path)
return json_response(data={"error": ex.reason}, status=ex.status_code)
except HTTPException: # just raise 2xx and 3xx codes
raise
except Exception as ex:
logger.exception("unknown exception during performing request to %s", request.path)
return json_response(data={"error": str(ex)}, status=500)
return handle
@@ -0,0 +1,69 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
try:
import aiohttp_openmetrics
except ImportError:
aiohttp_openmetrics = None # type: ignore[assignment]
from aiohttp.typedefs import Middleware
from aiohttp.web import HTTPNotFound, Request, Response, StreamResponse, middleware
from ahriman.web.middlewares import HandlerType
__all__ = [
"metrics",
"metrics_handler",
]
async def metrics(request: Request) -> Response:
"""
handler for returning metrics
Args:
request(Request): request object
Returns:
Response: response object
Raises:
HTTPNotFound: endpoint is disabled
"""
if aiohttp_openmetrics is None:
raise HTTPNotFound
return await aiohttp_openmetrics.metrics(request)
def metrics_handler() -> Middleware:
"""
middleware for metrics support
Returns:
Middleware: middleware function to handle server metrics
"""
if aiohttp_openmetrics is not None:
return aiohttp_openmetrics.metrics_middleware
@middleware
async def handle(request: Request, handler: HandlerType) -> StreamResponse:
return await handler(request)
return handle
@@ -0,0 +1,51 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import uuid
from aiohttp.typedefs import Middleware
from aiohttp.web import Request, StreamResponse, middleware
from ahriman.core.log.log_context import LogContext
from ahriman.web.middlewares import HandlerType
__all__ = ["request_id_handler"]
def request_id_handler() -> Middleware:
"""
middleware to trace request id header
Returns:
Middleware: request id processing middleware
"""
@middleware
async def handle(request: Request, handler: HandlerType) -> StreamResponse:
request_id = request.headers.getone("X-Request-ID", str(uuid.uuid4()))
token = LogContext.set("request_id", request_id)
try:
response = await handler(request)
response.headers["X-Request-ID"] = request_id
return response
finally:
LogContext.reset("request_id", token)
return handle
+79
View File
@@ -0,0 +1,79 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import re
from aiohttp.web import Application, View
from collections.abc import Iterator
import ahriman.web.views
from ahriman.core.configuration import Configuration
from ahriman.core.module_loader import implementations
from ahriman.web.views.base import BaseView
__all__ = ["setup_routes"]
def _dynamic_routes(configuration: Configuration) -> Iterator[tuple[str, type[View]]]:
"""
extract dynamic routes based on views
Args:
configuration(Configuration): configuration instance
Yields:
tuple[str, type[View]]: map of the route to its view
"""
for view in implementations(ahriman.web.views, BaseView):
for route in view.routes(configuration):
yield route, view
def _identifier(route: str) -> str:
"""
extract valid route identifier (aka name) for the route. This method replaces curly brackets by single colon
and replaces other special symbols (including slashes) by underscore
Args:
route(str): source route
Returns:
str: route with special symbols being replaced
"""
# replace special symbols
alphanum = re.sub(r"[^A-Za-z\d\-{}]", "_", route)
# finally replace curly brackets
return alphanum.replace("{", ":").replace("}", "")
def setup_routes(application: Application, configuration: Configuration) -> None:
"""
setup all defined routes
Args:
application(Application): web application instance
configuration(Configuration): configuration instance
"""
application.router.add_static("/static", configuration.getpath("web", "static_path"),
name="_static", follow_symlinks=True)
for route, view in _dynamic_routes(configuration):
application.router.add_view(route, view, name=_identifier(route))
@@ -0,0 +1,68 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.schemas.any_schema import AnySchema
from ahriman.web.schemas.aur_package_schema import AURPackageSchema
from ahriman.web.schemas.auth_info_schema import AuthInfoSchema
from ahriman.web.schemas.auth_schema import AuthSchema
from ahriman.web.schemas.auto_refresh_interval_schema import AutoRefreshIntervalSchema
from ahriman.web.schemas.build_options_schema import BuildOptionsSchema
from ahriman.web.schemas.changes_schema import ChangesSchema
from ahriman.web.schemas.configuration_schema import ConfigurationSchema
from ahriman.web.schemas.counters_schema import CountersSchema
from ahriman.web.schemas.dependencies_schema import DependenciesSchema
from ahriman.web.schemas.error_schema import ErrorSchema
from ahriman.web.schemas.event_bus_filter_schema import EventBusFilterSchema
from ahriman.web.schemas.event_schema import EventSchema
from ahriman.web.schemas.event_search_schema import EventSearchSchema
from ahriman.web.schemas.file_schema import FileSchema
from ahriman.web.schemas.hold_schema import HoldSchema
from ahriman.web.schemas.info_schema import InfoSchema
from ahriman.web.schemas.info_v2_schema import InfoV2Schema
from ahriman.web.schemas.internal_status_schema import InternalStatusSchema
from ahriman.web.schemas.log_schema import LogSchema
from ahriman.web.schemas.login_schema import LoginSchema
from ahriman.web.schemas.logs_rotate_schema import LogsRotateSchema
from ahriman.web.schemas.logs_schema import LogsSchema
from ahriman.web.schemas.logs_search_schema import LogsSearchSchema
from ahriman.web.schemas.oauth2_schema import OAuth2Schema
from ahriman.web.schemas.package_name_schema import PackageNameSchema
from ahriman.web.schemas.package_names_schema import PackageNamesSchema
from ahriman.web.schemas.package_patch_schema import PackagePatchSchema
from ahriman.web.schemas.package_properties_schema import PackagePropertiesSchema
from ahriman.web.schemas.package_schema import PackageSchema
from ahriman.web.schemas.package_status_schema import PackageStatusSchema, PackageStatusSimplifiedSchema
from ahriman.web.schemas.package_version_schema import PackageVersionSchema
from ahriman.web.schemas.packager_schema import PackagerSchema
from ahriman.web.schemas.pagination_schema import PaginationSchema
from ahriman.web.schemas.patch_name_schema import PatchNameSchema
from ahriman.web.schemas.patch_schema import PatchSchema
from ahriman.web.schemas.pgp_key_id_schema import PGPKeyIdSchema
from ahriman.web.schemas.pgp_key_schema import PGPKeySchema
from ahriman.web.schemas.process_id_schema import ProcessIdSchema
from ahriman.web.schemas.process_schema import ProcessSchema
from ahriman.web.schemas.remote_schema import RemoteSchema
from ahriman.web.schemas.repository_id_schema import RepositoryIdSchema
from ahriman.web.schemas.repository_stats_schema import RepositoryStatsSchema
from ahriman.web.schemas.rollback_schema import RollbackSchema
from ahriman.web.schemas.search_schema import SearchSchema
from ahriman.web.schemas.sse_schema import SSESchema
from ahriman.web.schemas.status_schema import StatusSchema
from ahriman.web.schemas.update_flags_schema import UpdateFlagsSchema
from ahriman.web.schemas.worker_schema import WorkerSchema
@@ -0,0 +1,26 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema
class AnySchema(Schema):
"""
response dummy schema
"""
@@ -0,0 +1,35 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class AURPackageSchema(Schema):
"""
response AUR package schema
"""
description = fields.String(required=True, metadata={
"description": "Package description",
"example": "ArcH linux ReposItory MANager",
})
package = fields.String(required=True, metadata={
"description": "Package base",
"example": "ahriman",
})
@@ -0,0 +1,41 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class AuthInfoSchema(Schema):
"""
authorization information schema
"""
control = fields.String(
metadata={
"description": "HTML control for login interface",
"example": "<button type=\"button\" class=\"btn btn-link\" data-bs-toggle=\"modal\" data-bs-target=\"#login-modal\" style=\"text-decoration: none\"><i class=\"bi bi-box-arrow-in-right\"></i> login</button>",
})
enabled = fields.Boolean(required=True, metadata={
"description": "Whether authentication is enabled or not",
})
external = fields.Boolean(required=True, metadata={
"description": "Whether authorization provider is external (e.g. OAuth)",
})
username = fields.String(metadata={
"description": "Currently authenticated username if available",
})
@@ -0,0 +1,30 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class AuthSchema(Schema):
"""
request cookie authorization schema
"""
AHRIMAN = fields.String(required=True, metadata={
"description": "API session key as returned from authorization",
})
@@ -0,0 +1,38 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class AutoRefreshIntervalSchema(Schema):
"""
auto refresh interval schema
"""
interval = fields.Integer(required=True, metadata={
"description": "Auto refresh interval in milliseconds",
"example": "60000",
})
is_active = fields.Boolean(required=True, metadata={
"description": "Whether this interval is the default active one",
})
text = fields.String(required=True, metadata={
"description": "Human readable interval description",
"example": "1 minute",
})
@@ -0,0 +1,34 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import fields
from ahriman.web.schemas.packager_schema import PackagerSchema
class BuildOptionsSchema(PackagerSchema):
"""
request build options schema
"""
increment = fields.Boolean(dump_default=True, metadata={
"description": "Increment pkgrel on conflicts",
})
refresh = fields.Boolean(dump_default=True, metadata={
"description": "Refresh pacman database"
})
@@ -0,0 +1,37 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class ChangesSchema(Schema):
"""
response package changes schema
"""
changes = fields.String(metadata={
"description": "Package changes in patch format",
})
last_commit_sha = fields.String(metadata={
"description": "Last recorded commit hash",
"example": "f1875edca1eb8fc0e55c41d1cae5fa05b6b7c6",
})
pkgbuild = fields.String(metadata={
"description": "Original PKGBUILD content",
})
@@ -0,0 +1,39 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class ConfigurationSchema(Schema):
"""
response configuration schema
"""
key = fields.String(required=True, metadata={
"description": "Configuration key",
"example": "host",
})
section = fields.String(required=True, metadata={
"description": "Configuration section",
"example": "web",
})
value = fields.String(required=True, metadata={
"description": "Configuration value",
"example": "127.0.0.1",
})
@@ -0,0 +1,51 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class CountersSchema(Schema):
"""
response package counters schema
"""
building = fields.Integer(required=True, metadata={
"description": "Amount of packages in building state",
"example": 1,
})
failed = fields.Integer(required=True, metadata={
"description": "Amount of packages in failed state",
"example": 1,
})
pending = fields.Integer(required=True, metadata={
"description": "Amount of packages in pending state",
"example": 2,
})
success = fields.Integer(required=True, metadata={
"description": "Amount of packages in success state",
"example": 3,
})
total = fields.Integer(required=True, metadata={
"description": "Total amount of packages",
"example": 6,
})
unknown_ = fields.Integer(data_key="unknown", required=True, metadata={
"description": "Amount of packages in unknown state",
"example": 0,
})
@@ -0,0 +1,31 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class DependenciesSchema(Schema):
"""
request/response package dependencies schema
"""
paths = fields.Dict(
keys=fields.String(), values=fields.List(fields.String()), required=True, metadata={
"description": "Map of filesystem paths to packages which contain this path",
})
@@ -0,0 +1,30 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class ErrorSchema(Schema):
"""
response error schema
"""
error = fields.String(required=True, metadata={
"description": "Error description",
})
@@ -0,0 +1,37 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.models.event import EventType
from ahriman.web.apispec import fields
from ahriman.web.schemas.repository_id_schema import RepositoryIdSchema
class EventBusFilterSchema(RepositoryIdSchema):
"""
request event bus filter schema
"""
event = fields.List(fields.String(), metadata={
"description": "Event type filter",
"example": [EventType.PackageUpdated],
})
object_id = fields.String(metadata={
"description": "Object identifier filter",
"example": "ahriman",
})
@@ -0,0 +1,46 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.models.event import EventType
from ahriman.web.apispec import Schema, fields
class EventSchema(Schema):
"""
request/response event schema
"""
created = fields.Integer(required=True, metadata={
"description": "Event creation timestamp",
"example": 1680537091,
})
data = fields.Dict(keys=fields.String(), metadata={
"description": "Event metadata if available",
})
event = fields.String(required=True, metadata={
"description": "Event type",
"example": EventType.PackageUpdated,
})
message = fields.String(metadata={
"description": "Event message if available",
})
object_id = fields.String(required=True, metadata={
"description": "Event object identifier",
"example": "ahriman",
})
@@ -0,0 +1,45 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.models.event import EventType
from ahriman.web.apispec import fields
from ahriman.web.schemas.pagination_schema import PaginationSchema
class EventSearchSchema(PaginationSchema):
"""
request event search schema
"""
event = fields.String(metadata={
"description": "Event type",
"example": EventType.PackageUpdated,
})
from_date = fields.Integer(metadata={
"description": "Minimal creation timestamp, inclusive",
"example": 1680537091,
})
object_id = fields.String(metadata={
"description": "Event object identifier",
"example": "ahriman",
})
to_date = fields.Integer(metadata={
"description": "Maximal creation timestamp, exclusive",
"example": 1680537091,
})
@@ -0,0 +1,30 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class FileSchema(Schema):
"""
request file upload schema
"""
archive = fields.Raw(required=True, metadata={
"description": "Package archive to be uploaded",
})
@@ -0,0 +1,30 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class HoldSchema(Schema):
"""
request hold schema
"""
is_held = fields.Boolean(required=True, metadata={
"description": "Package hold status",
})
@@ -0,0 +1,39 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman import __version__
from ahriman.web.apispec import Schema, fields
from ahriman.web.schemas.repository_id_schema import RepositoryIdSchema
class InfoSchema(Schema):
"""
response service information schema
"""
auth = fields.Boolean(required=True, metadata={
"description": "Whether authentication is enabled or not",
})
repositories = fields.Nested(RepositoryIdSchema(many=True), required=True, metadata={
"description": "List of loaded repositories",
})
version = fields.String(required=True, metadata={
"description": "Service version",
"example": __version__,
})
@@ -0,0 +1,51 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman import __version__
from ahriman.web.apispec import Schema, fields
from ahriman.web.schemas.auth_info_schema import AuthInfoSchema
from ahriman.web.schemas.auto_refresh_interval_schema import AutoRefreshIntervalSchema
from ahriman.web.schemas.repository_id_schema import RepositoryIdSchema
class InfoV2Schema(Schema):
"""
response service information schema
"""
auth = fields.Nested(AuthInfoSchema(), required=True, metadata={
"description": "Authorization descriptor",
})
autorefresh_intervals = fields.Nested(AutoRefreshIntervalSchema(many=True), metadata={
"description": "Available auto refresh intervals",
})
docs_enabled = fields.Boolean(metadata={
"description": "Whether API documentation is enabled",
})
index_url = fields.String(metadata={
"description": "URL to the repository index page",
"example": "https://ahriman.readthedocs.io/",
})
repositories = fields.Nested(RepositoryIdSchema(many=True), required=True, metadata={
"description": "List of loaded repositories",
})
version = fields.String(required=True, metadata={
"description": "Service version",
"example": __version__,
})
@@ -0,0 +1,45 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman import __version__
from ahriman.web.apispec import fields
from ahriman.web.schemas.counters_schema import CountersSchema
from ahriman.web.schemas.repository_id_schema import RepositoryIdSchema
from ahriman.web.schemas.repository_stats_schema import RepositoryStatsSchema
from ahriman.web.schemas.status_schema import StatusSchema
class InternalStatusSchema(RepositoryIdSchema):
"""
response service status schema
"""
packages = fields.Nested(CountersSchema(), required=True, metadata={
"description": "Repository package counters",
})
stats = fields.Nested(RepositoryStatsSchema(), required=True, metadata={
"description": "Repository stats",
})
status = fields.Nested(StatusSchema(), required=True, metadata={
"description": "Repository status as stored by web service",
})
version = fields.String(required=True, metadata={
"description": "Service version",
"example": __version__,
})
@@ -0,0 +1,42 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman import __version__
from ahriman.web.apispec import Schema, fields
class LogSchema(Schema):
"""
request and response package log schema
"""
created = fields.Float(required=True, metadata={
"description": "Log record timestamp",
"example": 1680537091.233495,
})
message = fields.String(required=True, metadata={
"description": "Log message",
})
process_id = fields.String(metadata={
"description": "Process unique identifier",
})
version = fields.String(required=True, metadata={
"description": "Package version to tag",
"example": __version__,
})
@@ -0,0 +1,35 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class LoginSchema(Schema):
"""
request login schema
"""
password = fields.String(required=True, metadata={
"description": "Login password",
"example": "pa55w0rd",
})
username = fields.String(required=True, metadata={
"description": "Login username",
"example": "user",
})
@@ -0,0 +1,30 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class LogsRotateSchema(Schema):
"""
request logs rotate schema
"""
keep_last_records = fields.Integer(metadata={
"description": "Keep the specified amount of records",
})
@@ -0,0 +1,38 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
from ahriman.web.schemas.status_schema import StatusSchema
class LogsSchema(Schema):
"""
response package logs schema
"""
logs = fields.String(required=True, metadata={
"description": "Full package log from the last build",
})
package_base = fields.String(required=True, metadata={
"description": "Package base name",
"example": "ahriman",
})
status = fields.Nested(StatusSchema(), required=True, metadata={
"description": "Last package status",
})
@@ -0,0 +1,39 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman import __version__
from ahriman.web.apispec import fields
from ahriman.web.schemas.pagination_schema import PaginationSchema
class LogsSearchSchema(PaginationSchema):
"""
request log search schema
"""
head = fields.Boolean(metadata={
"description": "Return versions only without fetching logs themselves",
})
process_id = fields.String(metadata={
"description": "Process unique identifier to search",
})
version = fields.String(metadata={
"description": "Package version to search",
"example": __version__,
})
@@ -0,0 +1,33 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class OAuth2Schema(Schema):
"""
request OAuth2 authorization schema
"""
code = fields.String(metadata={
"description": "OAuth2 authorization code. In case if not set, the redirect to provider will be initiated",
})
state = fields.String(metadata={
"description": "CSRF token returned by OAuth2 provider",
})
@@ -0,0 +1,31 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class PackageNameSchema(Schema):
"""
request package name schema
"""
package = fields.String(required=True, metadata={
"description": "Package name",
"example": "ahriman",
})
@@ -0,0 +1,32 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import fields
from ahriman.web.schemas.build_options_schema import BuildOptionsSchema
class PackageNamesSchema(BuildOptionsSchema):
"""
request package names schema
"""
packages = fields.List(fields.String(), required=True, metadata={
"description": "Package names",
"example": ["ahriman"],
})
@@ -0,0 +1,32 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import fields
from ahriman.web.schemas.package_names_schema import PackageNamesSchema
from ahriman.web.schemas.patch_schema import PatchSchema
class PackagePatchSchema(PackageNamesSchema):
"""
response schema with packages and patches
"""
patches = fields.Nested(PatchSchema(many=True), metadata={
"description": "optional environment variables to be applied as patches"
})
@@ -0,0 +1,83 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class PackagePropertiesSchema(Schema):
"""
request and response package properties schema
"""
architecture = fields.String(metadata={
"description": "Package architecture",
"example": "x86_64",
})
archive_size = fields.Integer(metadata={
"description": "Archive size in bytes",
"example": 287989,
})
build_date = fields.Integer(metadata={
"description": "Package build timestamp",
"example": 1680537091,
})
check_depends = fields.List(fields.String(), metadata={
"description": "Package test dependencies list",
"example": ["python-pytest"],
})
depends = fields.List(fields.String(), metadata={
"description": "Package dependencies list",
"example": ["devtools"],
})
description = fields.String(metadata={
"description": "Package description",
"example": "ArcH linux ReposItory MANager",
})
filename = fields.String(metadata={
"description": "Package file name",
"example": "ahriman-2.7.1-1-any.pkg.tar.zst",
})
groups = fields.List(fields.String(), metadata={
"description": "Package groups",
"example": ["base-devel"],
})
installed_size = fields.Integer(metadata={
"description": "Installed package size in bytes",
"example": 2047658,
})
licenses = fields.List(fields.String(), metadata={
"description": "Package licenses",
"example": ["GPL3"],
})
make_depends = fields.List(fields.String(), metadata={
"description": "Package make dependencies list",
"example": ["python-build"],
})
opt_depends = fields.List(fields.String(), metadata={
"description": "Package optional dependencies list",
"example": ["python-aiohttp"],
})
provides = fields.List(fields.String(), metadata={
"description": "Package provides list",
"example": ["ahriman-git"],
})
url = fields.String(metadata={
"description": "Upstream url",
"example": "https://github.com/arcan1s/ahriman",
})
@@ -0,0 +1,49 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman import __version__
from ahriman.web.apispec import Schema, fields
from ahriman.web.schemas.package_properties_schema import PackagePropertiesSchema
from ahriman.web.schemas.remote_schema import RemoteSchema
class PackageSchema(Schema):
"""
request and response package schema
"""
base = fields.String(required=True, metadata={
"description": "Package base",
"example": "ahriman",
})
packager = fields.String(metadata={
"description": "packager for the last success package build",
"example": "ahriman bot <ahriman@example.com>",
})
packages = fields.Dict(
keys=fields.String(), values=fields.Nested(PackagePropertiesSchema()), required=True, metadata={
"description": "Packages which belong to this base",
})
remote = fields.Nested(RemoteSchema(), required=True, metadata={
"description": "Package remote properties",
})
version = fields.String(required=True, metadata={
"description": "Package version",
"example": __version__,
})
@@ -0,0 +1,56 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.models.build_status import BuildStatusEnum
from ahriman.web.apispec import Schema, fields
from ahriman.web.schemas.package_schema import PackageSchema
from ahriman.web.schemas.repository_id_schema import RepositoryIdSchema
from ahriman.web.schemas.status_schema import StatusSchema
class PackageStatusSchema(Schema):
"""
response package status schema
"""
package = fields.Nested(PackageSchema(), required=True, metadata={
"description": "Package description",
})
status = fields.Nested(StatusSchema(), required=True, metadata={
"description": "Last package status",
})
repository = fields.Nested(RepositoryIdSchema(), required=True, metadata={
"description": "Repository identifier",
})
class PackageStatusSimplifiedSchema(Schema):
"""
special request package status schema
"""
package = fields.Nested(PackageSchema(), metadata={
"description": "Package description",
})
status = fields.Enum(BuildStatusEnum, by_value=True, required=True, metadata={
"description": "Current status",
})
repository = fields.Nested(RepositoryIdSchema(), required=True, metadata={
"description": "Repository identifier",
})
@@ -0,0 +1,33 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman import __version__
from ahriman.web.apispec import fields
from ahriman.web.schemas.repository_id_schema import RepositoryIdSchema
class PackageVersionSchema(RepositoryIdSchema):
"""
request package name schema
"""
version = fields.String(metadata={
"description": "Package version",
"example": __version__,
})
@@ -0,0 +1,30 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class PackagerSchema(Schema):
"""
request packager schema
"""
packager = fields.String(metadata={
"description": "Packager identity if applicable",
})
@@ -0,0 +1,36 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import fields
from ahriman.web.schemas.repository_id_schema import RepositoryIdSchema
class PaginationSchema(RepositoryIdSchema):
"""
request pagination schema
"""
limit = fields.Integer(metadata={
"description": "Limit records by specified amount",
"example": 42,
})
offset = fields.Integer(metadata={
"description": "Start records with the offset",
"example": 100,
})
@@ -0,0 +1,32 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import fields
from ahriman.web.schemas.package_name_schema import PackageNameSchema
class PatchNameSchema(PackageNameSchema):
"""
request package patch schema
"""
patch = fields.String(required=True, metadata={
"description": "Variable name",
"example": "PKGEXT",
})
@@ -0,0 +1,33 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class PatchSchema(Schema):
"""
request and response patch schema
"""
key = fields.String(metadata={
"description": "environment variable name. Required in case if it is not full diff",
})
value = fields.String(metadata={
"description": "environment variable value",
})
@@ -0,0 +1,35 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class PGPKeyIdSchema(Schema):
"""
request PGP key ID schema
"""
key = fields.String(required=True, metadata={
"description": "PGP key ID",
"example": "0xE989490C",
})
server = fields.String(required=True, metadata={
"description": "PGP key server",
"example": "keyserver.ubuntu.com",
})
@@ -0,0 +1,30 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class PGPKeySchema(Schema):
"""
response PGP key schema
"""
key = fields.String(required=True, metadata={
"description": "PGP key body",
})
@@ -0,0 +1,31 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class ProcessIdSchema(Schema):
"""
request and response spawned process id schema
"""
process_id = fields.String(required=True, metadata={
"description": "Spawned process unique ID",
"example": "ff456814-5669-4de6-9143-44dbf6f68607",
})
@@ -0,0 +1,30 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class ProcessSchema(Schema):
"""
process status response schema
"""
is_alive = fields.Bool(required=True, metadata={
"description": "Is process alive or not",
})
@@ -0,0 +1,47 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.models.package_source import PackageSource
from ahriman.web.apispec import Schema, fields
class RemoteSchema(Schema):
"""
request and response package remote schema
"""
branch = fields.String(metadata={
"description": "Repository branch",
"example": "master",
})
git_url = fields.String(metadata={
"description": "Package git url",
"example": "https://aur.archlinux.org/ahriman.git",
})
path = fields.String(metadata={
"description": "Path to package sources in git repository",
"example": ".",
})
source = fields.Enum(PackageSource, by_value=True, required=True, metadata={
"description": "Package source",
})
web_url = fields.String(metadata={
"description": "Package repository page",
"example": "https://aur.archlinux.org/packages/ahriman",
})
@@ -0,0 +1,39 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class RepositoryIdSchema(Schema):
"""
request and response repository unique identifier schema
"""
architecture = fields.String(metadata={
"description": "Repository architecture",
"example": "x86_64",
})
id = fields.String(metadata={
"description": "Unique repository identifier",
"example": "x86_64-aur",
})
repository = fields.String(metadata={
"description": "Repository name",
"example": "aur",
})
@@ -0,0 +1,43 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class RepositoryStatsSchema(Schema):
"""
response repository stats schema
"""
archive_size = fields.Int(metadata={
"description": "Total archive size of the packages in bytes",
"example": 42000,
})
bases = fields.Int(metadata={
"description": "Amount of unique packages bases",
"example": 2,
})
installed_size = fields.Int(metadata={
"description": "Total installed size of the packages in bytes",
"example": 42000000,
})
packages = fields.Int(metadata={
"description": "Amount of unique packages",
"example": 4,
})
@@ -0,0 +1,40 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman import __version__
from ahriman.web.apispec import fields
from ahriman.web.schemas.packager_schema import PackagerSchema
class RollbackSchema(PackagerSchema):
"""
request schema for package rollback
"""
hold = fields.Boolean(dump_default=True, metadata={
"description": "Hold package after rollback",
})
package = fields.String(required=True, metadata={
"description": "Package name",
"example": "ahriman",
})
version = fields.String(required=True, metadata={
"description": "Package version",
"example": __version__,
})
@@ -0,0 +1,31 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class SearchSchema(Schema):
"""
request package search schema
"""
for_ = fields.List(fields.String(), data_key="for", required=True, metadata={
"description": "Keyword for search",
"example": ["ahriman"],
})
@@ -0,0 +1,35 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.models.event import EventType
from ahriman.web.apispec import Schema, fields
class SSESchema(Schema):
"""
response SSE schema
"""
event = fields.String(required=True, metadata={
"description": "Event type",
"example": EventType.PackageUpdated,
})
data = fields.Dict(keys=fields.String(), values=fields.Raw(), metadata={
"description": "Event data",
})
@@ -0,0 +1,38 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.models.build_status import BuildStatusEnum
from ahriman.web.apispec import Schema, fields
class StatusSchema(Schema):
"""
request and response status schema
"""
status = fields.Enum(BuildStatusEnum, by_value=True, required=True, metadata={
"description": "Current status",
})
timestamp = fields.Integer(metadata={
"description": "Last update timestamp",
"example": 1680537091,
})
is_held = fields.Boolean(metadata={
"description": "Package hold status",
})
@@ -0,0 +1,37 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import fields
from ahriman.web.schemas.build_options_schema import BuildOptionsSchema
class UpdateFlagsSchema(BuildOptionsSchema):
"""
update flags request schema
"""
aur = fields.Boolean(dump_default=True, metadata={
"description": "Check AUR for updates",
})
local = fields.Boolean(dump_default=True, metadata={
"description": "Check local packages for updates",
})
manual = fields.Boolean(dump_default=True, metadata={
"description": "Check manually built packages",
})
@@ -0,0 +1,35 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from ahriman.web.apispec import Schema, fields
class WorkerSchema(Schema):
"""
request and response schema for workers
"""
address = fields.String(required=True, metadata={
"description": "Worker address",
"example": "http://localhost:8081",
})
identifier = fields.String(required=True, metadata={
"description": "Worker unique identifier",
"example": "42f03a62-48f7-46b7-af40-dacc720e92fa",
})
@@ -0,0 +1,73 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from collections.abc import Callable
from typing import Any
from ahriman import __version__
from ahriman.core.auth.helpers import authorized_userid
from ahriman.core.types import Comparable
from ahriman.core.utils import pretty_interval
from ahriman.web.apispec import aiohttp_apispec
from ahriman.web.views.base import BaseView
__all__ = ["server_info"]
async def server_info(view: BaseView) -> dict[str, Any]:
"""
generate server info which can be used in responses directly
Args:
view(BaseView): view of the request
Returns:
dict[str, Any]: server info as a JSON response
"""
autorefresh_intervals = [
{
"interval": interval * 1000, # milliseconds
"is_active": index == 0, # first element is always default
"text": pretty_interval(interval),
}
for index, interval in enumerate(view.configuration.getintlist("web", "autorefresh_intervals", fallback=[]))
if interval > 0 # special case if 0 exists and first, refresh will not be turned on by default
]
comparator: Callable[[dict[str, Any]], Comparable] = lambda interval: interval["interval"]
return {
"auth": {
"control": view.validator.auth_control,
"enabled": view.validator.enabled,
"external": view.validator.is_external,
"username": await authorized_userid(view.request),
},
"autorefresh_intervals": sorted(autorefresh_intervals, key=comparator),
"docs_enabled": aiohttp_apispec is not None,
"index_url": view.configuration.get("web", "index_url", fallback=None),
"repositories": [
{
"id": repository_id.id,
**repository_id.view(),
}
for repository_id in sorted(view.services)
],
"version": __version__,
}
@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,65 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import aiohttp_jinja2
from typing import Any, ClassVar
from ahriman.core.configuration import Configuration
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec import aiohttp_apispec
from ahriman.web.views.base import BaseView
class DocsView(BaseView):
"""
api docs view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Unauthorized
ROUTES = ["/api-docs"]
@classmethod
def routes(cls, configuration: Configuration) -> list[str]:
"""
extract routes list for the view
Args:
configuration(Configuration): configuration instance
Returns:
list[str]: list of routes defined for the view. By default, it tries to read :attr:`ROUTES` option if set
and returns empty list otherwise
"""
if aiohttp_apispec is None:
return []
return cls.ROUTES
@aiohttp_jinja2.template("api.jinja2")
async def get(self) -> dict[str, Any]:
"""
return static docs HTML
Returns:
dict[str, Any]: parameters for jinja template
"""
return {}
@@ -0,0 +1,99 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import Response, json_response
from collections.abc import Callable
from typing import ClassVar
from ahriman.core.configuration import Configuration
from ahriman.core.utils import partition
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec import aiohttp_apispec
from ahriman.web.views.base import BaseView
class SwaggerView(BaseView):
"""
api docs specification view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Unauthorized
ROUTES = ["/api-docs/swagger.json"]
@classmethod
def routes(cls, configuration: Configuration) -> list[str]:
"""
extract routes list for the view
Args:
configuration(Configuration): configuration instance
Returns:
list[str]: list of routes defined for the view. By default, it tries to read :attr:`ROUTES` option if set
and returns empty list otherwise
"""
if aiohttp_apispec is None:
return []
return cls.ROUTES
async def get(self) -> Response:
"""
get api specification
Returns:
Response: 200 with JSON api specification
"""
spec = self.request.app["swagger_dict"]
is_body_parameter: Callable[[dict[str, str]], bool] = lambda p: p["in"] == "body" or p["in"] == "formData"
# special workaround because it writes request body to parameters section
paths = spec["paths"]
for methods in paths.values():
for method in methods.values():
if "parameters" not in method:
continue
body, other = partition(method["parameters"], is_body_parameter)
if not body:
continue # there were no ``body`` parameters found
schema = next(iter(body))
content_type = "multipart/form-data" if schema["in"] == "formData" else "application/json"
# there should be only one body parameters
method["requestBody"] = {
"content": {
content_type: {
"schema": schema["schema"]
}
}
}
method["parameters"] = other
# inject security schema
spec["components"]["securitySchemes"] = {
key: value
for schema in spec["security"]
for key, value in schema.items()
}
return json_response(spec)
+280
View File
@@ -0,0 +1,280 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNotFound, Request, Response, StreamResponse, View, json_response
from aiohttp_cors import CorsViewMixin
from collections.abc import Awaitable, Callable
from typing import Any, ClassVar, TypeVar
from ahriman.core.auth import Auth
from ahriman.core.configuration import Configuration
from ahriman.core.distributed import WorkersCache
from ahriman.core.exceptions import UnknownPackageError
from ahriman.core.sign.gpg import GPG
from ahriman.core.spawn import Spawn
from ahriman.core.status.watcher import Watcher
from ahriman.core.utils import filter_json
from ahriman.models.repository_id import RepositoryId
from ahriman.models.user_access import UserAccess
from ahriman.web.keys import AuthKey, ConfigurationKey, SpawnKey, WatcherKey, WorkersKey
T = TypeVar("T", str, list[str])
class BaseView(View, CorsViewMixin):
"""
base web view to make things typed
Attributes:
OPTIONS_PERMISSION(UserAccess): (class attribute) options permissions of self
ROUTES(list[str]): (class attribute) list of supported routes
"""
OPTIONS_PERMISSION: ClassVar[UserAccess] = UserAccess.Unauthorized
ROUTES: ClassVar[list[str]] = []
@property
def configuration(self) -> Configuration:
"""
get configuration instance
Returns:
Configuration: configuration instance
"""
return self.request.app[ConfigurationKey]
@property
def services(self) -> dict[RepositoryId, Watcher]:
"""
get all loaded watchers
Returns:
dict[RepositoryId, Watcher]: map of loaded watchers per known repository
"""
return self.request.app[WatcherKey]
@property
def sign(self) -> GPG:
"""
get GPG control instance
Returns:
GPG: GPG wrapper instance
"""
return GPG(self.configuration)
@property
def spawner(self) -> Spawn:
"""
get process spawner instance
Returns:
Spawn: external process spawner instance
"""
return self.request.app[SpawnKey]
@property
def validator(self) -> Auth:
"""
get authorization instance
Returns:
Auth: authorization service instance
"""
return self.request.app[AuthKey]
@property
def workers(self) -> WorkersCache:
"""
get workers cache instance
Returns:
WorkersCache: workers service
"""
return self.request.app[WorkersKey]
@classmethod
async def get_permission(cls, request: Request) -> UserAccess:
"""
retrieve user permission from the request
Args:
request(Request): request object
Returns:
UserAccess: extracted permission
"""
method = "GET" if (other := request.method.upper()) == "HEAD" else other
permission: UserAccess = getattr(cls, f"{method}_PERMISSION", UserAccess.Full)
return permission
@classmethod
def routes(cls, configuration: Configuration) -> list[str]:
"""
extract routes list for the view
Args:
configuration(Configuration): configuration instance
Returns:
list[str]: list of routes defined for the view. By default, it tries to read :attr:`ROUTES` option if set
and returns empty list otherwise
"""
del configuration
return cls.ROUTES
@staticmethod
def get_non_empty(extractor: Callable[[str], T | None], key: str) -> T:
"""
get non-empty value from request parameters
Args:
extractor(Callable[[str], T | None]): function to get value
key(str): key to extract value
Returns:
T: extracted values if it is presented and not empty
Raises:
KeyError: in case if key was not found or value is empty
"""
try:
value = extractor(key)
if not value:
raise KeyError(key)
except (KeyError, ValueError):
raise KeyError(f"Key {key} is missing or empty") from None
return value
@staticmethod
def json_response(data: dict[str, Any] | list[Any], **kwargs: Any) -> Response:
"""
filter and convert data and return :class:`aiohttp.web.Response` object
Args:
data(dict[str, Any] | list[Any]): response in JSON format
**kwargs(Any): keyword arguments for :func:`aiohttp.web.json_response` function
Returns:
Response: generated response object
"""
return json_response(filter_json(data), **kwargs)
# pylint: disable=not-callable,protected-access
async def head(self) -> StreamResponse:
"""
HEAD method implementation based on the result of GET method
Returns:
StreamResponse: generated response for the request
Raises:
HTTPMethodNotAllowed: in case if there is no GET method implemented
"""
get_method: Callable[..., Awaitable[StreamResponse]] | None = getattr(self, "get", None)
# using if/else in order to suppress mypy warning which doesn't know that
# :func:`aiohttp.web.View._raise_allowed_methods()` raises exception
if get_method is not None:
response = await get_method()
response._body = b""
return response
self._raise_allowed_methods()
def page(self) -> tuple[int, int]:
"""
parse limit and offset and return values
Returns:
tuple[int, int]: limit and offset from request
Raises:
HTTPBadRequest: if supplied parameters are invalid
"""
try:
limit = int(self.request.query.get("limit", -1))
offset = int(self.request.query.get("offset", 0))
except ValueError as ex:
raise HTTPBadRequest(reason=str(ex))
# some checks
if limit < -1:
raise HTTPBadRequest(reason=f"Limit must be -1 or non-negative, got {limit}")
if offset < 0:
raise HTTPBadRequest(reason=f"Offset must be non-negative, got {offset}")
return limit, offset
def repository_id(self) -> RepositoryId:
"""
extract repository from request
Returns:
RepositoryId: repository if possible to construct and first one otherwise
"""
architecture = self.request.query.get("architecture")
name = self.request.query.get("repository")
if architecture and name:
return RepositoryId(architecture, name)
return next(iter(sorted(self.services.keys())))
def service(self, repository_id: RepositoryId | None = None, package_base: str | None = None) -> Watcher:
"""
get status watcher instance
Args:
repository_id(RepositoryId | None, optional): repository unique identifier (Default value = None)
package_base(str | None, optional): package base to validate if exists (Default value = None)
Returns:
Watcher: build status watcher instance. If no repository provided, it will return the first one
Raises:
HTTPNotFound: if no repository found
"""
if repository_id is None:
repository_id = self.repository_id()
try:
return self.services[repository_id](package_base)
except KeyError:
raise HTTPNotFound(reason=f"Repository {repository_id.id} is unknown")
except UnknownPackageError:
raise HTTPNotFound(reason=f"Package {package_base} is unknown")
async def username(self) -> str | None:
"""
extract username from request if any
Returns:
str | None: authorized username if any and ``None`` otherwise (e.g. if authorization is disabled)
"""
try: # try to read from payload
data: dict[str, str] = await self.request.json() # technically it is not, but we only need str here
if (packager := data.get("packager")) is not None:
return packager
except Exception:
self.request.app.logger.exception("could not extract json data for packager")
policy = self.request.app.get("identity")
if policy is not None:
identity: str = await policy.identify(self.request)
return identity
return None
@@ -0,0 +1,69 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import aiohttp_jinja2
from aiohttp.web import Response
from typing import ClassVar
from ahriman.models.user_access import UserAccess
from ahriman.web.server_info import server_info
from ahriman.web.views.base import BaseView
class IndexView(BaseView):
"""
root view
It uses jinja2 templates for report generation, the following variables are allowed:
* auth - authorization descriptor, required
* control - HTML to insert for login control, HTML string, required
* enabled - whether authorization is enabled by configuration or not, boolean, required
* username - authenticated username if any, string, null means not authenticated
* autorefresh_intervals - auto refresh intervals, optional
* interval - auto refresh interval in milliseconds, integer, required
* is_active - is current interval active or not, boolean, required
* text - text representation of the interval (e.g. "30 seconds"), string, required
* docs_enabled - indicates if api docs is enabled, boolean, required
* index_url - url to the repository index, string, optional
* repositories - list of repositories unique identifiers, required
* id - unique repository identifier, string, required
* repository - repository name, string, required
* architecture - repository architecture, string, required
* version - service version, string, required
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Unauthorized
ROUTES = ["/", "/index.html"]
async def get(self) -> Response:
"""
process get request. No parameters supported here
Returns:
Response: 200 with rendered index page
"""
context = await server_info(self)
template = self.configuration.get("web", "template", fallback="build-status.jinja2")
return aiohttp_jinja2.render_template(template, self.request, context)
@@ -0,0 +1,48 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPFound, HTTPNotFound
from typing import ClassVar
from ahriman.models.user_access import UserAccess
from ahriman.web.views.base import BaseView
class StaticView(BaseView):
"""
special workaround for static files redirection (e.g. favicon)
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Unauthorized
ROUTES = ["/favicon.ico"]
async def get(self) -> None:
"""
process get request. No parameters supported here
Raises:
HTTPFound: on success response
HTTPNotFound: if path is invalid or unknown
"""
if self.request.path in self.ROUTES: # explicit validation
raise HTTPFound(f"/static{self.request.path}")
raise HTTPNotFound
@@ -0,0 +1,46 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from typing import ClassVar
from ahriman.core.configuration import Configuration
class StatusViewGuard:
"""
helper for check if status routes are enabled
"""
ROUTES: ClassVar[list[str]]
@classmethod
def routes(cls, configuration: Configuration) -> list[str]:
"""
extract routes list for the view
Args:
configuration(Configuration): configuration instance
Returns:
list[str]: list of routes defined for the view. By default, it tries to read :attr:`ROUTES` option if set
and returns empty list otherwise
"""
if configuration.getboolean("web", "service_only", fallback=False):
return []
return cls.ROUTES
@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,164 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import json
from aiohttp.web import HTTPBadRequest, Request, Response, StreamResponse
from aiohttp_sse import EventSourceResponse, sse_response
from asyncio import Queue, QueueShutDown, wait_for
from typing import ClassVar
from ahriman.core.status.event_bus import SSEvent
from ahriman.models.event import EventType
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import EventBusFilterSchema, SSESchema
from ahriman.web.views.base import BaseView
class EventBusView(BaseView):
"""
event bus SSE view
Attributes:
READ_EVENTS(set[EventType]): (class attribute) events which are allowed for read-only users
"""
READ_EVENTS: ClassVar[set[EventType]] = {
EventType.PackageHeld,
EventType.PackageOutdated,
EventType.PackageRemoved,
EventType.PackageStatusChanged,
EventType.PackageUpdateFailed,
EventType.PackageUpdated,
EventType.ServiceStatusChanged,
}
ROUTES = ["/api/v1/events/stream"]
@classmethod
async def get_permission(cls, request: Request) -> UserAccess:
"""
retrieve user permission from the request
Args:
request(Request): request object
Returns:
UserAccess: extracted permission
"""
if request.method.upper() not in ("GET", "HEAD"):
return await BaseView.get_permission(request)
permission = UserAccess.Full
try:
topics = cls(request)._topics()
except HTTPBadRequest:
topics = None
if topics is not None and set(topics).issubset(cls.READ_EVENTS):
permission = UserAccess.Read
return permission
@staticmethod
async def _run(response: EventSourceResponse, queue: Queue[SSEvent]) -> None:
"""
read events from queue and send them to the client
Args:
response(EventSourceResponse): SSE response instance
queue(Queue[SSEvent]): subscriber queue
"""
while response.is_connected():
try:
event_type, data = await wait_for(queue.get(), timeout=response.ping_interval)
except TimeoutError:
continue
except QueueShutDown:
break
await response.send(json.dumps(data), event=event_type)
def _topics(self) -> list[EventType] | None:
"""
parse event filter from request query
Returns:
list[EventType] | None: event filter if any
Raises:
HTTPBadRequest: if invalid event type is supplied
"""
if self.request.query is None:
return None
try:
return [EventType(event) for event in self.request.query.getall("event", [])] or None
except ValueError as ex:
raise HTTPBadRequest(reason=str(ex))
@apidocs(
tags=["Audit log"],
summary="Live updates",
description="Stream live updates via SSE. Read-only users may subscribe only when all requested event filters "
"belong to read-safe package and service status events; build log or unfiltered streams require "
"full access. Streams are live-only and do not replay missed events after reconnect.",
permission=UserAccess.Full,
error_400_enabled=True,
error_404_description="Repository is unknown",
schema=SSESchema(many=True),
query_schema=EventBusFilterSchema,
)
async def get(self) -> StreamResponse:
"""
subscribe on updates
Returns:
StreamResponse: 200 with streaming updates
"""
topics = self._topics()
object_id = self.request.query.get("object_id")
event_bus = self.service().event_bus
async with sse_response(self.request) as response:
subscription_id, queue = await event_bus.subscribe(topics, object_id=object_id)
try:
await self._run(response, queue)
except (ConnectionResetError, QueueShutDown):
pass
finally:
await event_bus.unsubscribe(subscription_id)
return response
async def head(self) -> StreamResponse:
"""
HEAD method implementation based on the result of GET method
Returns:
StreamResponse: generated response for the request
"""
self._topics()
self.service()
return Response(headers={
"Cache-Control": "no-cache",
"Content-Type": "text/event-stream",
})
@@ -0,0 +1,99 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent, Response
from typing import ClassVar
from ahriman.models.event import Event
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import EventSchema, EventSearchSchema
from ahriman.web.views.base import BaseView
class EventsView(BaseView):
"""
audit log view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
GET_PERMISSION = POST_PERMISSION = UserAccess.Full # type: ClassVar[UserAccess]
ROUTES = ["/api/v1/events"]
@apidocs(
tags=["Audit log"],
summary="Get events",
description="Retrieve events from audit log",
permission=GET_PERMISSION,
error_400_enabled=True,
schema=EventSchema(many=True),
query_schema=EventSearchSchema,
)
async def get(self) -> Response:
"""
get events list
Returns:
Response: 200 with workers list on success
"""
limit, offset = self.page()
event = self.request.query.get("event") or None
object_id = self.request.query.get("object_id") or None
try:
from_date = to_date = None
if (value := self.request.query.get("from_date")) is not None:
from_date = int(value)
if (value := self.request.query.get("to_date")) is not None:
to_date = int(value)
except ValueError as ex:
raise HTTPBadRequest(reason=str(ex))
events = await self.service().event_get(event, object_id, from_date, to_date, limit, offset)
response = [event.view() for event in events]
return self.json_response(response)
@apidocs(
tags=["Audit log"],
summary="Create event",
description="Add new event to the audit log",
permission=POST_PERMISSION,
error_400_enabled=True,
body_schema=EventSchema,
)
async def post(self) -> None:
"""
add new audit log event
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: in case of success response
"""
try:
data = await self.request.json()
event = Event.from_json(data)
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
await self.service().event_add(event)
raise HTTPNoContent
@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,107 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent, Response
from collections.abc import Callable
from typing import ClassVar
from ahriman.core.types import Comparable
from ahriman.models.user_access import UserAccess
from ahriman.models.worker import Worker
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import WorkerSchema
from ahriman.web.views.base import BaseView
class WorkersView(BaseView):
"""
distributed workers view
Attributes:
DELETE_PERMISSION(UserAccess): (class attribute) delete permissions of self
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
DELETE_PERMISSION = GET_PERMISSION = POST_PERMISSION = UserAccess.Full # type: ClassVar[UserAccess]
ROUTES = ["/api/v1/distributed"]
@apidocs(
tags=["Distributed"],
summary="Unregister all workers",
description="Unregister and remove all known workers from the service",
permission=DELETE_PERMISSION,
)
async def delete(self) -> None:
"""
unregister worker
Raises:
HTTPNoContent: on success response
"""
self.workers.workers_remove()
raise HTTPNoContent
@apidocs(
tags=["Distributed"],
summary="Get workers",
description="Retrieve registered workers",
permission=GET_PERMISSION,
schema=WorkerSchema(many=True),
)
async def get(self) -> Response:
"""
get workers list
Returns:
Response: 200 with workers list on success
"""
workers = self.workers.workers
comparator: Callable[[Worker], Comparable] = lambda item: item.identifier
response = [worker.view() for worker in sorted(workers, key=comparator)]
return self.json_response(response)
@apidocs(
tags=["Distributed"],
summary="Register worker",
description="Register or update remote worker",
permission=POST_PERMISSION,
error_400_enabled=True,
body_schema=WorkerSchema,
)
async def post(self) -> None:
"""
register remote worker
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: in case of success response
"""
try:
data = await self.request.json()
worker = Worker(data["address"], identifier=data["identifier"])
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
self.workers.workers_update(worker)
raise HTTPNoContent
@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,65 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import Response
from typing import ClassVar
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import PackageNameSchema, PackageSchema, RepositoryIdSchema
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class Archives(StatusViewGuard, BaseView):
"""
package archives web view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Reporter
ROUTES = ["/api/v1/packages/{package}/archives"]
@apidocs(
tags=["Packages"],
summary="Get package archives",
description="Retrieve built package archives for the base",
permission=GET_PERMISSION,
error_404_description="Package base and/or repository are unknown",
schema=PackageSchema(many=True),
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
)
async def get(self) -> Response:
"""
get package archives
Returns:
Response: 200 with package archives on success
Raises:
HTTPNotFound: if no package was found
"""
package_base = self.request.match_info["package"]
archives = await self.service(package_base=package_base).package_archives(package_base)
return self.json_response([archive.view() for archive in archives])
@@ -0,0 +1,102 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent, Response
from typing import ClassVar
from ahriman.models.changes import Changes
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import ChangesSchema, PackageNameSchema, RepositoryIdSchema
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class ChangesView(StatusViewGuard, BaseView):
"""
package changes web view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Reporter
POST_PERMISSION: ClassVar[UserAccess] = UserAccess.Full
ROUTES = ["/api/v1/packages/{package}/changes"]
@apidocs(
tags=["Packages"],
summary="Get package changes",
description="Retrieve package changes since the last build",
permission=GET_PERMISSION,
error_404_description="Package base and/or repository are unknown",
schema=ChangesSchema,
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
)
async def get(self) -> Response:
"""
get package changes
Returns:
Response: 200 with package change on success
Raises:
HTTPNotFound: if package base is unknown
"""
package_base = self.request.match_info["package"]
changes = await self.service(package_base=package_base).package_changes_get(package_base)
return self.json_response(changes.view())
@apidocs(
tags=["Packages"],
summary="Update package changes",
description="Update package changes to the new ones",
permission=POST_PERMISSION,
error_400_enabled=True,
error_404_description="Repository is unknown",
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
body_schema=ChangesSchema,
)
async def post(self) -> None:
"""
insert new package changes
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: in case of success response
"""
package_base = self.request.match_info["package"]
try:
data = await self.request.json()
last_commit_sha = data.get("last_commit_sha") # empty/null meant removal
change = data.get("changes")
pkgbuild = data.get("pkgbuild")
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
changes = Changes(last_commit_sha, change, pkgbuild)
await self.service().package_changes_update(package_base, changes)
raise HTTPNoContent
@@ -0,0 +1,100 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent, Response
from typing import ClassVar
from ahriman.models.dependencies import Dependencies
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import DependenciesSchema, PackageNameSchema, RepositoryIdSchema
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class DependenciesView(StatusViewGuard, BaseView):
"""
package dependencies web view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Reporter
POST_PERMISSION: ClassVar[UserAccess] = UserAccess.Full
ROUTES = ["/api/v1/packages/{package}/dependencies"]
@apidocs(
tags=["Packages"],
summary="Get package dependencies",
description="Retrieve package implicit dependencies",
permission=GET_PERMISSION,
error_404_description="Package base and/or repository are unknown",
schema=DependenciesSchema,
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
)
async def get(self) -> Response:
"""
get package dependencies
Returns:
Response: 200 with package implicit dependencies on success
Raises:
HTTPNotFound: if package base is unknown
"""
package_base = self.request.match_info["package"]
dependencies = await self.service(package_base=package_base).package_dependencies_get(package_base)
return self.json_response(dependencies.view())
@apidocs(
tags=["Packages"],
summary="Update package dependencies",
description="Set package implicit dependencies",
permission=POST_PERMISSION,
error_400_enabled=True,
error_404_description="Repository is unknown",
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
body_schema=DependenciesSchema,
)
async def post(self) -> None:
"""
insert new package dependencies
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: in case of success response
"""
package_base = self.request.match_info["package"]
try:
data = await self.request.json()
data["package_base"] = package_base # read from path instead of object
dependencies = Dependencies.from_json(data)
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
await self.service(package_base=package_base).package_dependencies_update(package_base, dependencies)
raise HTTPNoContent
@@ -0,0 +1,75 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent, HTTPNotFound
from typing import ClassVar
from ahriman.core.exceptions import UnknownPackageError
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import HoldSchema, PackageNameSchema, RepositoryIdSchema
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class HoldView(StatusViewGuard, BaseView):
"""
package hold web view
Attributes:
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
POST_PERMISSION: ClassVar[UserAccess] = UserAccess.Full
ROUTES = ["/api/v1/packages/{package}/hold"]
@apidocs(
tags=["Packages"],
summary="Update package hold status",
description="Set package hold status",
permission=POST_PERMISSION,
error_400_enabled=True,
error_404_description="Package base and/or repository are unknown",
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
body_schema=HoldSchema,
)
async def post(self) -> None:
"""
update package hold status
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: in case of success response
HTTPNotFound: if no package was found
"""
package_base = self.request.match_info["package"]
try:
data = await self.request.json()
is_held = data["is_held"]
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
try:
await self.service().package_hold_update(package_base, enabled=is_held)
except UnknownPackageError:
raise HTTPNotFound(reason=f"Package {package_base} is unknown")
raise HTTPNoContent
@@ -0,0 +1,132 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent, HTTPNotFound, Response
from typing import ClassVar
from ahriman.core.exceptions import UnknownPackageError
from ahriman.core.utils import pretty_datetime
from ahriman.models.log_record import LogRecord
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import LogSchema, LogsSchema, PackageNameSchema, PackageVersionSchema, RepositoryIdSchema
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class LogsView(StatusViewGuard, BaseView):
"""
package logs web view
Attributes:
DELETE_PERMISSION(UserAccess): (class attribute) delete permissions of self
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
DELETE_PERMISSION = POST_PERMISSION = UserAccess.Full # type: ClassVar[UserAccess]
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Reporter
ROUTES = ["/api/v1/packages/{package}/logs"]
@apidocs(
tags=["Packages"],
summary="Delete package logs",
description="Delete all logs which belong to the specified package",
permission=DELETE_PERMISSION,
error_404_description="Repository is unknown",
match_schema=PackageNameSchema,
query_schema=PackageVersionSchema,
)
async def delete(self) -> None:
"""
delete package logs
Raises:
HTTPNoContent: on success response
"""
package_base = self.request.match_info["package"]
version = self.request.query.get("version")
await self.service().package_logs_remove(package_base, version)
raise HTTPNoContent
@apidocs(
tags=["Packages"],
summary="Get package logs",
description="Retrieve all package logs and the last package status",
permission=GET_PERMISSION,
error_404_description="Package base and/or repository are unknown",
schema=LogsSchema,
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
)
async def get(self) -> Response:
"""
get last package logs
Returns:
Response: 200 with package logs on success
Raises:
HTTPNotFound: if package base is unknown
"""
package_base = self.request.match_info["package"]
try:
_, status = await self.service().package_get(package_base)
logs = await self.service(package_base=package_base).package_logs_get(package_base, None, None, -1, 0)
except UnknownPackageError:
raise HTTPNotFound(reason=f"Package {package_base} is unknown")
response = {
"package_base": package_base,
"status": status.view(),
"logs": "\n".join(f"[{pretty_datetime(log_record.created)}] {log_record.message}" for log_record in logs)
}
return self.json_response(response)
@apidocs(
tags=["Packages"],
summary="Add package logs",
description="Insert new package log record",
permission=POST_PERMISSION,
error_400_enabled=True,
error_404_description="Repository is unknown",
match_schema=PackageNameSchema,
body_schema=LogSchema,
)
async def post(self) -> None:
"""
create new package log record
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: in case of success response
"""
package_base = self.request.match_info["package"]
try:
data = await self.request.json()
log_record = LogRecord.from_json(package_base, data)
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
await self.service().package_logs_add(log_record)
raise HTTPNoContent
@@ -0,0 +1,146 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent, HTTPNotFound, Response
from typing import ClassVar
from ahriman.core.exceptions import UnknownPackageError
from ahriman.models.build_status import BuildStatusEnum
from ahriman.models.package import Package
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import (
PackageNameSchema,
PackageStatusSchema,
PackageStatusSimplifiedSchema,
RepositoryIdSchema,
)
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class PackageView(StatusViewGuard, BaseView):
"""
package base specific web view
Attributes:
DELETE_PERMISSION(UserAccess): (class attribute) delete permissions of self
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
DELETE_PERMISSION = POST_PERMISSION = UserAccess.Full # type: ClassVar[UserAccess]
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Read
ROUTES = ["/api/v1/packages/{package}"]
@apidocs(
tags=["Packages"],
summary="Delete package",
description="Delete package and its status from service",
permission=DELETE_PERMISSION,
error_404_description="Repository is unknown",
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
)
async def delete(self) -> None:
"""
delete package base from status page
Raises:
HTTPNoContent: on success response
"""
package_base = self.request.match_info["package"]
await self.service().package_remove(package_base)
raise HTTPNoContent
@apidocs(
tags=["Packages"],
summary="Get package",
description="Retrieve packages and its descriptor",
permission=GET_PERMISSION,
error_404_description="Package base and/or repository are unknown",
schema=PackageStatusSchema(many=True),
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
)
async def get(self) -> Response:
"""
get current package base status
Returns:
Response: 200 with package description on success
Raises:
HTTPNotFound: if no package was found
"""
package_base = self.request.match_info["package"]
repository_id = self.repository_id()
try:
package, status = await self.service(repository_id).package_get(package_base)
except UnknownPackageError:
raise HTTPNotFound(reason=f"Package {package_base} is unknown")
response = [
{
"package": package.view(),
"status": status.view(),
"repository": repository_id.view(),
}
]
return self.json_response(response)
@apidocs(
tags=["Packages"],
summary="Update package",
description="Update package status and set its descriptor optionally",
permission=POST_PERMISSION,
error_400_enabled=True,
error_404_description="Repository is unknown",
match_schema=PackageNameSchema,
query_schema=RepositoryIdSchema,
body_schema=PackageStatusSimplifiedSchema,
)
async def post(self) -> None:
"""
update package build status
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: in case of success response
"""
package_base = self.request.match_info["package"]
try:
data = await self.request.json()
package = Package.from_json(data["package"]) if "package" in data else None
status = BuildStatusEnum(data["status"])
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
try:
if package is None:
await self.service().package_status_update(package_base, status)
else:
await self.service().package_update(package, status)
except UnknownPackageError:
raise HTTPBadRequest(reason=f"Package {package_base} is unknown, but no package body set")
raise HTTPNoContent
@@ -0,0 +1,100 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import itertools
from aiohttp.web import HTTPNoContent, Response
from collections.abc import Callable
from typing import ClassVar
from ahriman.core.types import Comparable
from ahriman.models.build_status import BuildStatus
from ahriman.models.package import Package
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import PackageStatusSchema, PaginationSchema, RepositoryIdSchema
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class PackagesView(StatusViewGuard, BaseView):
"""
global watcher view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Read
POST_PERMISSION: ClassVar[UserAccess] = UserAccess.Full
ROUTES = ["/api/v1/packages"]
@apidocs(
tags=["Packages"],
summary="Get packages list",
description="Retrieve packages and their descriptors",
permission=GET_PERMISSION,
error_400_enabled=True,
error_404_description="Repository is unknown",
schema=PackageStatusSchema(many=True),
query_schema=PaginationSchema,
)
async def get(self) -> Response:
"""
get current packages status
Returns:
Response: 200 with package description on success
"""
limit, offset = self.page()
stop = offset + limit if limit >= 0 else None
repository_id = self.repository_id()
packages = await self.service(repository_id).packages()
comparator: Callable[[tuple[Package, BuildStatus]], Comparable] = lambda items: items[0].base
response = [
{
"package": package.view(),
"status": status.view(),
"repository": repository_id.view(),
} for package, status in itertools.islice(sorted(packages, key=comparator), offset, stop)
]
return self.json_response(response)
@apidocs(
tags=["Packages"],
summary="Load packages",
description="Load packages from cache",
permission=POST_PERMISSION,
error_404_description="Repository is unknown",
query_schema=RepositoryIdSchema,
)
async def post(self) -> None:
"""
reload all packages from repository
Raises:
HTTPNoContent: on success response
"""
await self.service().load()
raise HTTPNoContent
@@ -0,0 +1,92 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPNoContent, HTTPNotFound, Response
from typing import ClassVar
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import PatchNameSchema, PatchSchema
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class PatchView(StatusViewGuard, BaseView):
"""
package patch web view
Attributes:
DELETE_PERMISSION(UserAccess): (class attribute) delete permissions of self
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
"""
DELETE_PERMISSION: ClassVar[UserAccess] = UserAccess.Full
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Reporter
ROUTES = ["/api/v1/packages/{package}/patches/{patch}"]
@apidocs(
tags=["Packages"],
summary="Delete package patch",
description="Delete package patch by variable",
permission=DELETE_PERMISSION,
match_schema=PatchNameSchema,
)
async def delete(self) -> None:
"""
delete package patch
Raises:
HTTPNoContent: on success response
"""
package_base = self.request.match_info["package"]
variable = self.request.match_info["patch"]
await self.service().package_patches_remove(package_base, variable)
raise HTTPNoContent
@apidocs(
tags=["Packages"],
summary="Get package patch",
description="Retrieve package patch by variable",
permission=GET_PERMISSION,
error_404_description="Patch name is unknown",
schema=PatchSchema,
match_schema=PatchNameSchema,
)
async def get(self) -> Response:
"""
get package patch
Returns:
Response: 200 with package patch on success
Raises:
HTTPNotFound: if package patch is unknown
"""
package_base = self.request.match_info["package"]
variable = self.request.match_info["patch"]
patches = await self.service().package_patches_get(package_base, variable)
selected = next((patch for patch in patches if patch.key == variable), None)
if selected is None:
raise HTTPNotFound(reason=f"Patch {variable} is unknown")
return self.json_response(selected.view())
@@ -0,0 +1,93 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent, Response
from typing import ClassVar
from ahriman.models.pkgbuild_patch import PkgbuildPatch
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import PackageNameSchema, PatchSchema
from ahriman.web.views.base import BaseView
from ahriman.web.views.status_view_guard import StatusViewGuard
class PatchesView(StatusViewGuard, BaseView):
"""
package patches web view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
GET_PERMISSION: ClassVar[UserAccess] = UserAccess.Reporter
POST_PERMISSION: ClassVar[UserAccess] = UserAccess.Full
ROUTES = ["/api/v1/packages/{package}/patches"]
@apidocs(
tags=["Packages"],
summary="Get package patches",
description="Retrieve all package patches",
permission=GET_PERMISSION,
schema=PatchSchema(many=True),
match_schema=PackageNameSchema,
)
async def get(self) -> Response:
"""
get package patches
Returns:
Response: 200 with package patches on success
"""
package_base = self.request.match_info["package"]
patches = await self.service().package_patches_get(package_base, None)
response = [patch.view() for patch in patches]
return self.json_response(response)
@apidocs(
tags=["Packages"],
summary="Update package patch",
description="Update or create package patch",
permission=POST_PERMISSION,
error_400_enabled=True,
match_schema=PackageNameSchema,
body_schema=PatchSchema,
)
async def post(self) -> None:
"""
update or create package patch
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: on success response
"""
package_base = self.request.match_info["package"]
try:
data = await self.request.json()
key = data.get("key")
value = data["value"]
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
await self.service().package_patches_update(package_base, PkgbuildPatch.parse(key, value))
raise HTTPNoContent
@@ -0,0 +1,19 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
@@ -0,0 +1,80 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, Response
from typing import ClassVar
from ahriman.models.pkgbuild_patch import PkgbuildPatch
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import PackagePatchSchema, ProcessIdSchema, RepositoryIdSchema
from ahriman.web.views.base import BaseView
class AddView(BaseView):
"""
add package web view
Attributes:
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
POST_PERMISSION: ClassVar[UserAccess] = UserAccess.Full
ROUTES = ["/api/v1/service/add"]
@apidocs(
tags=["Actions"],
summary="Add new package",
description="Add new package(s) from AUR",
permission=POST_PERMISSION,
error_400_enabled=True,
schema=ProcessIdSchema,
query_schema=RepositoryIdSchema,
body_schema=PackagePatchSchema,
)
async def post(self) -> Response:
"""
add new package
Returns:
Response: 200 with spawned process id
Raises:
HTTPBadRequest: if bad data is supplied
"""
try:
data = await self.request.json()
packages = self.get_non_empty(lambda key: [package for package in data[key] if package], "packages")
patches = [PkgbuildPatch.parse(patch["key"], patch.get("value", "")) for patch in data.get("patches", [])]
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
repository_id = self.repository_id()
username = await self.username()
process_id = self.spawner.packages_add(
repository_id,
packages,
username,
patches=patches,
now=True,
increment=data.get("increment", True),
refresh=data.get("refresh", False),
)
return self.json_response({"process_id": process_id})
@@ -0,0 +1,84 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPNoContent, Response
from typing import ClassVar
from ahriman.core.formatters import ConfigurationPrinter
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import ConfigurationSchema
from ahriman.web.views.base import BaseView
class ConfigView(BaseView):
"""
configuration control view
Attributes:
GET_PERMISSION(UserAccess): (class attribute) get permissions of self
POST_PERMISSION(UserAccess): (class attribute) post permissions of self
"""
GET_PERMISSION = POST_PERMISSION = UserAccess.Full # type: ClassVar[UserAccess]
ROUTES = ["/api/v1/service/config"]
@apidocs(
tags=["Actions"],
summary="Get configuration",
description="Get current web service configuration as nested dictionary",
permission=GET_PERMISSION,
schema=ConfigurationSchema(many=True),
)
async def get(self) -> Response:
"""
get current web service configuration
Returns:
Response: current web service configuration as nested dictionary
"""
dump = self.configuration.dump()
response = [
{
"section": section,
"key": key,
"value": value,
} for section, values in dump.items()
for key, value in values.items()
if key not in ConfigurationPrinter.HIDE_KEYS
]
return self.json_response(response)
@apidocs(
tags=["Actions"],
summary="Reload configuration",
description="Reload configuration from current files",
permission=POST_PERMISSION,
)
async def post(self) -> None:
"""
reload web service configuration
Raises:
HTTPNoContent: on success response
"""
self.configuration.reload()
raise HTTPNoContent
@@ -0,0 +1,64 @@
#
# Copyright (c) 2021-2026 ahriman team.
#
# This file is part of ahriman
# (see https://github.com/arcan1s/ahriman).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from aiohttp.web import HTTPBadRequest, HTTPNoContent
from typing import ClassVar
from ahriman.models.user_access import UserAccess
from ahriman.web.apispec.decorators import apidocs
from ahriman.web.schemas import LogsRotateSchema
from ahriman.web.views.base import BaseView
class LogsView(BaseView):
"""
logs management web view
Attributes:
DELETE_PERMISSION(UserAccess): (class attribute) delete permissions of self
"""
DELETE_PERMISSION: ClassVar[UserAccess] = UserAccess.Full
ROUTES = ["/api/v1/service/logs"]
@apidocs(
tags=["Actions"],
summary="Rotate logs",
description="Remove older logs from system",
permission=DELETE_PERMISSION,
error_400_enabled=True,
error_404_description="Repository is unknown",
query_schema=LogsRotateSchema,
)
async def delete(self) -> None:
"""
rotate logs from system
Raises:
HTTPBadRequest: if bad data is supplied
HTTPNoContent: on success response
"""
try:
keep_last_records = int(self.request.query.get("keep_last_records", 0))
except Exception as ex:
raise HTTPBadRequest(reason=str(ex))
await self.service().logs_rotate(keep_last_records)
raise HTTPNoContent
Loaded 100 of 815 files, more files were not shown because too many files have changed in this diff. Show more