> For the complete documentation index, see [llms.txt](https://docs.openg2p.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.openg2p.org/platform/platform-services/audit-manager/integration-with-registry.md). Agents can also search and read this documentation through its [MCP server](https://docs.openg2p.org/~gitbook/mcp).

# Integration with Registry

How OpenG2P registry services integrate with the Audit Manager. Covers two BFF integrations — Staff Portal API and Partner API — that share the same middleware shape but adapt to their respective auth

This section documents how OpenG2P registry services emit audit events to Audit Manager. Each registry BFF (Backend For Frontend) installs a small `AuditMiddleware` that captures every audit-worthy API call and ships it to Audit Manager as a CloudEvents payload, fire-and-forget.

There is **no shared library** for the middleware — each BFF carries its own copy adapted to its auth model. This is a deliberate choice: the shared `openg2p-fastapi-common` library is consumed by many services across the platform and its release cycle should not be coupled to audit-only changes. Drift risk is accepted in exchange for keeping the common library stable.

## Where the middleware lives

| BFF                    | Repo                                                           | Auth model                                                                      | Audit middleware path                                       |
| ---------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| Staff Portal API       | `openg2p-registry-gen2-apis/openg2p-registry-staff-portal-api` | Keycloak JWT (via `iam_core.user_auth.AuthMiddleware`)                          | `src/openg2p_registry_staff_portal_api/audit_middleware.py` |
| Partner API            | `openg2p-registry-gen2-apis/openg2p-registry-partner-api`      | Signature in request body (verified inside controllers via `keymanager_helper`) | `src/openg2p_registry_partner_api/audit_middleware.py`      |
| Beneficiary Portal API | `openg2p-registry-gen2-apis/openg2p-registry-bene-portal-api`  | (not yet integrated)                                                            | —                                                           |

## Integration approach (summary)

Every BFF integration follows the same shape:

1. **`AuditMiddleware`** is registered in `main.py`. For BFFs that have an upstream auth middleware (e.g. staff-portal-api's `AuthMiddleware`), the audit middleware is added **after** it, so it becomes the OUTERMOST wrapper and sees the populated `request.state.auth` post-handler. For BFFs without an upstream auth middleware (partner-api), the audit middleware is the only middleware.
2. **On every request** the middleware:
   * Calls `call_next` and lets the rest of the stack (auth, handler) run normally. If the inner stack raises, the exception is captured, audited as `outcome=failure / status=500`, then re-raised.
   * Decides whether to emit based on actor presence + outcome:

     | Request kind                                                                                                  | Audited?   |
     | ------------------------------------------------------------------------------------------------------------- | ---------- |
     | Has actor identity (any outcome)                                                                              | YES        |
     | No actor + outcome 2xx (legitimate public call)                                                               | NO         |
     | No actor + outcome non-2xx, `audit_anonymous_failures=true`                                                   | YES (anon) |
     | Health probes / OpenAPI surfaces / OPTIONS preflight                                                          | NO         |
     | Staff Portal API: paths in `audit_skip_paths` (the portal's per-page configuration, theme and language loads) | NO         |
   * Builds a CloudEvents 1.0 envelope and POSTs it to Audit Manager via `asyncio.create_task` — never blocks the response. Errors are logged, never raised to the caller.
3. **Default = disabled.** Both `audit_enabled=true` AND a non-empty `audit_manager_url` must be set; otherwise the middleware is a no-op.

## How the two implementations differ

The interface principles are identical; the implementations diverge where the auth model demands it:

| Principle                          | Staff Portal API                                                                                            | Partner API                                                                                                                           |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Where actor identity comes from    | `request.state.auth` populated by upstream `AuthMiddleware` (Keycloak JWT)                                  | `request.state.audit_actor` set by the controller after parsing the signed envelope (opt-in)                                          |
| Anonymous fallback                 | `actor.type=anonymous`, IP only — used for unauthenticated rejected attempts                                | Same shape, used when controller doesn't enrich (the v1 default state for all calls)                                                  |
| Outcome derivation                 | HTTP status code                                                                                            | HTTP status code, with controller-supplied `request.state.audit_outcome` override (because partner-api wraps errors in 200 responses) |
| 403 recovery                       | Decodes the bearer JWT (known-valid because AuthMiddleware ran) to identify the user that lacked permission | N/A — no JWT, no 403 path                                                                                                             |
| CloudEvents `source`/`type` prefix | `/openg2p/<release>-staff-portal-api` (set by the chart), `org.openg2p.staff_portal.<func>`                 | `/openg2p/<release>-partner-api` (set by the chart), `org.openg2p.partner_api.<func>`                                                 |

**One source per registry.** The chart sets each API's source from the release name, so the registries sharing one Audit Manager are told apart: the Farmer Registry's staff API (release `fr`) sends `/openg2p/fr-staff-portal-api`, the Agents Registry's (release `agents`) `/openg2p/agents-staff-portal-api`, and the Agent Portal API `/openg2p/<release>-agent-portal-api`. Registry Platform versions before this sent `/openg2p/registry-staff-portal-api` for every registry, so their events can be told apart only by matching them to each API's request log.

The full middleware designs are captured on the per-BFF pages above. For the event schema and the HTTP contract the middleware POSTs to, see [Functional Specifications](https://docs.openg2p.org/platform/platform-services/audit-manager/functional-specifications.md) and [API Reference](https://docs.openg2p.org/platform/platform-services/audit-manager/api-reference.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.openg2p.org/platform/platform-services/audit-manager/integration-with-registry.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
