Wazuh Server
Platform:
| Channel | Revision | Published | Runs on |
|---|---|---|---|
| 4.11/stable | 274 | 26 Aug 2026 | |
| 4.11/edge | 286 | 10 Oct 2026 | |
| 4.14/stable | 303 | Today | |
| 4.14/edge | 303 | 17 Nov 2026 |
juju deploy wazuh-server --channel 4.11/stable
-
- Last updated
- Revision Library version 0.5
# Copyright 2025 Canonical Ltd.
# Licensed under the Apache2.0. See LICENSE file in charm source for details.
"""Library to manage the integration with the Wazuh Server charm.
This library contains the Requires and Provides classes for handling the integration
between an application and a charm providing the `wazuh-apli-client` integration.
This library also contains a `WazuhApiRelationData` class to wrap the data that will
be shared via the integration.
### Requirer Charm
```python
from charms.wazuh_server.v0.wazuh_api import WazuhApiDataAvailableEvent, WazuhApiRequires
class WazuhApiRequirerCharm(ops.CharmBase):
def __init__(self, *args):
super().__init__(*args)
self.wazuh_api = wazuh_api.WazuhApiRequires(self)
self.framework.observe(self.wazuh_api.on.wazuh_api_data_available, self._handler)
...
def _handler(self, events: WazuhApiDataAvailableEvent) -> None:
...
```
As shown above, the library provides a custom event to handle the scenario in
which new Wazuh API data has been added or updated.
Credential reads refresh the consumer's tracked secret revision and read both
fields from one content snapshot. Requirers should also observe `secret-changed`
and call `get_relation_data()` when their credentials secret changes: rotating a
secret does not necessarily change the relation databag.
`get_relation_data()` returns `None` with a diagnostic when published data is
incomplete, invalid, or its secret is unavailable. Credential access through the
custom event raises `SecretError` when the secret cannot be used.
### Provider Charm
Following the previous example, this is an example of the provider charm.
```python
from charms.wazuh_server.v0.wazuh_api import import WazuhApiProvides
class WazuhApiProviderCharm(ops.CharmBase):
def __init__(self, *args):
super().__init__(*args)
self.wazuh_api = WazuhApiProvides(self)
...
```
The WazuhApiProvides object wraps the list of relations into a `relations` property
and provides an `update_relation_data` method to update the relation data by passing
a `WazuhApiRelationData` data object.
```python
class WazuhApiProviderCharm(ops.CharmBase):
...
def _on_config_changed(self, _) -> None:
for relation in self.model.relations[self.wazuh_api.relation_name]:
self.wazuh_api.update_relation_data(relation, self._get_wazuh_api_data())
```
"""
# The unique Charmhub library identifier, never change it
LIBID = "f0b9836db9604a9491247244109c24e6"
# Increment this major API version when introducing breaking changes
LIBAPI = 0
# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 5
PYDEPS = ["pydantic>=2"]
# pylint: disable=wrong-import-position
import logging # noqa: E402
import typing # noqa: E402
from typing import Dict, Optional # noqa: E402
import ops # noqa: E402
from pydantic import AnyHttpUrl, BaseModel, ValidationError # noqa: E402
# The wazuh dashboard charm dependencies require pydantic<2
# Disable used-before-assignment as parse_obj_as will not be recognized pylint
# pylint: disable=used-before-assignment
try:
from pydantic import TypeAdapter
except ImportError:
from pydantic import parse_obj_as
logger = logging.getLogger(__name__)
RELATION_NAME = "wazuh-api"
WAZUH_API_KEY_SECRET_LABEL = "wazuh-api-remote-credentials"
class SecretError(Exception):
"""Common ancestor for Secrets related exceptions."""
def _get_credentials(model: ops.Model, secret_id: str | None) -> tuple[str, str]:
"""Read and validate a single snapshot of the latest credentials."""
if not secret_id:
raise SecretError("Missing Wazuh API credentials secret ID")
try:
content = model.get_secret(id=secret_id).get_content(refresh=True)
except ops.ModelError as exc:
raise SecretError("Could not access Wazuh API credentials secret") from exc
user = content.get("user")
password = content.get("password")
if not isinstance(user, str) or not user:
raise SecretError("Missing or invalid Wazuh API credentials field: user")
if not isinstance(password, str) or not password:
raise SecretError("Missing or invalid Wazuh API credentials field: password")
return user, password
class WazuhApiRelationData(BaseModel):
"""Represent the relation data.
Attributes:
endpoint: The API endpoint.
user: The user to authenticate against the API.
password: The password to authenticate against the API.
user_credentials_secret: The secret ID containing the API credentials.
"""
endpoint: AnyHttpUrl
user: str
password: str
user_credentials_secret: str
def to_relation_data(self) -> Dict[str, str]:
"""Convert an instance of WazuhApiRelationData to the relation representation.
Returns:
Dict containing the representation.
"""
return {
"endpoint": str(self.endpoint),
"user_credentials_secret": self.user_credentials_secret,
}
class WazuhApiDataAvailableEvent(ops.RelationEvent):
"""Event emitted when relation data has changed.
Attributes:
endpoint: The API endpoint.
user: The user to authenticate against the API.
password: The password to authenticate against the API.
"""
@property
def endpoint(self) -> AnyHttpUrl:
"""Fetch the endpoint from the relation."""
assert self.relation.app # noqa: S101
url = typing.cast(str, self.relation.data[self.relation.app].get("endpoint"))
try:
return TypeAdapter(AnyHttpUrl).validate_python(url)
except NameError:
return parse_obj_as(AnyHttpUrl, url)
@property
def _credentials(self) -> tuple[str, str]:
"""Fetch the API credentials from the relation."""
assert self.relation.app # noqa: S101
relation_data = self.relation.data[self.relation.app]
return _get_credentials(self.framework.model, relation_data.get("user_credentials_secret"))
@property
def user(self) -> str:
"""Fetch the user from the relation."""
assert self.relation.app # noqa: S101
return self._credentials[0]
@property
def password(self) -> str:
"""Fetch the password from the relation."""
assert self.relation.app # noqa: S101
return self._credentials[1]
class WazuhApiRequiresEvents(ops.CharmEvents):
"""Wazuh API events.
This class defines the events that a requirer can emit.
Attributes:
wazuh_api_data_available: the WazuhApiDataAvailableEvent.
"""
wazuh_api_data_available = ops.EventSource(WazuhApiDataAvailableEvent)
class WazuhApiRequires(ops.Object):
"""Requirer side of the Wazuh API client relation.
Attributes:
on: events the provider can emit.
"""
on = WazuhApiRequiresEvents()
def __init__(self, charm: ops.CharmBase, relation_name: str = RELATION_NAME) -> None:
"""Construct.
Args:
charm: the provider charm.
relation_name: the relation name.
"""
super().__init__(charm, relation_name)
self.charm = charm
self.relation_name = relation_name
self.framework.observe(charm.on[relation_name].relation_changed, self._on_relation_changed)
def get_relation_data(self) -> Optional[WazuhApiRelationData]:
"""Retrieve the relation data.
Returns:
WazuhApiRelationData: validated data, or None if not ready or unusable.
"""
relation = self.model.get_relation(self.relation_name)
if relation is None:
logger.debug("No Wazuh API relation available")
return None
return self._get_relation_data_from_relation(relation)
def _get_relation_data_from_relation(
self, relation: ops.Relation
) -> WazuhApiRelationData | None:
"""Retrieve the relation data.
Args:
relation: the relation to retrieve the data from.
Returns:
WazuhApiRelationData: the relation data if found.
"""
if relation.app is None:
logger.debug("Wazuh API relation %s has no remote application", relation.id)
return None
relation_data = relation.data[relation.app]
secret_id = relation_data.get("user_credentials_secret")
url = relation_data.get("endpoint")
if not secret_id or not url:
logger.debug("Wazuh API relation %s is awaiting endpoint and credentials", relation.id)
return None
try:
try:
endpoint: AnyHttpUrl = TypeAdapter(AnyHttpUrl).validate_python(url)
except NameError:
endpoint = parse_obj_as(AnyHttpUrl, url)
user, password = _get_credentials(self.model, secret_id)
return WazuhApiRelationData(
endpoint=endpoint,
user_credentials_secret=secret_id,
user=user,
password=password,
)
except SecretError as exc:
logger.warning("Wazuh API relation %s: %s", relation.id, exc)
except ValidationError:
logger.warning("Wazuh API relation %s has an invalid endpoint", relation.id)
return None
def _is_relation_data_valid(self, relation: ops.Relation) -> bool:
"""Validate the relation data.
Args:
relation: the relation to validate.
Returns:
true: if the relation data is valid.
"""
return self._get_relation_data_from_relation(relation) is not None
def _on_relation_changed(self, event: ops.RelationChangedEvent) -> None:
"""Event emitted when the relation has changed.
Args:
event: event triggering this handler.
"""
if self._is_relation_data_valid(event.relation):
self.on.wazuh_api_data_available.emit(event.relation, app=event.app, unit=event.unit)
class WazuhApiProvides(ops.Object):
"""Provider side of the Wazuh API relation."""
def __init__(self, charm: ops.CharmBase, relation_name: str = RELATION_NAME) -> None:
"""Construct.
Args:
charm: the provider charm.
relation_name: the relation name.
"""
super().__init__(charm, relation_name)
self.charm = charm
self.relation_name = relation_name
def update_relation_data(
self, relation: ops.Relation, wazuh_api_data: WazuhApiRelationData
) -> None:
"""Update the relation data.
Args:
relation: the relation for which to update the data.
wazuh_api_data: a WazuhApiRelationData instance wrapping the data to be updated.
"""
relation_data = wazuh_api_data.to_relation_data()
relation.data[self.charm.model.app].update(relation_data)