Add audit log feature for recording all actions

Adds audit logging that records all authorized actions performed by
users and API keys. The audit log is automatically populated whenever
the authorizer approves an action, and is queryable via GraphQL, MCP,
and CLI interfaces. Permission checks are excluded via a dry-run flag
to avoid phantom entries on page loads.

Signed-off-by: Bryan Frimin <bryan@getprobo.com>
This commit is contained in:
Bryan Frimin
2026-03-20 15:42:11 +01:00
parent 000347b1f9
commit 7b320916af
34 changed files with 2546 additions and 13 deletions

View File

@@ -0,0 +1,70 @@
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"database/sql/driver"
"fmt"
)
type AuditLogActorType string
const (
AuditLogActorTypeUser AuditLogActorType = "USER"
AuditLogActorTypeAPIKey AuditLogActorType = "API_KEY"
AuditLogActorTypeSystem AuditLogActorType = "SYSTEM"
)
func (a AuditLogActorType) String() string {
return string(a)
}
func (a AuditLogActorType) IsValid() bool {
switch a {
case AuditLogActorTypeUser, AuditLogActorTypeAPIKey, AuditLogActorTypeSystem:
return true
}
return false
}
func (a AuditLogActorType) MarshalText() ([]byte, error) {
return []byte(a.String()), nil
}
func (a *AuditLogActorType) UnmarshalText(text []byte) error {
*a = AuditLogActorType(text)
if !a.IsValid() {
return fmt.Errorf("%s is not a valid AuditLogActorType", string(text))
}
return nil
}
func (a *AuditLogActorType) Scan(value any) error {
var s string
switch v := value.(type) {
case string:
s = v
case []byte:
s = string(v)
default:
return fmt.Errorf("unsupported type for AuditLogActorType: %T", value)
}
return a.UnmarshalText([]byte(s))
}
func (a AuditLogActorType) Value() (driver.Value, error) {
return a.String(), nil
}

View File

@@ -0,0 +1,243 @@
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"time"
"github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/page"
)
type (
AuditLogEntry struct {
ID gid.GID `db:"id"`
OrganizationID gid.GID `db:"organization_id"`
ActorID gid.GID `db:"actor_id"`
ActorType AuditLogActorType `db:"actor_type"`
Action string `db:"action"`
ResourceType string `db:"resource_type"`
ResourceID gid.GID `db:"resource_id"`
Metadata json.RawMessage `db:"metadata"`
CreatedAt time.Time `db:"created_at"`
}
AuditLogEntries []*AuditLogEntry
)
func (e AuditLogEntry) CursorKey(orderBy AuditLogEntryOrderField) page.CursorKey {
switch orderBy {
case AuditLogEntryOrderFieldCreatedAt:
return page.NewCursorKey(e.ID, e.CreatedAt)
}
panic(fmt.Sprintf("unsupported order by: %s", orderBy))
}
func (e *AuditLogEntry) AuthorizationAttributes(ctx context.Context, conn pg.Conn) (map[string]string, error) {
q := `SELECT organization_id FROM audit_log_entries WHERE id = $1 LIMIT 1;`
var organizationID gid.GID
if err := conn.QueryRow(ctx, q, e.ID).Scan(&organizationID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
}
return nil, fmt.Errorf("cannot query audit log entry authorization attributes: %w", err)
}
return map[string]string{"organization_id": organizationID.String()}, nil
}
func (e *AuditLogEntry) Insert(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
INSERT INTO audit_log_entries (
id,
tenant_id,
organization_id,
actor_id,
actor_type,
action,
resource_type,
resource_id,
metadata,
created_at
)
VALUES (
@id,
@tenant_id,
@organization_id,
@actor_id,
@actor_type,
@action,
@resource_type,
@resource_id,
@metadata,
@created_at
)
`
args := pgx.StrictNamedArgs{
"id": e.ID,
"tenant_id": scope.GetTenantID(),
"organization_id": e.OrganizationID,
"actor_id": e.ActorID,
"actor_type": e.ActorType,
"action": e.Action,
"resource_type": e.ResourceType,
"resource_id": e.ResourceID,
"metadata": e.Metadata,
"created_at": e.CreatedAt,
}
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot insert audit log entry: %w", err)
}
return nil
}
func (e *AuditLogEntry) LoadByID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
id gid.GID,
) error {
q := `
SELECT
id,
organization_id,
actor_id,
actor_type,
action,
resource_type,
resource_id,
metadata,
created_at
FROM
audit_log_entries
WHERE
%s
AND id = @id
LIMIT 1;
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"id": id}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query audit log entry: %w", err)
}
entry, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[AuditLogEntry])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return ErrResourceNotFound
}
return fmt.Errorf("cannot collect audit log entry: %w", err)
}
*e = entry
return nil
}
func (es *AuditLogEntries) LoadAllByOrganizationID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
cursor *page.Cursor[AuditLogEntryOrderField],
filter *AuditLogEntryFilter,
) error {
q := `
SELECT
id,
organization_id,
actor_id,
actor_type,
action,
resource_type,
resource_id,
metadata,
created_at
FROM
audit_log_entries
WHERE
%s
AND organization_id = @organization_id
AND %s
AND %s
`
q = fmt.Sprintf(q, scope.SQLFragment(), filter.SQLFragment(), cursor.SQLFragment())
args := pgx.StrictNamedArgs{"organization_id": organizationID}
maps.Copy(args, scope.SQLArguments())
maps.Copy(args, filter.SQLArguments())
maps.Copy(args, cursor.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query audit log entries: %w", err)
}
entries, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[AuditLogEntry])
if err != nil {
return fmt.Errorf("cannot collect audit log entries: %w", err)
}
*es = entries
return nil
}
func (es *AuditLogEntries) CountByOrganizationID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
filter *AuditLogEntryFilter,
) (int, error) {
q := `
SELECT COUNT(id)
FROM audit_log_entries
WHERE %s
AND organization_id = @organization_id
AND %s
`
q = fmt.Sprintf(q, scope.SQLFragment(), filter.SQLFragment())
args := pgx.StrictNamedArgs{"organization_id": organizationID}
maps.Copy(args, scope.SQLArguments())
maps.Copy(args, filter.SQLArguments())
var count int
if err := conn.QueryRow(ctx, q, args).Scan(&count); err != nil {
return 0, fmt.Errorf("cannot count audit log entries: %w", err)
}
return count, nil
}

View File

@@ -0,0 +1,107 @@
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"github.com/jackc/pgx/v5"
"go.probo.inc/probo/pkg/gid"
)
type AuditLogEntryFilter struct {
action *string
actorID *gid.GID
resourceType *string
resourceID *gid.GID
}
func NewAuditLogEntryFilter() *AuditLogEntryFilter {
return &AuditLogEntryFilter{}
}
func (f *AuditLogEntryFilter) WithAction(action string) *AuditLogEntryFilter {
f.action = &action
return f
}
func (f *AuditLogEntryFilter) WithActorID(actorID gid.GID) *AuditLogEntryFilter {
f.actorID = &actorID
return f
}
func (f *AuditLogEntryFilter) WithResourceType(resourceType string) *AuditLogEntryFilter {
f.resourceType = &resourceType
return f
}
func (f *AuditLogEntryFilter) WithResourceID(resourceID gid.GID) *AuditLogEntryFilter {
f.resourceID = &resourceID
return f
}
func (f *AuditLogEntryFilter) SQLFragment() string {
return `
(
CASE
WHEN @filter_action::text IS NOT NULL THEN
action = @filter_action::text
ELSE TRUE
END
AND
CASE
WHEN @filter_actor_id::text IS NOT NULL THEN
actor_id = @filter_actor_id::text
ELSE TRUE
END
AND
CASE
WHEN @filter_resource_type::text IS NOT NULL THEN
resource_type = @filter_resource_type::text
ELSE TRUE
END
AND
CASE
WHEN @filter_resource_id::text IS NOT NULL THEN
resource_id = @filter_resource_id::text
ELSE TRUE
END
)`
}
func (f *AuditLogEntryFilter) SQLArguments() pgx.StrictNamedArgs {
args := pgx.StrictNamedArgs{
"filter_action": nil,
"filter_actor_id": nil,
"filter_resource_type": nil,
"filter_resource_id": nil,
}
if f.action != nil {
args["filter_action"] = *f.action
}
if f.actorID != nil {
args["filter_actor_id"] = *f.actorID
}
if f.resourceType != nil {
args["filter_resource_type"] = *f.resourceType
}
if f.resourceID != nil {
args["filter_resource_id"] = *f.resourceID
}
return args
}

View File

@@ -0,0 +1,57 @@
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"fmt"
)
type AuditLogEntryOrderField string
const (
AuditLogEntryOrderFieldCreatedAt AuditLogEntryOrderField = "CREATED_AT"
)
func (p AuditLogEntryOrderField) Column() string {
switch p {
case AuditLogEntryOrderFieldCreatedAt:
return "created_at"
}
panic(fmt.Sprintf("unsupported order by: %s", p))
}
func (p AuditLogEntryOrderField) String() string {
return string(p)
}
func (p AuditLogEntryOrderField) IsValid() bool {
switch p {
case AuditLogEntryOrderFieldCreatedAt:
return true
}
return false
}
func (p AuditLogEntryOrderField) MarshalText() ([]byte, error) {
return []byte(p.String()), nil
}
func (p *AuditLogEntryOrderField) UnmarshalText(text []byte) error {
*p = AuditLogEntryOrderField(text)
if !p.IsValid() {
return fmt.Errorf("%s is not a valid AuditLogEntryOrderField", string(text))
}
return nil
}

View File

@@ -0,0 +1,121 @@
// Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
// ResourceTypeName returns a human-readable name for an entity type.
func ResourceTypeName(entityType uint16) string {
switch entityType {
case OrganizationEntityType:
return "Organization"
case FrameworkEntityType:
return "Framework"
case MeasureEntityType:
return "Measure"
case TaskEntityType:
return "Task"
case EvidenceEntityType:
return "Evidence"
case ConnectorEntityType:
return "Connector"
case VendorRiskAssessmentEntityType:
return "VendorRiskAssessment"
case VendorEntityType:
return "Vendor"
case VendorComplianceReportEntityType:
return "VendorComplianceReport"
case DocumentEntityType:
return "Document"
case IdentityEntityType:
return "Identity"
case ControlEntityType:
return "Control"
case RiskEntityType:
return "Risk"
case DocumentVersionEntityType:
return "DocumentVersion"
case DocumentVersionSignatureEntityType:
return "DocumentVersionSignature"
case AssetEntityType:
return "Asset"
case DatumEntityType:
return "Datum"
case AuditEntityType:
return "Audit"
case ReportEntityType:
return "Report"
case TrustCenterEntityType:
return "TrustCenter"
case TrustCenterAccessEntityType:
return "TrustCenterAccess"
case VendorBusinessAssociateAgreementEntityType:
return "VendorBusinessAssociateAgreement"
case FileEntityType:
return "File"
case VendorContactEntityType:
return "VendorContact"
case VendorDataPrivacyAgreementEntityType:
return "VendorDataPrivacyAgreement"
case FindingEntityType:
return "Finding"
case ObligationEntityType:
return "Obligation"
case VendorServiceEntityType:
return "VendorService"
case SnapshotEntityType:
return "Snapshot"
case ProcessingActivityEntityType:
return "ProcessingActivity"
case TrustCenterReferenceEntityType:
return "TrustCenterReference"
case TrustCenterDocumentAccessEntityType:
return "TrustCenterDocumentAccess"
case CustomDomainEntityType:
return "CustomDomain"
case InvitationEntityType:
return "Invitation"
case MembershipEntityType:
return "Membership"
case TrustCenterFileEntityType:
return "TrustCenterFile"
case MeetingEntityType:
return "Meeting"
case DataProtectionImpactAssessmentEntityType:
return "DataProtectionImpactAssessment"
case TransferImpactAssessmentEntityType:
return "TransferImpactAssessment"
case RightsRequestEntityType:
return "RightsRequest"
case StateOfApplicabilityEntityType:
return "StateOfApplicability"
case ApplicabilityStatementEntityType:
return "ApplicabilityStatement"
case WebhookSubscriptionEntityType:
return "WebhookSubscription"
case ComplianceFrameworkEntityType:
return "ComplianceFramework"
case ComplianceExternalURLEntityType:
return "ComplianceExternalURL"
case MailingListEntityType:
return "MailingList"
case MailingListSubscriberEntityType:
return "MailingListSubscriber"
case MailingListUpdateEntityType:
return "MailingListUpdate"
case AuditLogEntryEntityType:
return "AuditLogEntry"
default:
return "Unknown"
}
}

View File

@@ -91,6 +91,7 @@ const (
MailingListSubscriberEntityType uint16 = 65
MailingListUpdateEntityType uint16 = 66
FindingEntityType uint16 = 67
AuditLogEntryEntityType uint16 = 68
)
func NewEntityFromID(id gid.GID) (any, bool) {
@@ -223,6 +224,8 @@ func NewEntityFromID(id gid.GID) (any, bool) {
return &MailingListSubscriber{ID: id}, true
case MailingListUpdateEntityType:
return &MailingListUpdate{ID: id}, true
case AuditLogEntryEntityType:
return &AuditLogEntry{ID: id}, true
default:
return nil, false
}

View File

@@ -0,0 +1,31 @@
-- Copyright (c) 2026 Probo Inc <hello@getprobo.com>.
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-- PERFORMANCE OF THIS SOFTWARE.
CREATE TABLE audit_log_entries (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
organization_id TEXT NOT NULL REFERENCES organizations(id),
actor_id TEXT NOT NULL,
actor_type TEXT NOT NULL,
action TEXT NOT NULL,
resource_type TEXT NOT NULL,
resource_id TEXT NOT NULL,
metadata JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX idx_audit_log_entries_organization_id ON audit_log_entries (organization_id);
CREATE INDEX idx_audit_log_entries_actor_id ON audit_log_entries (actor_id);
CREATE INDEX idx_audit_log_entries_action ON audit_log_entries (action);
CREATE INDEX idx_audit_log_entries_created_at ON audit_log_entries (created_at);