Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions spp_audit/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,14 @@ External Python: ``requests`` (HTTP backend)
Changelog
=========

19.0.2.0.3
~~~~~~~~~~

- fix: mark the server-internal audit methods ``@api.private`` — backend
``write_entry`` / ``is_enabled`` and the rule's ``log``,
``log_lifecycle_action``, ``get_audit_rules``; server-side callers are
unaffected

19.0.2.0.2
~~~~~~~~~~

Expand Down
2 changes: 1 addition & 1 deletion spp_audit/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"name": "OpenSPP Audit",
"summary": "Comprehensively tracks all data modifications and user actions across the OpenSPP platform, recording old and new values for configured data. It enhances accountability and data integrity by maintaining an immutable history of changes, crucial for internal audits, compliance, and detecting unauthorized alterations. Supports multiple backends (database, file, syslog, HTTP) with tamper-resistant configuration.",
"category": "OpenSPP/Monitoring",
"version": "19.0.2.0.2",
"version": "19.0.2.0.3",
"sequence": 1,
"author": "OpenSPP.org",
"website": "https://github.com/OpenSPP/OpenSPP2",
Expand Down
13 changes: 13 additions & 0 deletions spp_audit/models/spp_audit_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,16 @@ class SppAuditBackend(models.AbstractModel):

Subclasses must implement _write_entry() to handle the actual
storage of audit entries.

Backend methods are private: they are for trusted server code only and
are not RPC-dispatchable.
"""

_name = "spp.audit.backend"
_description = "Abstract Audit Backend"

@api.model
@api.private
def write_entry(self, entry, env=None):
"""Write an audit entry to this backend.

Expand All @@ -144,6 +148,7 @@ def write_entry(self, entry, env=None):
raise NotImplementedError("Subclasses must implement write_entry()")

@api.model
@api.private
def is_enabled(self, env=None):
"""Check if this backend is enabled."""
raise NotImplementedError("Subclasses must implement is_enabled()")
Expand All @@ -157,10 +162,12 @@ class SppAuditBackendDb(models.AbstractModel):
_description = "Database Audit Backend"

@api.model
@api.private
def is_enabled(self, env=None):
return AuditConfig.get_bool("backend_db", env=env)

@api.model
@api.private
def write_entry(self, entry, env=None):
"""Write audit entry to database.

Expand Down Expand Up @@ -188,6 +195,7 @@ class SppAuditBackendFile(models.AbstractModel):
_current_date = None

@api.model
@api.private
def is_enabled(self, env=None):
return AuditConfig.get_bool("backend_file", env=env)

Expand Down Expand Up @@ -237,6 +245,7 @@ def _get_file_handle(cls, env=None):
return cls._file_handle

@api.model
@api.private
def write_entry(self, entry, env=None):
"""Write audit entry to JSONL file."""
try:
Expand Down Expand Up @@ -265,6 +274,7 @@ class SppAuditBackendSyslog(models.AbstractModel):
_syslog_initialized = False

@api.model
@api.private
def is_enabled(self, env=None):
return AuditConfig.get_bool("backend_syslog", env=env)

Expand Down Expand Up @@ -293,6 +303,7 @@ def _init_syslog(cls, env=None):
cls._syslog_initialized = True

@api.model
@api.private
def write_entry(self, entry, env=None):
"""Write audit entry to syslog."""
try:
Expand All @@ -317,6 +328,7 @@ class SppAuditBackendHttp(models.AbstractModel):
_description = "HTTP Webhook Audit Backend"

@api.model
@api.private
def is_enabled(self, env=None):
if not AuditConfig.get_bool("backend_http", env=env):
return False
Expand All @@ -325,6 +337,7 @@ def is_enabled(self, env=None):
return bool(endpoint)

@api.model
@api.private
def write_entry(self, entry, env=None):
"""Write audit entry to HTTP endpoint."""
endpoint = AuditConfig.get("http_endpoint", env=env)
Expand Down
9 changes: 9 additions & 0 deletions spp_audit/models/spp_audit_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,13 @@ def _process_action_id(self):
return

@api.model
@api.private
def get_audit_rules(self, method):
"""
The function returns audit rules based on the specified method.

Private: not RPC-dispatchable, on this model or on the audited models it is attached to.

:param method: The "method" parameter is a string that specifies the type of operation being
performed. It can have one of the following values: "create", "write", or "unlink"
:return: The method is returning a search result of "spp.audit.rule" records based on the
Expand Down Expand Up @@ -526,10 +529,13 @@ def get_audit_log_vals(self, res_id, method, data):
"parent_res_ids_str": ",".join(parent_res_ids),
}

@api.private
def log(self, method, old_values=None, new_values=None):
"""
Log changes made to a model's records by dispatching to all enabled backends.

Private: for server-side callers only, not RPC-dispatchable.

:param method: The operation type: "create", "write", "unlink", or lifecycle action
:param old_values: Dict of previous field values
:param new_values: Dict of updated field values
Expand Down Expand Up @@ -572,12 +578,15 @@ def log(self, method, old_values=None, new_values=None):
)

@api.model
@api.private
def log_lifecycle_action(self, model_name, record_id, action, old_values=None, new_values=None):
"""Log a lifecycle action for a record.

This is called explicitly from models (not via decorator).
Used for activate/deactivate/approve/reject/set_draft/download/preview/export actions.

Private: for server-side callers only, not RPC-dispatchable.

:param model_name: Technical model name (e.g., 'spp.studio.field')
:param record_id: ID of the record being logged
:param action: Action type - 'activate', 'deactivate', 'set_draft', 'approve', 'reject',
Expand Down
4 changes: 4 additions & 0 deletions spp_audit/readme/HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
### 19.0.2.0.3

- fix: mark the server-internal audit methods `@api.private` — backend `write_entry` / `is_enabled` and the rule's `log`, `log_lifecycle_action`, `get_audit_rules`; server-side callers are unaffected

### 19.0.2.0.2

- feat: `audit_disable` context key lets trusted machine flows (e.g. cross-instance replication of records already audited at their source) bypass audit logging and its full-record snapshot reads in create/write/unlink
Expand Down
13 changes: 11 additions & 2 deletions spp_audit/static/description/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,15 @@ <h2><a class="toc-backref" href="#toc-entry-1">Changelog</a></h2>
</div>
</div>
<div class="section" id="section-1">
<h1>19.0.2.0.3</h1>
<ul class="simple">
<li>fix: mark the server-internal audit methods <tt class="docutils literal">&#64;api.private</tt> — backend
<tt class="docutils literal">write_entry</tt> / <tt class="docutils literal">is_enabled</tt> and the rule’s <tt class="docutils literal">log</tt>,
<tt class="docutils literal">log_lifecycle_action</tt>, <tt class="docutils literal">get_audit_rules</tt>; server-side callers are
unaffected</li>
</ul>
</div>
<div class="section" id="section-2">
<h1>19.0.2.0.2</h1>
<ul class="simple">
<li>feat: <tt class="docutils literal">audit_disable</tt> context key lets trusted machine flows (e.g.
Expand All @@ -529,7 +538,7 @@ <h1>19.0.2.0.2</h1>
per-record searches) on every create/write of an audited model</li>
</ul>
</div>
<div class="section" id="section-2">
<div class="section" id="section-3">
<h1>19.0.2.0.1</h1>
<ul class="simple">
<li>fix: use &#64;api.model_create_multi for audit_create to support Odoo 19
Expand All @@ -542,7 +551,7 @@ <h1>19.0.2.0.1</h1>
<tt class="docutils literal">parent_data_html</tt> fields to prevent stored XSS (#50)</li>
</ul>
</div>
<div class="section" id="section-3">
<div class="section" id="section-4">
<h1>19.0.2.0.0</h1>
<ul class="simple">
<li>Initial migration to OpenSPP2</li>
Expand Down
1 change: 1 addition & 0 deletions spp_audit/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from . import test_audit_backend
from . import test_audit_disable
from . import test_html_escaping
from . import test_rpc_exposure
from . import test_spp_audit_rule
175 changes: 175 additions & 0 deletions spp_audit/tests/test_rpc_exposure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
"""Audit internals are server-side only and not RPC-dispatchable.

The audit backends and the rule's logging entry points write to the audit
trail on behalf of the server.
"""

import json
import os
import shutil
import tempfile
from unittest.mock import patch

from odoo import Command
from odoo.exceptions import AccessError
from odoo.service.model import call_kw
from odoo.tests.common import TransactionCase, new_test_user

BACKEND_MODELS = [
"spp.audit.backend",
"spp.audit.backend.db",
"spp.audit.backend.file",
"spp.audit.backend.syslog",
"spp.audit.backend.http",
]

SAMPLE_ENTRY = {
"seq": 1,
"ts": "2000-01-01T00:00:00+00:00",
"node": "test-node",
"rule_name": "Sample",
"model": "res.partner",
"res_id": 1,
"method": "write",
"user_id": 1,
"user_login": "sample.user",
"data": {"old": {"name": "Old"}, "new": {"name": "New"}},
}

PRIVATE_ERROR = "cannot be called remotely"


class RpcExposureCommon(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.internal_user = new_test_user(cls.env, login="audit_rpc_internal", groups="base.group_user")
cls.portal_user = new_test_user(cls.env, login="audit_rpc_portal", groups="base.group_portal")
cls.audit_manager = new_test_user(
cls.env,
login="audit_rpc_manager",
groups="base.group_user,spp_audit.group_audit_manager",
)
partner_model = cls.env["ir.model"].search([("model", "=", "res.partner")], limit=1)
cls.partner_rule = cls.env["spp.audit.rule"].search([("model_id", "=", partner_model.id)], limit=1)
name_field = cls.env["ir.model.fields"].search(
[("model_id", "=", partner_model.id), ("name", "=", "name")], limit=1
)
rule_vals = {
"is_log_create": True,
"is_log_write": True,
"field_to_log_ids": [Command.link(name_field.id)],
}
if cls.partner_rule:
cls.partner_rule.write(rule_vals)
else:
cls.partner_rule = cls.env["spp.audit.rule"].create(
dict(rule_vals, name="RPC exposure partner rule", model_id=partner_model.id)
)

def setUp(self):
super().setUp()
self.temp_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.temp_dir, ignore_errors=True)

def _reset_file_handle(self):
"""Drop the file backend's cached handle, which is kept per process."""
file_backend = type(self.env["spp.audit.backend.file"])
if file_backend._file_handle is not None:
file_backend._file_handle.close()
file_backend._file_handle = None

def _audit_lines(self):
lines = []
for file_name in os.listdir(self.temp_dir):
with open(os.path.join(self.temp_dir, file_name)) as audit_file:
lines.extend(json.loads(line) for line in audit_file if line.strip())
return lines

def _assert_not_rpc_callable(self, model, method, args, user):
with self.assertRaises(AccessError) as error:
call_kw(model.with_user(user), method, args, {})
self.assertIn(PRIVATE_ERROR, str(error.exception))


class TestBackendNotRpcCallable(RpcExposureCommon):
def test_write_entry_refused_for_every_backend(self):
"""write_entry is private on every backend, for every user."""
with patch.dict(os.environ, {"OPENSPP_AUDIT_FILE_PATH": self.temp_dir}):
# Point the file backend at this test's directory
self._reset_file_handle()
self.addCleanup(self._reset_file_handle)
for user in (self.portal_user, self.internal_user, self.audit_manager):
for model_name in BACKEND_MODELS:
with self.subTest(model=model_name, user=user.login):
self._assert_not_rpc_callable(self.env[model_name], "write_entry", [dict(SAMPLE_ENTRY)], user)
self.assertEqual(self._audit_lines(), [], "A refused call must not write to the audit file")

def test_is_enabled_refused_for_every_backend(self):
"""is_enabled is private on every backend."""
for model_name in BACKEND_MODELS:
with self.subTest(model=model_name):
self._assert_not_rpc_callable(self.env[model_name], "is_enabled", [], self.internal_user)


class TestRuleLoggingNotRpcCallable(RpcExposureCommon):
def test_log_refused(self):
"""rule.log is private."""
self._assert_not_rpc_callable(
self.env["spp.audit.rule"],
"log",
[[self.partner_rule.id], "write", [{"id": 1, "name": "Old"}], [{"id": 1, "name": "New"}]],
self.audit_manager,
)

def test_log_lifecycle_action_refused(self):
"""log_lifecycle_action is private."""
self._assert_not_rpc_callable(
self.env["spp.audit.rule"],
"log_lifecycle_action",
["res.partner", 1, "approve", {"state": "draft"}, {"state": "approved"}],
self.audit_manager,
)

def test_get_audit_rules_refused(self):
"""get_audit_rules is private on the rule model and on audited models."""
for model_name in ("spp.audit.rule", "res.partner"):
with self.subTest(model=model_name):
self._assert_not_rpc_callable(self.env[model_name], "get_audit_rules", ["write"], self.internal_user)


class TestServerSideLoggingStillWorks(RpcExposureCommon):
def test_audited_write_reaches_database_and_file(self):
"""A real write still produces its log line in the database and the file backend."""
partner = self.env["res.partner"].create({"name": "RPC exposure before"})
log_domain = [("model_id.model", "=", "res.partner"), ("res_id", "=", partner.id), ("method", "=", "write")]
with patch.dict(
os.environ,
{
"OPENSPP_AUDIT_BACKEND_DB": "true",
"OPENSPP_AUDIT_BACKEND_FILE": "true",
"OPENSPP_AUDIT_FILE_PATH": self.temp_dir,
},
):
# Start from a file handle pointing at this test's directory
self._reset_file_handle()
self.addCleanup(self._reset_file_handle)

partner.write({"name": "RPC exposure after"})

self.assertEqual(self.env["spp.audit.log"].search_count(log_domain), 1)
written = [
line for line in self._audit_lines() if line.get("res_id") == partner.id and line.get("method") == "write"
]
self.assertEqual(len(written), 1)
self.assertEqual(written[0]["data"]["new"]["name"], "RPC exposure after")

def test_lifecycle_action_still_logs_server_side(self):
"""Server code can still record a lifecycle action."""
partner = self.env["res.partner"].create({"name": "RPC exposure lifecycle"})
log_domain = [("model_id.model", "=", "res.partner"), ("res_id", "=", partner.id), ("method", "=", "revoke")]
logged = self.env["spp.audit.rule"].log_lifecycle_action(
"res.partner", partner.id, "revoke", {"state": "valid"}, {"state": "revoked"}
)
self.assertTrue(logged)
self.assertEqual(self.env["spp.audit.log"].search_count(log_domain), 1)
Loading