// Copyright (c) 2025-2026 Probo Inc . // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package coredata import ( "context" "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/iam/policy" "go.probo.inc/probo/pkg/page" ) type ( Audit struct { ID gid.GID `db:"id"` Name *string `db:"name"` OrganizationID gid.GID `db:"organization_id"` FrameworkID gid.GID `db:"framework_id"` ReportFileID *gid.GID `db:"report_file_id"` ValidFrom *time.Time `db:"valid_from"` ValidUntil *time.Time `db:"valid_until"` AuditStartDate *time.Time `db:"audit_start_date"` AuditEndDate *time.Time `db:"audit_end_date"` State AuditState `db:"state"` CompliancePortalVisibility CompliancePortalVisibility `db:"trust_center_visibility"` CreatedAt time.Time `db:"created_at"` UpdatedAt time.Time `db:"updated_at"` } Audits []*Audit ) func (a *Audit) CursorKey(field AuditOrderField) page.CursorKey { switch field { case AuditOrderFieldCreatedAt: return page.NewCursorKey(a.ID, a.CreatedAt) case AuditOrderFieldValidFrom: return page.NewCursorKey(a.ID, a.ValidFrom) case AuditOrderFieldValidUntil: return page.NewCursorKey(a.ID, a.ValidUntil) case AuditOrderFieldAuditStartDate: return page.NewCursorKey(a.ID, a.AuditStartDate) case AuditOrderFieldAuditEndDate: return page.NewCursorKey(a.ID, a.AuditEndDate) case AuditOrderFieldState: return page.NewCursorKey(a.ID, a.State) } panic(fmt.Sprintf("unsupported order by: %s", field)) } // AuthorizationAttributes returns the authorization attributes for policy evaluation. func (a *Audit) AuthorizationAttributes( ctx context.Context, conn pg.Querier, resourceIDs []gid.GID, ) (policy.AttributesByID, error) { q := `SELECT id, organization_id FROM audits WHERE id = ANY(@resource_ids::text[])` args := pgx.StrictNamedArgs{ "resource_ids": resourceIDs, } rows, err := conn.Query(ctx, q, args) if err != nil { return nil, fmt.Errorf("cannot query authorization attributes: %w", err) } defer rows.Close() attrsByID := make(policy.AttributesByID) for rows.Next() { var id, organizationID gid.GID if err := rows.Scan(&id, &organizationID); err != nil { return nil, fmt.Errorf("cannot scan authorization attributes: %w", err) } attrsByID[id] = policy.Attributes{ "organization_id": organizationID.String(), } } if err := rows.Err(); err != nil { return nil, fmt.Errorf("cannot iterate authorization attributes: %w", err) } return attrsByID, nil } func (a *Audit) LoadByID( ctx context.Context, conn pg.Querier, scope Scoper, auditID gid.GID, ) error { q := ` SELECT id, name, organization_id, framework_id, report_file_id, valid_from, valid_until, audit_start_date, audit_end_date, state, trust_center_visibility, created_at, updated_at FROM audits WHERE %s AND id = @audit_id LIMIT 1; ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{"audit_id": auditID} maps.Copy(args, scope.SQLArguments()) rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query audit: %w", err) } audit, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Audit]) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return ErrResourceNotFound } return fmt.Errorf("cannot collect audit: %w", err) } *a = audit return nil } func (a *Audits) CountByOrganizationID( ctx context.Context, conn pg.Querier, scope Scoper, organizationID gid.GID, ) (int, error) { q := ` SELECT COUNT(id) FROM audits WHERE %s AND organization_id = @organization_id ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{"organization_id": organizationID} maps.Copy(args, scope.SQLArguments()) row := conn.QueryRow(ctx, q, args) var count int err := row.Scan(&count) if err != nil { return 0, fmt.Errorf("cannot count audits: %w", err) } return count, nil } func (a *Audits) LoadByOrganizationID( ctx context.Context, conn pg.Querier, scope Scoper, organizationID gid.GID, cursor *page.Cursor[AuditOrderField], filter *AuditFilter, ) error { q := ` SELECT id, name, organization_id, framework_id, report_file_id, valid_from, valid_until, audit_start_date, audit_end_date, state, trust_center_visibility, created_at, updated_at FROM audits 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 audits: %w", err) } audits, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Audit]) if err != nil { return fmt.Errorf("cannot collect audits: %w", err) } *a = audits return nil } func (a *Audit) Insert( ctx context.Context, conn pg.Tx, scope Scoper, ) error { q := ` INSERT INTO audits ( id, name, tenant_id, organization_id, framework_id, report_file_id, valid_from, valid_until, audit_start_date, audit_end_date, state, trust_center_visibility, created_at, updated_at ) VALUES ( @id, @name, @tenant_id, @organization_id, @framework_id, @report_file_id, @valid_from, @valid_until, @audit_start_date, @audit_end_date, @state, @trust_center_visibility, @created_at, @updated_at ) ` args := pgx.StrictNamedArgs{ "id": a.ID, "name": a.Name, "tenant_id": scope.GetTenantID(), "organization_id": a.OrganizationID, "framework_id": a.FrameworkID, "report_file_id": a.ReportFileID, "valid_from": a.ValidFrom, "valid_until": a.ValidUntil, "audit_start_date": a.AuditStartDate, "audit_end_date": a.AuditEndDate, "state": a.State, "trust_center_visibility": a.CompliancePortalVisibility, "created_at": a.CreatedAt, "updated_at": a.UpdatedAt, } _, err := conn.Exec(ctx, q, args) if err != nil { return fmt.Errorf("cannot insert audit: %w", err) } return nil } func (a *Audit) Update( ctx context.Context, conn pg.Tx, scope Scoper, ) error { q := ` UPDATE audits SET name = @name, report_file_id = @report_file_id, valid_from = @valid_from, valid_until = @valid_until, audit_start_date = @audit_start_date, audit_end_date = @audit_end_date, state = @state, trust_center_visibility = @trust_center_visibility, updated_at = @updated_at WHERE %s AND id = @id ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{ "id": a.ID, "name": a.Name, "report_file_id": a.ReportFileID, "valid_from": a.ValidFrom, "valid_until": a.ValidUntil, "audit_start_date": a.AuditStartDate, "audit_end_date": a.AuditEndDate, "state": a.State, "trust_center_visibility": a.CompliancePortalVisibility, "updated_at": a.UpdatedAt, } maps.Copy(args, scope.SQLArguments()) _, err := conn.Exec(ctx, q, args) if err != nil { return fmt.Errorf("cannot update audit: %w", err) } return nil } func (a *Audit) Delete( ctx context.Context, conn pg.Tx, scope Scoper, ) error { q := ` DELETE FROM audits WHERE %s AND id = @id ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{"id": a.ID} maps.Copy(args, scope.SQLArguments()) _, err := conn.Exec(ctx, q, args) if err != nil { return fmt.Errorf("cannot delete audit: %w", err) } return nil } func (a *Audits) LoadByControlID( ctx context.Context, conn pg.Querier, scope Scoper, controlID gid.GID, cursor *page.Cursor[AuditOrderField], ) error { q := ` WITH audits_by_control AS ( SELECT a.id, a.tenant_id, a.name, a.organization_id, a.framework_id, a.report_file_id, a.valid_from, a.valid_until, a.audit_start_date, a.audit_end_date, a.state, a.trust_center_visibility, a.created_at, a.updated_at FROM audits a INNER JOIN controls_audits ca ON a.id = ca.audit_id WHERE ca.control_id = @control_id ) SELECT id, name, organization_id, framework_id, report_file_id, valid_from, valid_until, audit_start_date, audit_end_date, state, trust_center_visibility, created_at, updated_at FROM audits_by_control WHERE %s AND %s ` q = fmt.Sprintf(q, scope.SQLFragment(), cursor.SQLFragment()) args := pgx.NamedArgs{"control_id": controlID} maps.Copy(args, scope.SQLArguments()) maps.Copy(args, cursor.SQLArguments()) rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query audits: %w", err) } audits, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Audit]) if err != nil { return fmt.Errorf("cannot collect audits: %w", err) } *a = audits return nil } func (a *Audits) LoadByFindingID( ctx context.Context, conn pg.Querier, scope Scoper, findingID gid.GID, cursor *page.Cursor[AuditOrderField], ) error { q := ` WITH audits_by_finding AS ( SELECT a.id, a.tenant_id, a.name, a.organization_id, a.framework_id, a.report_file_id, a.valid_from, a.valid_until, a.audit_start_date, a.audit_end_date, a.state, a.trust_center_visibility, a.created_at, a.updated_at FROM audits a INNER JOIN findings_audits fa ON a.id = fa.audit_id WHERE fa.finding_id = @finding_id ) SELECT id, name, organization_id, framework_id, report_file_id, valid_from, valid_until, audit_start_date, audit_end_date, state, trust_center_visibility, created_at, updated_at FROM audits_by_finding WHERE %s AND %s ` q = fmt.Sprintf(q, scope.SQLFragment(), cursor.SQLFragment()) args := pgx.StrictNamedArgs{"finding_id": findingID} maps.Copy(args, scope.SQLArguments()) maps.Copy(args, cursor.SQLArguments()) rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query audits: %w", err) } audits, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Audit]) if err != nil { return fmt.Errorf("cannot collect audits: %w", err) } *a = audits return nil } func (a *Audits) CountByControlID( ctx context.Context, conn pg.Querier, scope Scoper, controlID gid.GID, ) (int, error) { q := ` WITH audits_by_control AS ( SELECT a.id, a.tenant_id FROM audits a INNER JOIN controls_audits ca ON a.id = ca.audit_id WHERE ca.control_id = @control_id ) SELECT COUNT(id) FROM audits_by_control WHERE %s ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{"control_id": controlID} maps.Copy(args, scope.SQLArguments()) row := conn.QueryRow(ctx, q, args) var count int err := row.Scan(&count) if err != nil { return 0, fmt.Errorf("cannot count audits: %w", err) } return count, nil } func (a *Audits) CountByFindingID( ctx context.Context, conn pg.Querier, scope Scoper, findingID gid.GID, ) (int, error) { q := ` WITH audits_by_finding AS ( SELECT a.id, a.tenant_id FROM audits a INNER JOIN findings_audits fa ON a.id = fa.audit_id WHERE fa.finding_id = @finding_id ) SELECT COUNT(id) FROM audits_by_finding WHERE %s ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{"finding_id": findingID} maps.Copy(args, scope.SQLArguments()) row := conn.QueryRow(ctx, q, args) var count int err := row.Scan(&count) if err != nil { return 0, fmt.Errorf("cannot count audits: %w", err) } return count, nil } func (a *Audit) LoadByReportFileID( ctx context.Context, conn pg.Querier, scope Scoper, fileID gid.GID, ) error { q := ` SELECT id, name, organization_id, framework_id, report_file_id, valid_from, valid_until, audit_start_date, audit_end_date, state, trust_center_visibility, created_at, updated_at FROM audits WHERE %s AND report_file_id = @report_file_id LIMIT 1; ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{"report_file_id": fileID} maps.Copy(args, scope.SQLArguments()) rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query audit: %w", err) } audit, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Audit]) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return ErrResourceNotFound } return fmt.Errorf("cannot collect audit: %w", err) } *a = audit return nil } func (as *Audits) LoadByReportFileIDs( ctx context.Context, conn pg.Querier, scope Scoper, fileIDs []gid.GID, ) error { q := ` SELECT id, name, organization_id, framework_id, report_file_id, valid_from, valid_until, audit_start_date, audit_end_date, state, trust_center_visibility, created_at, updated_at FROM audits WHERE %s AND report_file_id = ANY(@file_ids) ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{"file_ids": fileIDs} maps.Copy(args, scope.SQLArguments()) rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query audits by report file IDs: %w", err) } audits, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Audit]) if err != nil { return fmt.Errorf("cannot collect audits by report file IDs: %w", err) } *as = audits return nil } func (as *Audits) LoadByReportIDs( ctx context.Context, conn pg.Querier, scope Scoper, reportIDs []gid.GID, ) error { q := ` SELECT id, name, organization_id, framework_id, report_id, valid_from, valid_until, audit_start_date, audit_end_date, state, trust_center_visibility, created_at, updated_at FROM audits WHERE %s AND report_id = ANY(@report_ids) ` q = fmt.Sprintf(q, scope.SQLFragment()) args := pgx.StrictNamedArgs{"report_ids": reportIDs} maps.Copy(args, scope.SQLArguments()) rows, err := conn.Query(ctx, q, args) if err != nil { return fmt.Errorf("cannot query audits by report IDs: %w", err) } audits, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Audit]) if err != nil { return fmt.Errorf("cannot collect audits by report IDs: %w", err) } *as = audits return nil }