Switch AuthorizationAttributes to batch and add AuthorizeBatch

Change AuthorizationAttributer.AuthorizationAttributes to take a slice
of resource ids and return policy.AttributesByID, so a single SQL
round-trip can load condition attributes for a whole batch. All
coredata implementations are migrated to a single
`WHERE id = ANY(@resource_ids::text[])` query that returns only the
rows it finds.

Authorizer gains:
  - AuthorizeBatch — all-or-nothing across a homogeneous (same entity
    type, same organization) resource set; rejects mixed entity types,
    mixed organizations, and empty batches with structured errors.
  - AuthorizeMulti — heterogeneous evaluation that returns one error
    per item and writes audit log entries in a single bulk insert.

The single-resource Authorize is rewired to delegate to AuthorizeBatch
so all paths share the same condition evaluation and audit logging.
recordAuditLog is split into buildAuditLogEntry plus a batch insert.

Tests cover the new batch and multi paths, mixed/empty/unsupported
resource cases, audit log batching, and dry-run behaviour.

Signed-off-by: Bryan Frimin <bryan@probo.com>
This commit is contained in:
Bryan Frimin
2026-05-23 11:26:24 -07:00
parent 2d08dfbe2f
commit b39d880c0f
82 changed files with 4942 additions and 986 deletions

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -69,19 +70,42 @@ func (e AccessEntry) CursorKey(orderBy AccessEntryOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (e *AccessEntry) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (e *AccessEntry) AuthorizationAttributes(
q := `SELECT organization_id FROM access_entries WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM access_entries WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, e.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query access entry authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (e *AccessEntry) LoadByID( func (e *AccessEntry) LoadByID(

View File

@@ -16,7 +16,6 @@ package coredata
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"maps" "maps"
"time" "time"
@@ -24,6 +23,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
) )
type ( type (
@@ -92,19 +92,39 @@ INSERT INTO access_entry_decision_history (
func (h *AccessEntryDecisionHistory) AuthorizationAttributes( func (h *AccessEntryDecisionHistory) AuthorizationAttributes(
ctx context.Context, ctx context.Context,
conn pg.Querier, conn pg.Querier,
) (map[string]string, error) { resourceIDs []gid.GID,
q := `SELECT organization_id FROM access_entry_decision_history WHERE id = $1 LIMIT 1;` ) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM access_entry_decision_history WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, h.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot load authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (hs *AccessEntryDecisionHistories) LoadByEntryID( func (hs *AccessEntryDecisionHistories) LoadByEntryID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,19 +54,42 @@ func (c AccessReviewCampaign) CursorKey(orderBy AccessReviewCampaignOrderField)
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (c *AccessReviewCampaign) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (c *AccessReviewCampaign) AuthorizationAttributes(
q := `SELECT organization_id FROM access_review_campaigns WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM access_review_campaigns WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, c.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query access review campaign authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (c *AccessReviewCampaign) LoadByID( func (c *AccessReviewCampaign) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -52,19 +53,42 @@ func (as AccessSource) CursorKey(orderBy AccessSourceOrderField) page.CursorKey
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (as *AccessSource) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (as *AccessSource) AuthorizationAttributes(
q := `SELECT organization_id FROM access_sources WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM access_sources WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, as.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query access source authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (as *AccessSource) LoadByID( func (as *AccessSource) LoadByID(

View File

@@ -27,6 +27,7 @@ import (
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/agent" "go.probo.inc/probo/pkg/agent"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -121,30 +122,42 @@ func (e AgentRun) CursorKey(orderBy AgentRunOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (e *AgentRun) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (e *AgentRun) AuthorizationAttributes(
q := `SELECT organization_id FROM agent_runs WHERE id = @id LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM agent_runs WHERE id = ANY(@resource_ids::text[])`
args := pgx.StrictNamedArgs{"id": e.ID.String()} args := pgx.StrictNamedArgs{
"resource_ids": resourceIDs,
}
rows, err := conn.Query(ctx, q, args) rows, err := conn.Query(ctx, q, args)
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot query agent run authorization attributes: %w", err) return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
type row struct { defer rows.Close()
OrganizationID gid.GID `db:"organization_id"`
}
r, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[row]) attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if err != nil { if err != nil {
if errors.Is(err, pgx.ErrNoRows) { return nil, fmt.Errorf("cannot scan authorization attributes: %w", err)
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot load agent run authorization attributes: %w", err) attrsByID[id] = policy.Attributes{
"organization_id": organizationID.String(),
}
} }
return map[string]string{"organization_id": r.OrganizationID.String()}, nil if err := rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (e *AgentRun) LoadByID( func (e *AgentRun) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -57,19 +58,42 @@ func (s ApplicabilityStatement) CursorKey(orderBy ApplicabilityStatementOrderFie
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (s *ApplicabilityStatement) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *ApplicabilityStatement) AuthorizationAttributes(
q := `SELECT organization_id FROM applicability_statements WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM applicability_statements WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query applicability statement authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (sac *ApplicabilityStatement) LoadByID( func (sac *ApplicabilityStatement) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -55,19 +56,42 @@ func (a *Asset) CursorKey(field AssetOrderField) page.CursorKey {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (a *Asset) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (a *Asset) AuthorizationAttributes(
q := `SELECT organization_id FROM assets WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM assets WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, a.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query asset authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 *Asset) LoadByID( func (a *Asset) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -61,19 +62,42 @@ func (a *Audit) CursorKey(field AuditOrderField) page.CursorKey {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (a *Audit) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (a *Audit) AuthorizationAttributes(
q := `SELECT organization_id FROM audits WHERE id = $1 LIMIT 1;` 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[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, a.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query audit authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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( func (a *Audit) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,19 +54,42 @@ func (e AuditLogEntry) CursorKey(orderBy AuditLogEntryOrderField) page.CursorKey
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (e *AuditLogEntry) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (e *AuditLogEntry) AuthorizationAttributes(
q := `SELECT organization_id FROM audit_log_entries WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM audit_log_entries WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, e.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query audit log entry authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (e *AuditLogEntry) Insert( func (e *AuditLogEntry) Insert(
@@ -121,6 +145,61 @@ VALUES (
return nil return nil
} }
// BulkInsert writes all entries to audit_log_entries in a single PostgreSQL
// COPY operation. Used by the authorizer's batch path to fold N per-resource
// INSERTs into a single round trip.
func (es AuditLogEntries) BulkInsert(
ctx context.Context,
conn pg.Querier,
scope Scoper,
) error {
if len(es) == 0 {
return nil
}
rows := make([][]any, 0, len(es))
for _, e := range es {
rows = append(
rows,
[]any{
e.ID,
scope.GetTenantID(),
e.OrganizationID,
e.ActorID,
e.ActorType,
e.Action,
e.ResourceType,
e.ResourceID,
e.Metadata,
e.CreatedAt,
},
)
}
_, err := conn.CopyFrom(
ctx,
pgx.Identifier{"audit_log_entries"},
[]string{
"id",
"tenant_id",
"organization_id",
"actor_id",
"actor_type",
"action",
"resource_type",
"resource_id",
"metadata",
"created_at",
},
pgx.CopyFromRows(rows),
)
if err != nil {
return fmt.Errorf("cannot bulk insert audit log entries: %w", err)
}
return nil
}
func (e *AuditLogEntry) LoadByID( func (e *AuditLogEntry) LoadByID(
ctx context.Context, ctx context.Context,
conn pg.Querier, conn pg.Querier,

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,19 +54,42 @@ func (c ComplianceExternalURL) CursorKey(orderBy ComplianceExternalURLOrderField
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (c *ComplianceExternalURL) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (c *ComplianceExternalURL) AuthorizationAttributes(
q := `SELECT organization_id FROM compliance_external_urls WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM compliance_external_urls WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, c.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query compliance external URL authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (c *ComplianceExternalURL) LoadByID( func (c *ComplianceExternalURL) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -56,19 +57,42 @@ func (c ComplianceFramework) CursorKey(orderBy ComplianceFrameworkOrderField) pa
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (c *ComplianceFramework) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (c *ComplianceFramework) AuthorizationAttributes(
q := `SELECT organization_id FROM compliance_frameworks WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM compliance_frameworks WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, c.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query compliance framework authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (c *ComplianceFramework) LoadByID( func (c *ComplianceFramework) LoadByID(

View File

@@ -28,6 +28,7 @@ import (
"go.probo.inc/probo/pkg/connector" "go.probo.inc/probo/pkg/connector"
"go.probo.inc/probo/pkg/crypto/cipher" "go.probo.inc/probo/pkg/crypto/cipher"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -85,19 +86,42 @@ func (c *Connector) CursorKey(orderBy ConnectorOrderField) page.CursorKey {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (c *Connector) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (c *Connector) AuthorizationAttributes(
q := `SELECT organization_id FROM connectors WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM connectors WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, c.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query connector authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (c *Connectors) LoadAllByOrganizationIDProtocolAndProvider( func (c *Connectors) LoadAllByOrganizationIDProtocolAndProvider(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -58,19 +59,42 @@ func (c Control) CursorKey(orderBy ControlOrderField) page.CursorKey {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (c *Control) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (c *Control) AuthorizationAttributes(
q := `SELECT organization_id FROM controls WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM controls WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, c.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query control authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (c *Controls) CountByDocumentID( func (c *Controls) CountByDocumentID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -57,19 +58,42 @@ func (b *CookieBanner) CursorKey(field CookieBannerOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (b *CookieBanner) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (b *CookieBanner) AuthorizationAttributes(
q := `SELECT organization_id FROM cookie_banners WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM cookie_banners WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, b.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query cookie banner authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (b *CookieBanner) LoadByID( func (b *CookieBanner) LoadByID(

View File

@@ -26,6 +26,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
) )
type ( type (
@@ -42,19 +43,42 @@ type (
CookieBannerTranslations []*CookieBannerTranslation CookieBannerTranslations []*CookieBannerTranslation
) )
func (t *CookieBannerTranslation) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (t *CookieBannerTranslation) AuthorizationAttributes(
q := `SELECT organization_id FROM cookie_banner_translations WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM cookie_banner_translations WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, t.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query cookie banner translation authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (t *CookieBannerTranslation) LoadByID( func (t *CookieBannerTranslation) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -80,19 +81,42 @@ func (v *CookieBannerVersion) CursorKey(field CookieBannerVersionOrderField) pag
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (v *CookieBannerVersion) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (v *CookieBannerVersion) AuthorizationAttributes(
q := `SELECT organization_id FROM cookie_banner_versions WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM cookie_banner_versions WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, v.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query cookie banner version authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (v *CookieBannerVersion) GetSnapshot() (CookieBannerVersionSnapshot, error) { func (v *CookieBannerVersion) GetSnapshot() (CookieBannerVersionSnapshot, error) {

View File

@@ -26,6 +26,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -82,19 +83,42 @@ func (c *CookieCategory) CursorKey(field CookieCategoryOrderField) page.CursorKe
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (c *CookieCategory) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (c *CookieCategory) AuthorizationAttributes(
q := `SELECT organization_id FROM cookie_categories WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM cookie_categories WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, c.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query cookie category authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (c *CookieCategory) LoadByID( func (c *CookieCategory) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -58,19 +59,42 @@ func (r *CookieConsentRecord) CursorKey(field CookieConsentRecordOrderField) pag
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (r *CookieConsentRecord) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (r *CookieConsentRecord) AuthorizationAttributes(
q := `SELECT organization_id FROM cookie_consent_records WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM cookie_consent_records WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, r.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query consent record authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (r *CookieConsentRecords) LoadByCookieBannerID( func (r *CookieConsentRecords) LoadByCookieBannerID(

View File

@@ -27,6 +27,7 @@ import (
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/crypto/cipher" "go.probo.inc/probo/pkg/crypto/cipher"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -68,19 +69,42 @@ func NewCustomDomain(tenantID gid.TenantID, domain string) *CustomDomain {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (cd *CustomDomain) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (cd *CustomDomain) AuthorizationAttributes(
q := `SELECT organization_id FROM custom_domains WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM custom_domains WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, cd.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query custom domain authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (cd *CustomDomain) CursorKey(field CustomDomainOrderField) page.CursorKey { func (cd *CustomDomain) CursorKey(field CustomDomainOrderField) page.CursorKey {

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -163,19 +164,42 @@ func (dpia *DataProtectionImpactAssessment) CursorKey(field DataProtectionImpact
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (dpia *DataProtectionImpactAssessment) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (dpia *DataProtectionImpactAssessment) AuthorizationAttributes(
q := `SELECT organization_id FROM processing_activity_data_protection_impact_assessments WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM processing_activity_data_protection_impact_assessments WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, dpia.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query data protection impact assessment authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (dpias *DataProtectionImpactAssessments) CountByOrganizationID( func (dpias *DataProtectionImpactAssessments) CountByOrganizationID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -55,19 +56,42 @@ func (d *Datum) CursorKey(field DatumOrderField) page.CursorKey {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (d *Datum) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (d *Datum) AuthorizationAttributes(
q := `SELECT organization_id FROM data WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM data WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, d.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query datum authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (d *Datum) LoadByID( func (d *Datum) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -65,26 +66,42 @@ func (p Document) CursorKey(orderBy DocumentOrderField) page.CursorKey {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (d *Document) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (d *Document) AuthorizationAttributes(
q := ` ctx context.Context,
SELECT organization_id conn pg.Querier,
FROM documents resourceIDs []gid.GID,
WHERE id = $1 ) (policy.AttributesByID, error) {
LIMIT 1; q := `SELECT id, organization_id FROM documents WHERE id = ANY(@resource_ids::text[])`
`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, d.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query document authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{ defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if err != nil {
return nil, fmt.Errorf("cannot scan authorization attributes: %w", err)
}
attrsByID[id] = policy.Attributes{
"organization_id": organizationID.String(), "organization_id": organizationID.String(),
}, nil }
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (p *Document) LoadByID( func (p *Document) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,27 +54,42 @@ type (
) )
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (dv *DocumentVersion) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (dv *DocumentVersion) AuthorizationAttributes(
q := ` ctx context.Context,
SELECT organization_id conn pg.Querier,
FROM document_versions resourceIDs []gid.GID,
WHERE id = $1 ) (policy.AttributesByID, error) {
LIMIT 1; q := `SELECT id, organization_id FROM document_versions WHERE id = ANY(@resource_ids::text[])`
`
var organizationID gid.GID args := pgx.StrictNamedArgs{
"resource_ids": resourceIDs,
if err := conn.QueryRow(ctx, q, dv.ID).Scan(&organizationID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query document version authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{ defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if err != nil {
return nil, fmt.Errorf("cannot scan authorization attributes: %w", err)
}
attrsByID[id] = policy.Attributes{
"organization_id": organizationID.String(), "organization_id": organizationID.String(),
}, nil }
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (dv *DocumentVersions) LoadByDocumentID( func (dv *DocumentVersions) LoadByDocumentID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -54,19 +55,42 @@ func (d DocumentVersionApprovalDecision) CursorKey(orderBy DocumentVersionApprov
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (d *DocumentVersionApprovalDecision) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (d *DocumentVersionApprovalDecision) AuthorizationAttributes(
q := `SELECT organization_id FROM document_version_approval_decisions WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM document_version_approval_decisions WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, d.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query document version approval decision authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (d *DocumentVersionApprovalDecision) LoadByID( func (d *DocumentVersionApprovalDecision) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -50,19 +51,42 @@ func (q DocumentVersionApprovalQuorum) CursorKey(orderBy DocumentVersionApproval
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (q *DocumentVersionApprovalQuorum) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (q *DocumentVersionApprovalQuorum) AuthorizationAttributes(
query := `SELECT organization_id FROM document_version_approval_quorums WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
query := `SELECT id, organization_id FROM document_version_approval_quorums WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, query, q.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query approval quorum authorization attributes: %w", err) rows, err := conn.Query(ctx, query, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (q *DocumentVersionApprovalQuorum) LoadByID( func (q *DocumentVersionApprovalQuorum) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -64,19 +65,42 @@ func (pvs DocumentVersionSignature) CursorKey(orderBy DocumentVersionSignatureOr
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (dvs *DocumentVersionSignature) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (dvs *DocumentVersionSignature) AuthorizationAttributes(
q := `SELECT organization_id FROM document_version_signatures WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM document_version_signatures WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, dvs.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query document version signature authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (pvs *DocumentVersionSignature) LoadByDocumentVersionIDAndSignatory( func (pvs *DocumentVersionSignature) LoadByDocumentVersionIDAndSignatory(

View File

@@ -23,6 +23,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
) )
@@ -65,8 +66,46 @@ var (
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
// Email is identity-scoped (not org-scoped), so it returns an empty map. // Email is identity-scoped (not org-scoped), so it returns an empty map.
func (e *Email) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (e *Email) AuthorizationAttributes(
return map[string]string{}, nil ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `
SELECT
id
FROM
emails
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 email authorization attributes: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var id gid.GID
err = rows.Scan(&id)
if err != nil {
return nil, fmt.Errorf("cannot scan email authorization attributes: %w", err)
}
attrsByID[id] = policy.Attributes{}
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate email authorization attributes: %w", err)
}
return attrsByID, nil
} }
func NewEmail( func NewEmail(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -59,19 +60,42 @@ func (e Evidence) CursorKey(orderBy EvidenceOrderField) page.CursorKey {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (e *Evidence) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (e *Evidence) AuthorizationAttributes(
q := `SELECT organization_id FROM evidences WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM evidences WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, e.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query evidence authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (e Evidence) Upsert( func (e Evidence) Upsert(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
) )
@@ -63,19 +64,42 @@ var (
) )
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (ej *ExportJob) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (ej *ExportJob) AuthorizationAttributes(
q := `SELECT organization_id FROM export_jobs WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM export_jobs WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, ej.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query export job authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (ej *ExportJob) Insert( func (ej *ExportJob) Insert(

View File

@@ -26,6 +26,7 @@ import (
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/filemanager" "go.probo.inc/probo/pkg/filemanager"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
) )
type ( type (
@@ -65,19 +66,42 @@ func (f *File) GetMimeType() string {
var _ filemanager.File = (*File)(nil) var _ filemanager.File = (*File)(nil)
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (f *File) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (f *File) AuthorizationAttributes(
q := `SELECT organization_id FROM files WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM files WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, f.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query file authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (f *File) LoadByID( func (f *File) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -72,19 +73,42 @@ func (f *Finding) CursorKey(field FindingOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (f *Finding) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (f *Finding) AuthorizationAttributes(
q := `SELECT organization_id FROM findings WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM findings WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, f.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query finding authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (f *Finding) LoadByID( func (f *Finding) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,20 +54,49 @@ func (f *Framework) CursorKey(orderBy FrameworkOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. func (f *Framework) AuthorizationAttributes(
func (f *Framework) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { ctx context.Context,
q := `SELECT organization_id FROM frameworks WHERE id = $1 LIMIT 1;` conn pg.Querier,
frameworkIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `
SELECT
id,
organization_id
FROM
frameworks
WHERE
id = ANY(@framework_ids::text[])
`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, f.ID).Scan(&organizationID); err != nil { "framework_ids": frameworkIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query framework authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query framework authorization attributes batch: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var (
frameworkID gid.GID
organizationID gid.GID
)
if err := rows.Scan(&frameworkID, &organizationID); err != nil {
return nil, fmt.Errorf("cannot scan framework authorization attributes batch: %w", err)
}
attrsByID[frameworkID] = policy.Attributes{
"organization_id": organizationID.String(),
}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate framework authorization attributes batch: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil return attrsByID, nil
} }
func (f *Frameworks) CountByOrganizationID( func (f *Frameworks) CountByOrganizationID(
@@ -100,6 +130,22 @@ WHERE
return count, nil return count, nil
} }
func uniqueGIDs(values []gid.GID) []gid.GID {
set := make(map[gid.GID]struct{}, len(values))
unique := make([]gid.GID, 0, len(values))
for _, value := range values {
if _, ok := set[value]; ok {
continue
}
set[value] = struct{}{}
unique = append(unique, value)
}
return unique
}
func (f *Frameworks) LoadByOrganizationID( func (f *Frameworks) LoadByOrganizationID(
ctx context.Context, ctx context.Context,
conn pg.Querier, conn pg.Querier,

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -143,7 +144,11 @@ LIMIT 1;
// AuthorizationAttributes loads the minimal authorization attributes for policy condition evaluation. // AuthorizationAttributes loads the minimal authorization attributes for policy condition evaluation.
// It is intentionally lightweight and does not populate the Identity struct. // It is intentionally lightweight and does not populate the Identity struct.
func (i *Identity) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (i *Identity) AuthorizationAttributes(
ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := ` q := `
SELECT SELECT
id, id,
@@ -151,25 +156,41 @@ SELECT
FROM FROM
identities identities
WHERE WHERE
id = $1 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 identity authorization attributes: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var ( var (
id gid.GID id gid.GID
emailAddress string emailAddress string
) )
if err := conn.QueryRow(ctx, q, i.ID).Scan(&id, &emailAddress); err != nil {
if errors.Is(err, pgx.ErrNoRows) { if err := rows.Scan(&id, &emailAddress); err != nil {
return nil, ErrResourceNotFound return nil, fmt.Errorf("cannot scan identity authorization attributes: %w", err)
} }
return nil, fmt.Errorf("cannot query identity iam attributes: %w", err) attrsByID[id] = policy.Attributes{
}
return map[string]string{
"identity_id": id.String(), "identity_id": id.String(),
"email": emailAddress, "email": emailAddress,
}, nil }
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate identity authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (i *Identity) Insert( func (i *Identity) Insert(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -142,34 +143,56 @@ WHERE
// AuthorizationAttributes loads the minimal authorization attributes for policy condition evaluation. // AuthorizationAttributes loads the minimal authorization attributes for policy condition evaluation.
// It is intentionally lightweight and does not populate the Invitation struct. // It is intentionally lightweight and does not populate the Invitation struct.
func (i *Invitation) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (i *Invitation) AuthorizationAttributes(
ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := ` q := `
SELECT SELECT
email, organization_id id,
email,
organization_id
FROM FROM
iam_invitations iam_invitations
WHERE WHERE
id = $1 id = ANY(@resource_ids::text[])
LIMIT 1;
` `
args := pgx.StrictNamedArgs{
"resource_ids": resourceIDs,
}
rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query invitation authorization attributes: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var ( var (
id gid.GID
email string email string
organizationID gid.GID organizationID gid.GID
) )
if err := conn.QueryRow(ctx, q, i.ID).Scan(&email, &organizationID); err != nil { err = rows.Scan(&id, &email, &organizationID)
if errors.Is(err, pgx.ErrNoRows) { if err != nil {
return nil, ErrResourceNotFound return nil, fmt.Errorf("cannot scan invitation authorization attributes: %w", err)
} }
return nil, fmt.Errorf("cannot query invitation iam attributes: %w", err) attrsByID[id] = policy.Attributes{
}
return map[string]string{
"email": email, "email": email,
"organization_id": organizationID.String(), "organization_id": organizationID.String(),
}, nil }
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate invitation authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (i *Invitation) Update(ctx context.Context, conn pg.Tx, scope Scoper) error { func (i *Invitation) Update(ctx context.Context, conn pg.Tx, scope Scoper) error {

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
) )
@@ -35,19 +36,42 @@ type MailingList struct {
UpdatedAt time.Time `db:"updated_at"` UpdatedAt time.Time `db:"updated_at"`
} }
func (ml *MailingList) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (ml *MailingList) AuthorizationAttributes(
q := `SELECT organization_id FROM mailing_lists WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM mailing_lists WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, ml.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query mailing list authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (ml *MailingList) LoadByID( func (ml *MailingList) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -44,19 +45,42 @@ type (
MailingListSubscribers []*MailingListSubscriber MailingListSubscribers []*MailingListSubscriber
) )
func (cns *MailingListSubscriber) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (cns *MailingListSubscriber) AuthorizationAttributes(
q := `SELECT organization_id FROM mailing_list_subscribers WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM mailing_list_subscribers WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, cns.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query mailing list subscriber authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (cns *MailingListSubscriber) CursorKey(orderBy MailingListSubscriberOrderField) page.CursorKey { func (cns *MailingListSubscriber) CursorKey(orderBy MailingListSubscriberOrderField) page.CursorKey {

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,19 +54,42 @@ func (mlu *MailingListUpdate) CursorKey(orderBy MailingListUpdateOrderField) pag
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (mlu *MailingListUpdate) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (mlu *MailingListUpdate) AuthorizationAttributes(
q := `SELECT organization_id FROM mailing_list_updates WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM mailing_list_updates WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, mlu.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query mailing list update authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (mlu *MailingListUpdate) Insert(ctx context.Context, conn pg.Tx, scope Scoper) error { func (mlu *MailingListUpdate) Insert(ctx context.Context, conn pg.Tx, scope Scoper) error {

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -56,19 +57,42 @@ func (m Measure) CursorKey(orderBy MeasureOrderField) page.CursorKey {
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (m *Measure) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (m *Measure) AuthorizationAttributes(
q := `SELECT organization_id FROM measures WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM measures WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, m.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query measure authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (m *Measures) CountByRiskID( func (m *Measures) CountByRiskID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -199,42 +200,64 @@ WHERE
return nil return nil
} }
func (m *Membership) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (m *Membership) AuthorizationAttributes(
ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := ` q := `
SELECT SELECT
id,
identity_id, identity_id,
organization_id, organization_id,
role role
FROM FROM
iam_memberships iam_memberships
WHERE WHERE
id = $1 id = ANY(@resource_ids::text[])
LIMIT 1;
` `
args := pgx.StrictNamedArgs{
"resource_ids": resourceIDs,
}
rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query membership authorization attributes: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var ( var (
id gid.GID
identityID gid.GID identityID gid.GID
organizationID gid.GID organizationID gid.GID
role MembershipRole role MembershipRole
) )
if err := conn.QueryRow(ctx, q, m.ID).Scan( err = rows.Scan(
&id,
&identityID, &identityID,
&organizationID, &organizationID,
&role, &role,
); err != nil { )
if errors.Is(err, pgx.ErrNoRows) { if err != nil {
return nil, ErrResourceNotFound return nil, fmt.Errorf("cannot scan membership authorization attributes: %w", err)
} }
return nil, fmt.Errorf("cannot query membership iam attributes: %w", err) attrsByID[id] = policy.Attributes{
}
return map[string]string{
"identity_id": identityID.String(), "identity_id": identityID.String(),
"organization_id": organizationID.String(), "organization_id": organizationID.String(),
"role": role.String(), "role": role.String(),
}, nil }
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate membership authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (m *Membership) LoadByIdentityAndOrg( func (m *Membership) LoadByIdentityAndOrg(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -87,26 +88,56 @@ func (p MembershipProfile) CursorKey(orderBy MembershipProfileOrderField) page.C
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (p *MembershipProfile) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (p *MembershipProfile) AuthorizationAttributes(
q := `SELECT organization_id, identity_id FROM iam_membership_profiles WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `
SELECT
id,
organization_id,
identity_id
FROM
iam_membership_profiles
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 profile authorization attributes: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var ( var (
id gid.GID
organizationID gid.GID organizationID gid.GID
identityID gid.GID identityID gid.GID
) )
if err := conn.QueryRow(ctx, q, p.ID).Scan(&organizationID, &identityID); err != nil { err = rows.Scan(&id, &organizationID, &identityID)
if errors.Is(err, pgx.ErrNoRows) { if err != nil {
return nil, ErrResourceNotFound return nil, fmt.Errorf("cannot scan profile authorization attributes: %w", err)
} }
return nil, fmt.Errorf("cannot query profile authorization attributes: %w", err) attrsByID[id] = policy.Attributes{
}
return map[string]string{
"organization_id": organizationID.String(), "organization_id": organizationID.String(),
"identity_id": identityID.String(), "identity_id": identityID.String(),
}, nil }
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate profile authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (p *MembershipProfile) LoadByID( func (p *MembershipProfile) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
"go.probo.inc/probo/pkg/uri" "go.probo.inc/probo/pkg/uri"
) )
@@ -72,32 +73,55 @@ func (c *OAuth2Client) CursorKey(orderBy OAuth2ClientOrderField) page.CursorKey
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (c *OAuth2Client) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (c *OAuth2Client) AuthorizationAttributes(
ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := ` q := `
SELECT SELECT
id,
organization_id organization_id
FROM FROM
iam_oauth2_clients iam_oauth2_clients
WHERE WHERE
id = $1 id = ANY(@resource_ids::text[])
LIMIT 1;
` `
var organizationID *gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, c.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query oauth2 client authorization attributes: %w", err) return nil, fmt.Errorf("cannot query oauth2 client authorization attributes: %w", err)
} }
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var (
id gid.GID
organizationID *gid.GID
)
err = rows.Scan(&id, &organizationID)
if err != nil {
return nil, fmt.Errorf("cannot scan oauth2 client authorization attributes: %w", err)
}
attrs := make(map[string]string) attrs := make(map[string]string)
if organizationID != nil { if organizationID != nil {
attrs["organization_id"] = organizationID.String() attrs["organization_id"] = organizationID.String()
} }
attrsByID[id] = attrs
}
return attrs, nil if err = rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate oauth2 client authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (c *OAuth2Client) LoadByID( func (c *OAuth2Client) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
"go.probo.inc/probo/pkg/uri" "go.probo.inc/probo/pkg/uri"
) )
@@ -58,31 +59,56 @@ func (c *OAuth2Consent) CursorKey(orderBy OAuth2ConsentOrderField) page.CursorKe
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (c *OAuth2Consent) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (c *OAuth2Consent) AuthorizationAttributes(
ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := ` q := `
SELECT SELECT
id,
identity_id, identity_id,
session_id session_id
FROM FROM
iam_oauth2_consents iam_oauth2_consents
WHERE WHERE
id = $1 id = ANY(@resource_ids::text[])
LIMIT 1;
` `
var identityID, sessionID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, c.ID).Scan(&identityID, &sessionID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query oauth2_consent authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query oauth2 consent authorization attributes: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var (
id gid.GID
identityID gid.GID
sessionID gid.GID
)
err = rows.Scan(&id, &identityID, &sessionID)
if err != nil {
return nil, fmt.Errorf("cannot scan oauth2 consent authorization attributes: %w", err)
} }
return map[string]string{ attrsByID[id] = policy.Attributes{
"identity_id": identityID.String(), "identity_id": identityID.String(),
"session_id": sessionID.String(), "session_id": sessionID.String(),
}, nil }
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate oauth2 consent authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (c *OAuth2Consent) LoadByID( func (c *OAuth2Consent) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -63,19 +64,42 @@ func (o *Obligation) CursorKey(field ObligationOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (o *Obligation) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (o *Obligation) AuthorizationAttributes(
q := `SELECT organization_id FROM obligations WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM obligations WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, o.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query obligation authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (o *Obligation) LoadByID( func (o *Obligation) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -46,19 +47,41 @@ type (
Organizations []*Organization Organizations []*Organization
) )
func (o *Organization) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (o *Organization) AuthorizationAttributes(
q := `SELECT id FROM organizations WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id FROM organizations 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 gid.GID var id gid.GID
if err := conn.QueryRow(ctx, q, o.ID).Scan(&id); err != nil { if err := rows.Scan(&id); err != nil {
if errors.Is(err, pgx.ErrNoRows) { return nil, fmt.Errorf("cannot scan authorization attributes: %w", err)
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query organization authorization attributes: %w", err) attrsByID[id] = policy.Attributes{
"organization_id": id.String(),
}
} }
return map[string]string{"organization_id": o.ID.String()}, nil if err := rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (o Organization) CursorKey(orderBy OrganizationOrderField) page.CursorKey { func (o Organization) CursorKey(orderBy OrganizationOrderField) page.CursorKey {

View File

@@ -23,6 +23,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -93,19 +94,51 @@ LIMIT 1;
return nil return nil
} }
func (a *PersonalAPIKey) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (a *PersonalAPIKey) AuthorizationAttributes(
q := "SELECT identity_id FROM iam_personal_api_keys WHERE id = $1 LIMIT 1;" ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `
SELECT
id,
identity_id
FROM
iam_personal_api_keys
WHERE
id = ANY(@resource_ids::text[])
`
var identityID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, a.ID).Scan(&identityID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query personal api key iam attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query personal api key authorization attributes: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var (
id gid.GID
identityID gid.GID
)
err = rows.Scan(&id, &identityID)
if err != nil {
return nil, fmt.Errorf("cannot scan personal api key authorization attributes: %w", err)
} }
return map[string]string{"identity_id": identityID.String()}, nil attrsByID[id] = policy.Attributes{"identity_id": identityID.String()}
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate personal api key authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (a *PersonalAPIKeys) LoadByIdentityID( func (a *PersonalAPIKeys) LoadByIdentityID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -176,19 +177,42 @@ func (p *ProcessingActivity) CursorKey(field ProcessingActivityOrderField) page.
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (p *ProcessingActivity) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (p *ProcessingActivity) AuthorizationAttributes(
q := `SELECT organization_id FROM processing_activities WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM processing_activities WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, p.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query processing activity authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (p *ProcessingActivity) LoadByID( func (p *ProcessingActivity) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -42,19 +43,42 @@ type (
Reports []*Report Reports []*Report
) )
func (r *Report) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (r *Report) AuthorizationAttributes(
q := `SELECT organization_id FROM reports WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM reports WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, r.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query report authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (r *Report) LoadByID( func (r *Report) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -61,19 +62,42 @@ func (rr *RightsRequest) CursorKey(field RightsRequestOrderField) page.CursorKey
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (rr *RightsRequest) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (rr *RightsRequest) AuthorizationAttributes(
q := `SELECT organization_id FROM rights_requests WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM rights_requests WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, rr.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query rights request authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (rr *RightsRequest) LoadByID( func (rr *RightsRequest) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -182,19 +183,42 @@ func (r *Risk) CursorKey(orderBy RiskOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (r *Risk) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (r *Risk) AuthorizationAttributes(
q := `SELECT organization_id FROM risks WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM risks WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, r.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query risk authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (r *Risks) CountByMeasureID( func (r *Risks) CountByMeasureID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -51,19 +52,42 @@ func (ra *RiskAssessment) CursorKey(orderBy RiskAssessmentOrderField) page.Curso
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (ra *RiskAssessment) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (ra *RiskAssessment) AuthorizationAttributes(
q := `SELECT organization_id FROM risk_assessments WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM risk_assessments WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, ra.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query risk assessment authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (ra *RiskAssessments) CountByOrganizationID( func (ra *RiskAssessments) CountByOrganizationID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,19 +54,42 @@ func (n *RiskAssessmentNode) CursorKey(orderBy RiskAssessmentNodeOrderField) pag
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (n *RiskAssessmentNode) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (n *RiskAssessmentNode) AuthorizationAttributes(
q := `SELECT organization_id FROM risk_assessment_nodes WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM risk_assessment_nodes WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, n.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query risk assessment node authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (ns *RiskAssessmentNodes) LoadByRiskAssessmentScopeID( func (ns *RiskAssessmentNodes) LoadByRiskAssessmentScopeID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -54,19 +55,42 @@ func (p *RiskAssessmentProcess) CursorKey(orderBy RiskAssessmentProcessOrderFiel
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (p *RiskAssessmentProcess) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (p *RiskAssessmentProcess) AuthorizationAttributes(
q := `SELECT organization_id FROM risk_assessment_processes WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM risk_assessment_processes WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, p.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query risk assessment process authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (ps *RiskAssessmentProcesses) LoadByRiskAssessmentScopeID( func (ps *RiskAssessmentProcesses) LoadByRiskAssessmentScopeID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -52,19 +53,42 @@ func (s *RiskAssessmentScenario) CursorKey(orderBy RiskAssessmentScenarioOrderFi
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (s *RiskAssessmentScenario) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *RiskAssessmentScenario) AuthorizationAttributes(
q := `SELECT organization_id FROM risk_assessment_scenarios WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM risk_assessment_scenarios WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query risk scenario authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (ss *RiskAssessmentScenarios) LoadByOrganizationID( func (ss *RiskAssessmentScenarios) LoadByOrganizationID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -51,19 +52,42 @@ func (s *RiskAssessmentScope) CursorKey(orderBy RiskAssessmentScopeOrderField) p
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (s *RiskAssessmentScope) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *RiskAssessmentScope) AuthorizationAttributes(
q := `SELECT organization_id FROM risk_assessment_scopes WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM risk_assessment_scopes WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query risk assessment scope authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (ss *RiskAssessmentScopes) LoadByRiskAssessmentID( func (ss *RiskAssessmentScopes) LoadByRiskAssessmentID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -54,19 +55,42 @@ func (t *RiskAssessmentThreat) CursorKey(orderBy RiskAssessmentThreatOrderField)
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (t *RiskAssessmentThreat) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (t *RiskAssessmentThreat) AuthorizationAttributes(
q := `SELECT organization_id FROM risk_assessment_threats WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM risk_assessment_threats WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, t.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query risk assessment threat authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (ts *RiskAssessmentThreats) LoadByRiskAssessmentScopeID( func (ts *RiskAssessmentThreats) LoadByRiskAssessmentScopeID(

View File

@@ -27,6 +27,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -63,19 +64,42 @@ func (s *SAMLConfiguration) CursorKey(orderBy SAMLConfigurationOrderField) page.
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (s *SAMLConfiguration) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *SAMLConfiguration) AuthorizationAttributes(
q := `SELECT organization_id FROM iam_saml_configurations WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM iam_saml_configurations WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query saml configuration authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (s *SAMLConfiguration) GetIdPCertificate() (*x509.Certificate, error) { func (s *SAMLConfiguration) GetIdPCertificate() (*x509.Certificate, error) {

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -60,19 +61,42 @@ func (s *SCIMBridge) CursorKey(orderBy SCIMBridgeOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (s *SCIMBridge) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *SCIMBridge) AuthorizationAttributes(
q := `SELECT organization_id FROM iam_scim_bridges WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM iam_scim_bridges WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query scim bridge authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (s *SCIMBridge) LoadByID( func (s *SCIMBridge) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -50,19 +51,42 @@ func (s *SCIMConfiguration) CursorKey(orderBy SCIMConfigurationOrderField) page.
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (s *SCIMConfiguration) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *SCIMConfiguration) AuthorizationAttributes(
q := `SELECT organization_id FROM iam_scim_configurations WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM iam_scim_configurations WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query scim configuration authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (s *SCIMConfiguration) LoadByID( func (s *SCIMConfiguration) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -56,19 +57,42 @@ func (s *SCIMEvent) CursorKey(orderBy SCIMEventOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (s *SCIMEvent) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *SCIMEvent) AuthorizationAttributes(
q := `SELECT organization_id FROM iam_scim_events WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM iam_scim_events WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query scim event authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (s *SCIMEvent) LoadByID( func (s *SCIMEvent) LoadByID(

View File

@@ -26,6 +26,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -194,27 +195,51 @@ LIMIT 1;
// AuthorizationAttributes loads the minimal authorization attributes for policy condition evaluation. // AuthorizationAttributes loads the minimal authorization attributes for policy condition evaluation.
// It is intentionally lightweight and does not populate the Session struct. // It is intentionally lightweight and does not populate the Session struct.
func (s *Session) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *Session) AuthorizationAttributes(
ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := ` q := `
SELECT SELECT
id,
identity_id identity_id
FROM FROM
iam_sessions iam_sessions
WHERE WHERE
id = $1 id = ANY(@resource_ids::text[])
LIMIT 1;
` `
var identityID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&identityID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query session iam attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query session authorization attributes: %w", err)
}
defer rows.Close()
attrsByID := make(policy.AttributesByID, len(resourceIDs))
for rows.Next() {
var (
id gid.GID
identityID gid.GID
)
err = rows.Scan(&id, &identityID)
if err != nil {
return nil, fmt.Errorf("cannot scan session authorization attributes: %w", err)
} }
return map[string]string{"identity_id": identityID.String()}, nil attrsByID[id] = policy.Attributes{"identity_id": identityID.String()}
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("cannot iterate session authorization attributes: %w", err)
}
return attrsByID, nil
} }
func (s *Session) Insert( func (s *Session) Insert(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
) )
@@ -57,19 +58,42 @@ func (e ErrSlackMessageNotFound) Error() string {
return "slack message not found" return "slack message not found"
} }
func (sm *SlackMessage) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (sm *SlackMessage) AuthorizationAttributes(
q := `SELECT organization_id FROM slack_messages WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM slack_messages WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, sm.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query slack message authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 NewSlackMessage( func NewSlackMessage(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -52,19 +53,42 @@ func (s StatementOfApplicability) CursorKey(orderBy StatementOfApplicabilityOrde
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (s *StatementOfApplicability) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (s *StatementOfApplicability) AuthorizationAttributes(
q := `SELECT organization_id FROM statements_of_applicability WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM statements_of_applicability WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, s.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query statement of applicability authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (s *StatementOfApplicability) LoadByID( func (s *StatementOfApplicability) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -63,19 +64,42 @@ func (t Task) CursorKey(orderBy TaskOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (t *Task) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (t *Task) AuthorizationAttributes(
q := `SELECT organization_id FROM tasks WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM tasks WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, t.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query task authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (t *Task) LoadByID( func (t *Task) LoadByID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -181,19 +182,42 @@ func (v ThirdParty) CursorKey(orderBy ThirdPartyOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (v *ThirdParty) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (v *ThirdParty) AuthorizationAttributes(
q := `SELECT organization_id FROM third_parties WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM third_parties WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, v.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query thirdParty authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (v *ThirdParty) LoadByID( func (v *ThirdParty) LoadByID(

View File

@@ -16,7 +16,6 @@ package coredata
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"maps" "maps"
"time" "time"
@@ -24,6 +23,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,19 +53,42 @@ func (v ThirdPartyBusinessAssociateAgreement) CursorKey(orderBy ThirdPartyBusine
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (vbaa *ThirdPartyBusinessAssociateAgreement) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (vbaa *ThirdPartyBusinessAssociateAgreement) AuthorizationAttributes(
q := `SELECT organization_id FROM third_party_business_associate_agreements WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM third_party_business_associate_agreements WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, vbaa.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query thirdParty business associate agreement authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (vbaa *ThirdPartyBusinessAssociateAgreement) LoadByThirdPartyID( func (vbaa *ThirdPartyBusinessAssociateAgreement) LoadByThirdPartyID(

View File

@@ -16,7 +16,6 @@ package coredata
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"maps" "maps"
"time" "time"
@@ -24,6 +23,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -54,19 +54,42 @@ func (c ThirdPartyComplianceReport) CursorKey(orderBy ThirdPartyComplianceReport
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (v *ThirdPartyComplianceReport) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (v *ThirdPartyComplianceReport) AuthorizationAttributes(
q := `SELECT organization_id FROM third_party_compliance_reports WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM third_party_compliance_reports WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, v.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query thirdParty compliance report authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (vcs *ThirdPartyComplianceReports) LoadForThirdPartyID( func (vcs *ThirdPartyComplianceReports) LoadForThirdPartyID(

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/mail" "go.probo.inc/probo/pkg/mail"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -57,19 +58,42 @@ func (vc ThirdPartyContact) CursorKey(orderBy ThirdPartyContactOrderField) page.
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (vc *ThirdPartyContact) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (vc *ThirdPartyContact) AuthorizationAttributes(
q := `SELECT organization_id FROM third_party_contacts WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM third_party_contacts WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, vc.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query thirdParty contact authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (vc *ThirdPartyContact) LoadByID( func (vc *ThirdPartyContact) LoadByID(

View File

@@ -16,7 +16,6 @@ package coredata
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"maps" "maps"
"time" "time"
@@ -24,6 +23,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,19 +53,42 @@ func (v ThirdPartyDataPrivacyAgreement) CursorKey(orderBy ThirdPartyDataPrivacyA
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (vdpa *ThirdPartyDataPrivacyAgreement) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (vdpa *ThirdPartyDataPrivacyAgreement) AuthorizationAttributes(
q := `SELECT organization_id FROM third_party_data_privacy_agreements WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM third_party_data_privacy_agreements WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, vdpa.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query thirdParty data privacy agreement authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (vdpa *ThirdPartyDataPrivacyAgreement) LoadByThirdPartyID( func (vdpa *ThirdPartyDataPrivacyAgreement) LoadByThirdPartyID(

View File

@@ -16,7 +16,6 @@ package coredata
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"maps" "maps"
"time" "time"
@@ -24,6 +23,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -55,19 +55,42 @@ func (v ThirdPartyRiskAssessment) CursorKey(orderBy ThirdPartyRiskAssessmentOrde
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (v *ThirdPartyRiskAssessment) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (v *ThirdPartyRiskAssessment) AuthorizationAttributes(
q := `SELECT organization_id FROM third_party_risk_assessments WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM third_party_risk_assessments WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, v.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query thirdParty risk assessment authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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
} }
// Insert adds a new risk assessment to the database // Insert adds a new risk assessment to the database

View File

@@ -24,6 +24,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -52,19 +53,42 @@ func (vs ThirdPartyService) CursorKey(orderBy ThirdPartyServiceOrderField) page.
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (vs *ThirdPartyService) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (vs *ThirdPartyService) AuthorizationAttributes(
q := `SELECT organization_id FROM third_party_services WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM third_party_services WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, vs.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query thirdParty service authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (vs *ThirdPartyService) LoadByID( func (vs *ThirdPartyService) LoadByID(

View File

@@ -26,6 +26,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -79,19 +80,42 @@ func (tp *TrackerPattern) CursorKey(field TrackerPatternOrderField) page.CursorK
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (tp *TrackerPattern) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (tp *TrackerPattern) AuthorizationAttributes(
q := `SELECT organization_id FROM tracker_patterns WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM tracker_patterns WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, tp.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query tracker pattern authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (tp *TrackerPattern) LoadByID( func (tp *TrackerPattern) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -67,19 +68,42 @@ func (tr *TrackerResource) CursorKey(field TrackerResourceOrderField) page.Curso
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (tr *TrackerResource) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (tr *TrackerResource) AuthorizationAttributes(
q := `SELECT organization_id FROM tracker_resources WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM tracker_resources WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, tr.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query tracker resource authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (tr *TrackerResource) LoadByID( func (tr *TrackerResource) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -162,19 +163,42 @@ func (tia *TransferImpactAssessment) CursorKey(field TransferImpactAssessmentOrd
panic(fmt.Sprintf("unsupported order by: %s", field)) panic(fmt.Sprintf("unsupported order by: %s", field))
} }
func (tia *TransferImpactAssessment) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (tia *TransferImpactAssessment) AuthorizationAttributes(
q := `SELECT organization_id FROM processing_activity_transfer_impact_assessments WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM processing_activity_transfer_impact_assessments WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, tia.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query transfer impact assessment authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (tias *TransferImpactAssessments) CountByOrganizationID( func (tias *TransferImpactAssessments) CountByOrganizationID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -56,19 +57,42 @@ func (tc *TrustCenter) CursorKey(orderBy TrustCenterOrderField) page.CursorKey {
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (tc *TrustCenter) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (tc *TrustCenter) AuthorizationAttributes(
q := `SELECT organization_id FROM trust_centers WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM trust_centers WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, tc.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query trust center authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (tc *TrustCenter) LoadByID( func (tc *TrustCenter) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -52,19 +53,42 @@ func (tca *TrustCenterAccess) CursorKey(orderBy TrustCenterAccessOrderField) pag
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (tca *TrustCenterAccess) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (tca *TrustCenterAccess) AuthorizationAttributes(
q := `SELECT organization_id FROM trust_center_accesses WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM trust_center_accesses WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, tca.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query trust center access authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (tca *TrustCenterAccess) LoadByID( func (tca *TrustCenterAccess) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -53,19 +54,42 @@ func (tcda *TrustCenterDocumentAccess) CursorKey(orderBy TrustCenterDocumentAcce
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (tcda *TrustCenterDocumentAccess) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (tcda *TrustCenterDocumentAccess) AuthorizationAttributes(
q := `SELECT organization_id FROM trust_center_document_accesses WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM trust_center_document_accesses WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, tcda.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query trust center document access authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (tcda *TrustCenterDocumentAccess) LoadByID( func (tcda *TrustCenterDocumentAccess) LoadByID(

View File

@@ -16,7 +16,6 @@ package coredata
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"maps" "maps"
"time" "time"
@@ -24,6 +23,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -55,19 +55,42 @@ func (t TrustCenterFile) CursorKey(orderBy TrustCenterFileOrderField) page.Curso
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (t *TrustCenterFile) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (t *TrustCenterFile) AuthorizationAttributes(
q := `SELECT organization_id FROM trust_center_files WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM trust_center_files WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, t.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query trust center file authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (t *TrustCenterFile) LoadByID( func (t *TrustCenterFile) LoadByID(

View File

@@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"go.gearno.de/kit/pg" "go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -60,19 +61,42 @@ func (t TrustCenterReference) CursorKey(orderBy TrustCenterReferenceOrderField)
panic(fmt.Sprintf("unsupported order by: %s", orderBy)) panic(fmt.Sprintf("unsupported order by: %s", orderBy))
} }
func (t *TrustCenterReference) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (t *TrustCenterReference) AuthorizationAttributes(
q := `SELECT organization_id FROM trust_center_references WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM trust_center_references WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, t.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query trust center reference authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (t *TrustCenterReference) LoadByID( func (t *TrustCenterReference) LoadByID(

View File

@@ -26,6 +26,7 @@ import (
"go.probo.inc/probo/pkg/crypto/cipher" "go.probo.inc/probo/pkg/crypto/cipher"
"go.probo.inc/probo/pkg/crypto/rand" "go.probo.inc/probo/pkg/crypto/rand"
"go.probo.inc/probo/pkg/gid" "go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
"go.probo.inc/probo/pkg/page" "go.probo.inc/probo/pkg/page"
) )
@@ -84,19 +85,42 @@ func (w WebhookSubscription) CursorKey(orderBy WebhookSubscriptionOrderField) pa
} }
// AuthorizationAttributes returns the authorization attributes for policy evaluation. // AuthorizationAttributes returns the authorization attributes for policy evaluation.
func (w *WebhookSubscription) AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) { func (w *WebhookSubscription) AuthorizationAttributes(
q := `SELECT organization_id FROM webhook_subscriptions WHERE id = $1 LIMIT 1;` ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
q := `SELECT id, organization_id FROM webhook_subscriptions WHERE id = ANY(@resource_ids::text[])`
var organizationID gid.GID args := pgx.StrictNamedArgs{
if err := conn.QueryRow(ctx, q, w.ID).Scan(&organizationID); err != nil { "resource_ids": resourceIDs,
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrResourceNotFound
} }
return nil, fmt.Errorf("cannot query webhook subscription authorization attributes: %w", err) rows, err := conn.Query(ctx, q, args)
if err != nil {
return nil, fmt.Errorf("cannot query authorization attributes: %w", err)
} }
return map[string]string{"organization_id": organizationID.String()}, nil defer rows.Close()
attrsByID := make(policy.AttributesByID)
for rows.Next() {
var id, organizationID gid.GID
err := rows.Scan(&id, &organizationID)
if 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 (w *WebhookSubscription) LoadByID( func (w *WebhookSubscription) LoadByID(

View File

@@ -16,10 +16,10 @@ package iam
import ( import (
"context" "context"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"maps" "maps"
"slices"
"strings" "strings"
"time" "time"
@@ -30,10 +30,14 @@ import (
"go.probo.inc/probo/pkg/iam/policy" "go.probo.inc/probo/pkg/iam/policy"
) )
// AuthorizationAttributer is implemented by entities that provide attributes // AuthorizationAttributer is implemented by entities that can provide
// for policy condition evaluation. // authorization attributes for multiple resources in one query.
type AuthorizationAttributer interface { type AuthorizationAttributer interface {
AuthorizationAttributes(ctx context.Context, conn pg.Querier) (map[string]string, error) AuthorizationAttributes(
ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error)
} }
// AuthorizeParams contains the parameters for an authorization request. // AuthorizeParams contains the parameters for an authorization request.
@@ -42,11 +46,40 @@ type AuthorizeParams struct {
Resource gid.GID Resource gid.GID
Session *gid.GID Session *gid.GID
Action string Action string
ResourceAttributes map[string]string ResourceAttributes policy.Attributes
DryRun bool DryRun bool
SkipAssumptionCheck bool SkipAssumptionCheck bool
} }
// AuthorizeBatchParams contains the parameters for a batch authorization request.
type AuthorizeBatchParams struct {
Principal gid.GID
Session *gid.GID
Action string
Resources []gid.GID
ResourceAttributes policy.Attributes
DryRun bool
SkipAssumptionCheck bool
}
// MultiAuthorizeItem contains one authorization request in a multi-authorization batch.
// ResourceAttributes are merged on top of the resource attributes loaded
// for the resource before the policy is evaluated.
type MultiAuthorizeItem struct {
Resource gid.GID
Action string
ResourceAttributes policy.Attributes
DryRun bool
SkipAssumptionCheck bool
}
// AuthorizeMultiParams contains the parameters for a multi-authorization request.
type AuthorizeMultiParams struct {
Principal gid.GID
Session *gid.GID
Items []MultiAuthorizeItem
}
// Authorizer evaluates authorization requests against registered policies. // Authorizer evaluates authorization requests against registered policies.
type Authorizer struct { type Authorizer struct {
pg *pg.Client pg *pg.Client
@@ -72,58 +105,303 @@ func (a *Authorizer) RegisterPolicySet(ps *PolicySet) {
// Authorize checks if the principal is allowed to perform the action on the resource. // Authorize checks if the principal is allowed to perform the action on the resource.
func (a *Authorizer) Authorize(ctx context.Context, params AuthorizeParams) (*coredata.Scope, error) { func (a *Authorizer) Authorize(ctx context.Context, params AuthorizeParams) (*coredata.Scope, error) {
return a.AuthorizeBatch(
ctx,
AuthorizeBatchParams{
Principal: params.Principal,
Session: params.Session,
Action: params.Action,
Resources: []gid.GID{params.Resource},
ResourceAttributes: params.ResourceAttributes,
DryRun: params.DryRun,
SkipAssumptionCheck: params.SkipAssumptionCheck,
},
)
}
// AuthorizeBatch checks whether the principal is allowed to perform the action
// on all provided resources.
func (a *Authorizer) AuthorizeBatch(ctx context.Context, params AuthorizeBatchParams) (*coredata.Scope, error) {
if params.Principal.EntityType() != coredata.IdentityEntityType { if params.Principal.EntityType() != coredata.IdentityEntityType {
return nil, NewUnsupportedPrincipalTypeError(params.Principal.EntityType()) return nil, NewUnsupportedPrincipalTypeError(params.Principal.EntityType())
} }
if len(params.Resources) == 0 {
return nil, NewEmptyResourceBatchError(params.Action)
}
expectedEntityType := params.Resources[0].EntityType()
items := make([]MultiAuthorizeItem, 0, len(params.Resources))
for _, resourceID := range params.Resources {
if resourceID.EntityType() != expectedEntityType {
entityTypes := make([]uint16, 0, len(params.Resources))
for _, r := range params.Resources {
entityTypes = append(entityTypes, r.EntityType())
}
return nil, NewMixedEntityTypeBatchError(
params.Action,
uniqueSortedEntityTypes(entityTypes),
)
}
items = append(
items,
MultiAuthorizeItem{
Resource: resourceID,
Action: params.Action,
DryRun: params.DryRun,
SkipAssumptionCheck: params.SkipAssumptionCheck,
},
)
}
var scope *coredata.Scope var scope *coredata.Scope
if err := a.pg.WithTx(ctx, func(ctx context.Context, tx pg.Tx) error { if err := a.pg.WithTx(
authorizedScope, err := a.authorize(ctx, tx, params) ctx,
func(ctx context.Context, tx pg.Tx) error {
authorizedScope, err := a.authorizeMulti(
ctx,
tx,
AuthorizeMultiParams{
Principal: params.Principal,
Session: params.Session,
Items: items,
},
params.ResourceAttributes,
)
if err != nil { if err != nil {
return err return err
} }
scope = authorizedScope scope = authorizedScope
return nil return nil
}); err != nil { },
); err != nil {
return nil, err return nil, err
} }
return scope, nil return scope, nil
} }
func (a *Authorizer) authorize(ctx context.Context, tx pg.Tx, params AuthorizeParams) (*coredata.Scope, error) { // AuthorizeMulti evaluates each item independently and returns one decision
resourceAttrs, err := a.buildResourceAttributes(ctx, tx, params) // per item: a nil entry means allowed, a non-nil entry carries the iam
if err != nil { // error explaining the denial (typically *ErrInsufficientPermissions).
return nil, fmt.Errorf("cannot build resource attributes: %w", err) //
// Audit log entries for allowed, non-dry-run items are written in a single
// bulk insert. Use AuthorizeBatch instead when callers want all-or-nothing
// semantics for a homogeneous batch.
func (a *Authorizer) AuthorizeMulti(
ctx context.Context,
params AuthorizeMultiParams,
) (*coredata.Scope, []error, error) {
if params.Principal.EntityType() != coredata.IdentityEntityType {
return nil, nil, NewUnsupportedPrincipalTypeError(params.Principal.EntityType())
} }
resourceOrgID := resourceAttrs["organization_id"] if len(params.Items) == 0 {
return nil, nil, NewEmptyResourceBatchError("")
// Find role for resource's organization
membership, err := a.loadMembership(ctx, tx, params.Principal, resourceOrgID)
if err != nil {
return nil, fmt.Errorf("cannot load memberships for principal: %w", err)
} }
// Check whether the viewer is currently assuming the org of the accessed resource var (
if membership != nil && params.Session != nil && !params.SkipAssumptionCheck { scope *coredata.Scope
if _, err := a.getActiveChildSessionForMembership( decisions []error
)
if err := a.pg.WithTx(
ctx,
func(ctx context.Context, tx pg.Tx) error {
s, itemAttrs, d, err := a.evaluateMultiInTx(ctx, tx, params, nil)
if err != nil {
return err
}
entries := make(coredata.AuditLogEntries, 0, len(params.Items))
for i, item := range params.Items {
if d[i] != nil {
continue
}
entry := a.buildAuditLogEntry(
ctx,
AuthorizeParams{
Principal: params.Principal,
Resource: item.Resource,
Session: params.Session,
Action: item.Action,
DryRun: item.DryRun,
},
itemAttrs[i],
)
if entry == nil {
continue
}
entries = append(entries, entry)
}
if len(entries) > 0 {
if err := entries.BulkInsert(ctx, tx, s); err != nil {
a.logger.ErrorCtx(
ctx,
"cannot bulk insert audit log entries",
log.Error(err),
log.String("action", params.Items[0].Action),
)
}
}
scope = s
decisions = d
return nil
},
); err != nil {
return nil, nil, err
}
return scope, decisions, nil
}
func (a *Authorizer) authorizeMulti(
ctx context.Context,
tx pg.Tx,
params AuthorizeMultiParams,
extraResourceAttributes policy.Attributes,
) (*coredata.Scope, error) {
scope, itemAttrs, decisions, err := a.evaluateMultiInTx(
ctx, ctx,
tx, tx,
*params.Session, params,
membership.ID, extraResourceAttributes,
); err != nil { )
if _, ok := errors.AsType[*ErrSessionNotFound](err); ok { if err != nil {
return nil, NewAssumptionRequiredError(params.Principal, membership.ID) return nil, err
} }
if _, ok := errors.AsType[*ErrSessionExpired](err); ok { for _, decision := range decisions {
return nil, NewAssumptionRequiredError(params.Principal, membership.ID) if decision != nil {
return nil, decision
}
} }
return nil, fmt.Errorf("cannot get active child session for membership: %w", err) entries := make(coredata.AuditLogEntries, 0, len(params.Items))
for i, item := range params.Items {
entry := a.buildAuditLogEntry(
ctx,
AuthorizeParams{
Principal: params.Principal,
Resource: item.Resource,
Session: params.Session,
Action: item.Action,
DryRun: item.DryRun,
},
itemAttrs[i],
)
if entry == nil {
continue
}
entries = append(entries, entry)
}
if len(entries) > 0 {
if err := entries.BulkInsert(ctx, tx, scope); err != nil {
a.logger.ErrorCtx(
ctx,
"cannot bulk insert audit log entries",
log.Error(err),
log.String("action", params.Items[0].Action),
)
}
}
return scope, nil
}
// evaluateMultiInTx evaluates every item in params against the loaded
// policies and resource attributes. It returns the shared scope, the merged
// per-item resource attributes (used for both evaluation and audit log
// building), and a parallel slice of per-item decisions (nil = allowed).
// Callers decide which decisions to persist to the audit log.
func (a *Authorizer) evaluateMultiInTx(
ctx context.Context,
tx pg.Tx,
params AuthorizeMultiParams,
extraResourceAttributes policy.Attributes,
) (*coredata.Scope, []policy.Attributes, []error, error) {
uniqueResourceIDs := make([]gid.GID, 0, len(params.Items))
seenResourceIDs := make(map[gid.GID]struct{}, len(params.Items))
requiresAssumptionCheck := false
for _, item := range params.Items {
if !item.SkipAssumptionCheck {
requiresAssumptionCheck = true
}
if _, ok := seenResourceIDs[item.Resource]; ok {
continue
}
seenResourceIDs[item.Resource] = struct{}{}
uniqueResourceIDs = append(uniqueResourceIDs, item.Resource)
}
resourceAttrsByResourceID, err := a.buildResourceAttributesBatch(
ctx,
tx,
uniqueResourceIDs,
extraResourceAttributes,
)
if err != nil {
return nil, nil, nil, fmt.Errorf("cannot build resource attributes batch: %w", err)
}
actionForErrors := params.Items[0].Action
resourceOrgID := resourceAttrsByResourceID[uniqueResourceIDs[0]]["organization_id"]
for _, resourceID := range uniqueResourceIDs[1:] {
if resourceAttrsByResourceID[resourceID]["organization_id"] != resourceOrgID {
orgIDs := make([]string, 0, len(uniqueResourceIDs))
for _, id := range uniqueResourceIDs {
orgIDs = append(orgIDs, resourceAttrsByResourceID[id]["organization_id"])
}
return nil, nil, nil, NewMixedOrganizationBatchError(
actionForErrors,
uniqueSortedStrings(orgIDs),
)
}
}
membership, err := a.loadMembership(ctx, tx, params.Principal, resourceOrgID)
if err != nil {
return nil, nil, nil, fmt.Errorf("cannot load memberships for principal: %w", err)
}
// The assumption check is a property of (principal, membership, session),
// so it only runs once even though SkipAssumptionCheck is per-item.
// On failure, ErrAssumptionRequired is recorded only against items that
// did not opt out.
var assumptionErr error
if requiresAssumptionCheck {
err := a.checkAssumption(
ctx,
tx,
params.Principal,
params.Session,
membership,
false,
)
if err != nil {
if _, ok := errors.AsType[*ErrAssumptionRequired](err); !ok {
return nil, nil, nil, err
}
assumptionErr = err
} }
} }
@@ -132,10 +410,9 @@ func (a *Authorizer) authorize(ctx context.Context, tx pg.Tx, params AuthorizePa
role = membership.Role.String() role = membership.Role.String()
} }
// Only set principal.organization_id if they have a role in this org var scopedPrincipalAttrs policy.Attributes
var scopedPrincipalAttrs map[string]string
if membership != nil && role != "" { if membership != nil && role != "" {
scopedPrincipalAttrs = map[string]string{ scopedPrincipalAttrs = policy.Attributes{
"organization_id": membership.OrganizationID.String(), "organization_id": membership.OrganizationID.String(),
"role": membership.Role.String(), "role": membership.Role.String(),
} }
@@ -143,7 +420,7 @@ func (a *Authorizer) authorize(ctx context.Context, tx pg.Tx, params AuthorizePa
principalAttrs, err := a.buildPrincipalAttributes(ctx, tx, params.Principal, scopedPrincipalAttrs) principalAttrs, err := a.buildPrincipalAttributes(ctx, tx, params.Principal, scopedPrincipalAttrs)
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot build principal attributes: %w", err) return nil, nil, nil, fmt.Errorf("cannot build principal attributes: %w", err)
} }
if params.Session != nil { if params.Session != nil {
@@ -152,32 +429,162 @@ func (a *Authorizer) authorize(ctx context.Context, tx pg.Tx, params AuthorizePa
policies := a.buildPoliciesForRole(role) policies := a.buildPoliciesForRole(role)
decisions := make([]error, len(params.Items))
itemAttrs := make([]policy.Attributes, len(params.Items))
for i, item := range params.Items {
resAttrs := resourceAttrsByResourceID[item.Resource]
if len(item.ResourceAttributes) > 0 {
merged := maps.Clone(resAttrs)
maps.Copy(merged, item.ResourceAttributes)
resAttrs = merged
}
itemAttrs[i] = resAttrs
if assumptionErr != nil && !item.SkipAssumptionCheck {
decisions[i] = assumptionErr
continue
}
req := policy.AuthorizationRequest{ req := policy.AuthorizationRequest{
Principal: params.Principal, Principal: params.Principal,
Resource: params.Resource, Resource: item.Resource,
Action: params.Action, Action: item.Action,
ConditionContext: policy.ConditionContext{ ConditionContext: policy.ConditionContext{
Principal: principalAttrs, Principal: principalAttrs,
Resource: resourceAttrs, Resource: resAttrs,
}, },
} }
if a.evaluator.Evaluate(req, policies).IsAllowed() { if !a.evaluator.Evaluate(req, policies).IsAllowed() {
scope := coredata.NewScopeFromObjectID(params.Resource) decisions[i] = NewInsufficientPermissionsError(params.Principal, item.Resource, item.Action)
if resourceOrgID != "" { }
orgID, err := gid.ParseGID(resourceOrgID)
if err != nil {
return nil, fmt.Errorf("cannot parse organization id from resource attributes: %w", err)
} }
scope := coredata.NewScopeFromObjectID(uniqueResourceIDs[0])
if resourceOrgID != "" {
orgID, _ := gid.ParseGID(resourceOrgID)
scope = coredata.NewScope(orgID.TenantID()) scope = coredata.NewScope(orgID.TenantID())
} }
a.recordAuditLog(ctx, tx, params, resourceAttrs) return scope, itemAttrs, decisions, nil
return scope, nil }
func (a *Authorizer) buildResourceAttributesBatch(
ctx context.Context,
conn pg.Querier,
uniqueResourceIDs []gid.GID,
extraResourceAttributes policy.Attributes,
) (policy.AttributesByID, error) {
resourceAttrsByID, err := a.loadResourceAttributesByType(ctx, conn, uniqueResourceIDs)
if err != nil {
return nil, err
} }
return nil, NewInsufficientPermissionsError(params.Principal, params.Resource, params.Action) resourceAttrsByResourceID := make(policy.AttributesByID, len(uniqueResourceIDs))
for _, resourceID := range uniqueResourceIDs {
resourceAttrs := resourceAttrsByID[resourceID]
attrs := policy.Attributes{
"id": resourceID.String(),
}
maps.Copy(attrs, resourceAttrs)
if extraResourceAttributes != nil {
maps.Copy(attrs, extraResourceAttributes)
}
resourceAttrsByResourceID[resourceID] = attrs
}
return resourceAttrsByResourceID, nil
}
func (a *Authorizer) loadResourceAttributesByType(
ctx context.Context,
conn pg.Querier,
resourceIDs []gid.GID,
) (policy.AttributesByID, error) {
resourceIDsByEntityType := make(map[uint16][]gid.GID)
orderedEntityTypes := make([]uint16, 0, len(resourceIDs))
for _, resourceID := range resourceIDs {
entityType := resourceID.EntityType()
if _, ok := resourceIDsByEntityType[entityType]; !ok {
orderedEntityTypes = append(orderedEntityTypes, entityType)
}
resourceIDsByEntityType[entityType] = append(resourceIDsByEntityType[entityType], resourceID)
}
resourceAttrsByID := make(policy.AttributesByID, len(resourceIDs))
for _, entityType := range orderedEntityTypes {
groupResourceIDs := resourceIDsByEntityType[entityType]
entity, ok := coredata.NewEntityFromID(groupResourceIDs[0])
if !ok {
return nil, fmt.Errorf("unsupported resource type: %d", groupResourceIDs[0].EntityType())
}
attributer, ok := entity.(AuthorizationAttributer)
if !ok {
return nil, NewBatchAuthorizationUnsupportedResourceTypeError(entityType)
}
groupAttrsByID, err := attributer.AuthorizationAttributes(ctx, conn, groupResourceIDs)
if err != nil {
return nil, fmt.Errorf(
"cannot load batched resource attributes for entity type %d: %w",
entityType,
err,
)
}
for _, resourceID := range groupResourceIDs {
resourceAttrs, ok := groupAttrsByID[resourceID]
if !ok {
return nil, coredata.ErrResourceNotFound
}
resourceAttrsByID[resourceID] = resourceAttrs
}
}
return resourceAttrsByID, nil
}
func (a *Authorizer) checkAssumption(
ctx context.Context,
tx pg.Tx,
principalID gid.GID,
sessionID *gid.GID,
membership *coredata.Membership,
skipAssumptionCheck bool,
) error {
if membership == nil || sessionID == nil || skipAssumptionCheck {
return nil
}
if _, err := a.getActiveChildSessionForMembership(
ctx,
tx,
*sessionID,
membership.ID,
); err != nil {
if _, ok := errors.AsType[*ErrSessionNotFound](err); ok {
return NewAssumptionRequiredError(principalID, membership.ID)
}
if _, ok := errors.AsType[*ErrSessionExpired](err); ok {
return NewAssumptionRequiredError(principalID, membership.ID)
}
return fmt.Errorf("cannot get active child session for membership: %w", err)
}
return nil
} }
func (a *Authorizer) loadMembership( func (a *Authorizer) loadMembership(
@@ -234,55 +641,30 @@ func (a *Authorizer) buildPrincipalAttributes(
ctx context.Context, ctx context.Context,
conn pg.Querier, conn pg.Querier,
principalID gid.GID, principalID gid.GID,
defaultAttrs map[string]string, defaultAttrs policy.Attributes,
) (map[string]string, error) { ) (policy.Attributes, error) {
attrs := map[string]string{ attrs := policy.Attributes{
"id": principalID.String(), "id": principalID.String(),
} }
maps.Copy(attrs, defaultAttrs) maps.Copy(attrs, defaultAttrs)
if entity, ok := coredata.NewEntityFromID(principalID); ok { if entity, ok := coredata.NewEntityFromID(principalID); ok {
if attributer, ok := entity.(AuthorizationAttributer); ok { attributer, ok := entity.(AuthorizationAttributer)
entityAttrs, err := attributer.AuthorizationAttributes(ctx, conn) if !ok {
return nil, NewBatchAuthorizationUnsupportedResourceTypeError(principalID.EntityType())
}
entityAttrsByID, err := attributer.AuthorizationAttributes(ctx, conn, []gid.GID{principalID})
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot load principal attributes: %w", err) return nil, fmt.Errorf("cannot load principal attributes: %w", err)
} }
maps.Copy(attrs, entityAttrs) entityAttrs, ok := entityAttrsByID[principalID]
}
}
return attrs, nil
}
func (a *Authorizer) buildResourceAttributes(
ctx context.Context,
conn pg.Querier,
params AuthorizeParams,
) (map[string]string, error) {
attrs := map[string]string{
"id": params.Resource.String(),
}
entity, ok := coredata.NewEntityFromID(params.Resource)
if !ok { if !ok {
return nil, fmt.Errorf("unsupported resource type: %d", params.Resource.EntityType()) return nil, coredata.ErrResourceNotFound
}
attributer, ok := entity.(AuthorizationAttributer)
if !ok {
return nil, fmt.Errorf("resource %d does not implement AuthorizationAttributer", params.Resource.EntityType())
}
entityAttrs, err := attributer.AuthorizationAttributes(ctx, conn)
if err != nil {
return nil, fmt.Errorf("cannot load resource attributes: %w", err)
} }
maps.Copy(attrs, entityAttrs) maps.Copy(attrs, entityAttrs)
if params.ResourceAttributes != nil {
maps.Copy(attrs, params.ResourceAttributes)
} }
return attrs, nil return attrs, nil
@@ -298,9 +680,44 @@ func (a *Authorizer) buildPoliciesForRole(role string) []*policy.Policy {
return policies return policies
} }
// resourceTypeFromAction extracts the resource type name from an action func uniqueSortedStrings(values []string) []string {
// string. For example, "core:thirdParty:create" returns "ThirdParty" and set := make(map[string]struct{}, len(values))
// "core:webhook-subscription:delete" returns "WebhookSubscription". unique := make([]string, 0, len(values))
for _, value := range values {
if _, ok := set[value]; ok {
continue
}
set[value] = struct{}{}
unique = append(unique, value)
}
slices.Sort(unique)
return unique
}
func uniqueSortedEntityTypes(values []uint16) []uint16 {
set := make(map[uint16]struct{}, len(values))
unique := make([]uint16, 0, len(values))
for _, value := range values {
if _, ok := set[value]; ok {
continue
}
set[value] = struct{}{}
unique = append(unique, value)
}
slices.Sort(unique)
return unique
}
// resourceTypeFromAction extracts the PascalCase resource type from an
// action string, e.g. "core:webhook-subscription:delete" -> "WebhookSubscription".
func resourceTypeFromAction(action string) string { func resourceTypeFromAction(action string) string {
parts := strings.Split(action, ":") parts := strings.Split(action, ":")
if len(parts) < 3 { if len(parts) < 3 {
@@ -317,19 +734,20 @@ func resourceTypeFromAction(action string) string {
return strings.Join(segments, "") return strings.Join(segments, "")
} }
func (a *Authorizer) recordAuditLog( // buildAuditLogEntry returns nil when no entry should be recorded
// (dry run or missing/invalid organization id).
func (a *Authorizer) buildAuditLogEntry(
ctx context.Context, ctx context.Context,
tx pg.Tx,
params AuthorizeParams, params AuthorizeParams,
resourceAttrs map[string]string, resourceAttrs policy.Attributes,
) { ) *coredata.AuditLogEntry {
if params.DryRun { if params.DryRun {
return return nil
} }
orgIDStr := resourceAttrs["organization_id"] orgIDStr := resourceAttrs["organization_id"]
if orgIDStr == "" { if orgIDStr == "" {
return return nil
} }
orgID, err := gid.ParseGID(orgIDStr) orgID, err := gid.ParseGID(orgIDStr)
@@ -340,7 +758,7 @@ func (a *Authorizer) recordAuditLog(
log.Error(err), log.Error(err),
) )
return return nil
} }
var actorType coredata.AuditLogActorType var actorType coredata.AuditLogActorType
@@ -352,18 +770,9 @@ func (a *Authorizer) recordAuditLog(
resourceType := resourceTypeFromAction(params.Action) resourceType := resourceTypeFromAction(params.Action)
metadata, err := json.Marshal(map[string]any{}) metadata := []byte("{}")
if err != nil {
a.logger.ErrorCtx(
ctx,
"cannot marshal audit log metadata",
log.Error(err),
)
return return &coredata.AuditLogEntry{
}
entry := &coredata.AuditLogEntry{
ID: gid.New(orgID.TenantID(), coredata.AuditLogEntryEntityType), ID: gid.New(orgID.TenantID(), coredata.AuditLogEntryEntityType),
OrganizationID: orgID, OrganizationID: orgID,
ActorID: params.Principal, ActorID: params.Principal,
@@ -374,16 +783,4 @@ func (a *Authorizer) recordAuditLog(
Metadata: metadata, Metadata: metadata,
CreatedAt: time.Now(), CreatedAt: time.Now(),
} }
scope := coredata.NewScope(orgID.TenantID())
if err := entry.Insert(ctx, tx, scope); err != nil {
a.logger.ErrorCtx(
ctx,
"cannot insert audit log entry",
log.Error(err),
log.String("action", params.Action),
log.String("resource_id", params.Resource.String()),
)
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,489 @@
// 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 iam
import (
"context"
"errors"
"io"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
"go.probo.inc/probo/pkg/iam/policy"
)
func TestAuthorizer_ValidateInputs(t *testing.T) {
t.Parallel()
t.Run("authorize rejects unsupported principal type", func(t *testing.T) {
t.Parallel()
a := &Authorizer{}
_, err := a.Authorize(
context.Background(),
AuthorizeParams{
Principal: gid.New(gid.NewTenantID(), coredata.OrganizationEntityType),
},
)
require.Error(t, err)
errUnsupported, ok := errors.AsType[*ErrUnsupportedPrincipalType](err)
require.True(t, ok)
assert.Equal(t, coredata.OrganizationEntityType, errUnsupported.EntityType)
})
t.Run("authorize batch rejects unsupported principal type", func(t *testing.T) {
t.Parallel()
a := &Authorizer{}
_, err := a.AuthorizeBatch(
context.Background(),
AuthorizeBatchParams{
Principal: gid.New(gid.NewTenantID(), coredata.OrganizationEntityType),
Resources: []gid.GID{gid.New(gid.NewTenantID(), coredata.FrameworkEntityType)},
},
)
require.Error(t, err)
errUnsupported, ok := errors.AsType[*ErrUnsupportedPrincipalType](err)
require.True(t, ok)
assert.Equal(t, coredata.OrganizationEntityType, errUnsupported.EntityType)
})
t.Run("authorize batch rejects empty resources", func(t *testing.T) {
t.Parallel()
a := &Authorizer{}
_, err := a.AuthorizeBatch(
context.Background(),
AuthorizeBatchParams{
Principal: gid.New(gid.NilTenant, coredata.IdentityEntityType),
},
)
require.Error(t, err)
_, ok := errors.AsType[*ErrEmptyResourceBatch](err)
require.True(t, ok)
})
}
func TestAuthorizer_InternalErrorPaths(t *testing.T) {
t.Parallel()
ctx := context.Background()
identityID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
unknownResourceID := gid.New(gid.NewTenantID(), 65535)
unsupportedResourceID := gid.New(gid.NewTenantID(), coredata.OAuth2AccessTokenEntityType)
a := &Authorizer{
evaluator: policy.NewEvaluator(),
policySet: NewPolicySet(),
}
t.Run("authorize batch returns wrapped resource attributes batch error", func(t *testing.T) {
t.Parallel()
_, err := a.authorizeMulti(
ctx,
nil,
AuthorizeMultiParams{
Principal: identityID,
Items: []MultiAuthorizeItem{
{
Resource: unknownResourceID,
Action: "core:test:list",
},
},
},
nil,
)
require.Error(t, err)
assert.ErrorContains(t, err, "cannot build resource attributes batch")
})
t.Run("authorize batch rejects mixed entity types", func(t *testing.T) {
t.Parallel()
firstResourceID := gid.New(gid.NewTenantID(), coredata.FrameworkEntityType)
secondResourceID := gid.New(gid.NewTenantID(), coredata.OrganizationEntityType)
_, err := a.AuthorizeBatch(
ctx,
AuthorizeBatchParams{
Principal: identityID,
Action: "core:test:list",
Resources: []gid.GID{firstResourceID, secondResourceID},
},
)
require.Error(t, err)
errMixedEntityType, ok := errors.AsType[*ErrMixedEntityTypeBatch](err)
require.True(t, ok)
assert.Equal(
t,
[]uint16{coredata.OrganizationEntityType, coredata.FrameworkEntityType},
errMixedEntityType.EntityTypes,
)
})
t.Run("build principal attributes rejects unsupported batch interface type", func(t *testing.T) {
t.Parallel()
_, err := a.buildPrincipalAttributes(
ctx,
nil,
unsupportedResourceID,
map[string]string{"role": "OWNER"},
)
require.Error(t, err)
errUnsupported, ok := errors.AsType[*ErrBatchAuthorizationUnsupportedResourceType](err)
require.True(t, ok)
assert.Equal(t, coredata.OAuth2AccessTokenEntityType, errUnsupported.EntityType)
})
t.Run("build principal attributes keeps defaults when entity type is unknown", func(t *testing.T) {
t.Parallel()
attrs, err := a.buildPrincipalAttributes(
ctx,
nil,
unknownResourceID,
map[string]string{"role": "OWNER"},
)
require.NoError(t, err)
assert.Equal(t, unknownResourceID.String(), attrs["id"])
assert.Equal(t, "OWNER", attrs["role"])
})
}
func TestAuthorizer_HelperMethods(t *testing.T) {
t.Parallel()
t.Run("check assumption short-circuits", func(t *testing.T) {
t.Parallel()
a := &Authorizer{}
identityID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
sessionID := gid.New(gid.NilTenant, coredata.SessionEntityType)
membership := &coredata.Membership{ID: gid.New(gid.NewTenantID(), coredata.MembershipEntityType)}
require.NoError(t, a.checkAssumption(context.Background(), nil, identityID, nil, membership, false))
require.NoError(t, a.checkAssumption(context.Background(), nil, identityID, &sessionID, nil, false))
require.NoError(t, a.checkAssumption(context.Background(), nil, identityID, &sessionID, membership, true))
})
t.Run("build policies for role includes identity scoped policies", func(t *testing.T) {
t.Parallel()
a := &Authorizer{
policySet: NewPolicySet().
AddIdentityScopedPolicy(policy.NewPolicy("identity", "Identity", policy.Allow("identity:read"))).
AddRolePolicy("OWNER", policy.NewPolicy("owner", "Owner", policy.Allow("core:*"))),
}
withRole := a.buildPoliciesForRole("OWNER")
require.Len(t, withRole, 2)
withoutRole := a.buildPoliciesForRole("VIEWER")
require.Len(t, withoutRole, 1)
})
t.Run("unique sorted strings deduplicates and sorts", func(t *testing.T) {
t.Parallel()
got := uniqueSortedStrings([]string{"b", "a", "b", "", "c", "a"})
assert.Equal(t, []string{"", "a", "b", "c"}, got)
})
t.Run("unique sorted entity types deduplicates and sorts", func(t *testing.T) {
t.Parallel()
got := uniqueSortedEntityTypes(
[]uint16{
coredata.FrameworkEntityType,
coredata.OrganizationEntityType,
coredata.FrameworkEntityType,
coredata.OrganizationEntityType,
},
)
assert.Equal(
t,
[]uint16{coredata.OrganizationEntityType, coredata.FrameworkEntityType},
got,
)
})
t.Run("resource type from action parses segments", func(t *testing.T) {
t.Parallel()
assert.Equal(t, "ThirdParty", resourceTypeFromAction("core:third-party:get"))
assert.Equal(t, "WebhookSubscription", resourceTypeFromAction("core:webhook-subscription:delete"))
assert.Equal(t, "Unknown", resourceTypeFromAction("invalid-action"))
})
}
func TestAuthorizer_LoadMembership(t *testing.T) {
t.Parallel()
a := &Authorizer{}
t.Run("empty organization id returns nil membership", func(t *testing.T) {
t.Parallel()
membership, err := a.loadMembership(
context.Background(),
nil,
gid.New(gid.NilTenant, coredata.IdentityEntityType),
"",
)
require.NoError(t, err)
assert.Nil(t, membership)
})
t.Run("invalid organization id returns parse error", func(t *testing.T) {
t.Parallel()
_, err := a.loadMembership(
context.Background(),
nil,
gid.New(gid.NilTenant, coredata.IdentityEntityType),
"not-a-gid",
)
require.Error(t, err)
assert.ErrorContains(t, err, "cannot parse gid")
})
}
func TestAuthorizer_BuildAuditLogEntry(t *testing.T) {
t.Parallel()
tenantID := gid.NewTenantID()
orgID := gid.New(tenantID, coredata.OrganizationEntityType)
principalID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
resourceID := gid.New(tenantID, coredata.FrameworkEntityType)
sessionID := gid.New(gid.NilTenant, coredata.SessionEntityType)
tests := []struct {
name string
params AuthorizeParams
resourceAttrs policy.Attributes
wantNil bool
wantActorType coredata.AuditLogActorType
}{
{
name: "dry run returns nil",
params: AuthorizeParams{
Principal: principalID,
Resource: resourceID,
Action: "core:framework:get",
DryRun: true,
},
resourceAttrs: policy.Attributes{
"organization_id": orgID.String(),
},
wantNil: true,
},
{
name: "missing organization id returns nil",
params: AuthorizeParams{
Principal: principalID,
Resource: resourceID,
Action: "core:framework:get",
},
resourceAttrs: policy.Attributes{
"id": resourceID.String(),
},
wantNil: true,
},
{
name: "unparseable organization id returns nil",
params: AuthorizeParams{
Principal: principalID,
Resource: resourceID,
Action: "core:framework:get",
},
resourceAttrs: policy.Attributes{
"organization_id": "invalid-gid",
},
wantNil: true,
},
{
name: "session present sets user actor type",
params: AuthorizeParams{
Principal: principalID,
Resource: resourceID,
Action: "core:framework:get",
Session: &sessionID,
},
resourceAttrs: policy.Attributes{
"organization_id": orgID.String(),
},
wantActorType: coredata.AuditLogActorTypeUser,
},
{
name: "nil session sets api key actor type",
params: AuthorizeParams{
Principal: principalID,
Resource: resourceID,
Action: "core:framework:get",
},
resourceAttrs: policy.Attributes{
"organization_id": orgID.String(),
},
wantActorType: coredata.AuditLogActorTypeAPIKey,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
a := &Authorizer{
logger: log.NewLogger(log.WithOutput(io.Discard)),
}
entry := a.buildAuditLogEntry(context.Background(), tt.params, tt.resourceAttrs)
if tt.wantNil {
assert.Nil(t, entry)
return
}
require.NotNil(t, entry)
assert.Equal(t, tt.wantActorType, entry.ActorType)
assert.Equal(t, tt.params.Principal, entry.ActorID)
assert.Equal(t, tt.params.Resource, entry.ResourceID)
assert.Equal(t, tt.params.Action, entry.Action)
})
}
}
func TestAuthorizer_WrappedInternalErrors(t *testing.T) {
t.Parallel()
a := &Authorizer{
logger: log.NewLogger(log.WithOutput(io.Discard)),
}
queryErr := errors.New("query failed")
tx := &errorTx{queryErr: queryErr}
principalID := gid.New(gid.NilTenant, coredata.IdentityEntityType)
membershipID := gid.New(gid.NewTenantID(), coredata.MembershipEntityType)
sessionID := gid.New(gid.NilTenant, coredata.SessionEntityType)
resourceOrgID := gid.New(gid.NewTenantID(), coredata.OrganizationEntityType).String()
t.Run("load membership wraps load errors", func(t *testing.T) {
t.Parallel()
_, err := a.loadMembership(context.Background(), tx, principalID, resourceOrgID)
require.Error(t, err)
assert.ErrorContains(t, err, "cannot load active membership")
})
t.Run("get active child session wraps load errors", func(t *testing.T) {
t.Parallel()
_, err := a.getActiveChildSessionForMembership(
context.Background(),
tx,
sessionID,
membershipID,
)
require.Error(t, err)
assert.ErrorContains(t, err, "cannot load child session")
})
t.Run("check assumption wraps non-assumption errors", func(t *testing.T) {
t.Parallel()
err := a.checkAssumption(
context.Background(),
tx,
principalID,
&sessionID,
&coredata.Membership{ID: membershipID},
false,
)
require.Error(t, err)
assert.ErrorContains(t, err, "cannot get active child session for membership")
_, ok := errors.AsType[*ErrAssumptionRequired](err)
assert.False(t, ok)
})
t.Run("build principal attributes wraps load errors", func(t *testing.T) {
t.Parallel()
_, err := a.buildPrincipalAttributes(context.Background(), tx, principalID, nil)
require.Error(t, err)
assert.ErrorContains(t, err, "cannot load principal attributes")
})
t.Run("load resource attributes by type wraps load errors", func(t *testing.T) {
t.Parallel()
resourceID := gid.New(gid.NewTenantID(), coredata.FrameworkEntityType)
_, err := a.loadResourceAttributesByType(context.Background(), tx, []gid.GID{resourceID})
require.Error(t, err)
assert.ErrorContains(t, err, "cannot load batched resource attributes")
})
}
type errorRow struct {
err error
}
func (r *errorRow) Scan(...any) error {
return r.err
}
type errorTx struct {
queryErr error
}
var _ pg.Tx = (*errorTx)(nil)
func (tx *errorTx) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {
return pgconn.CommandTag{}, tx.queryErr
}
func (tx *errorTx) Query(context.Context, string, ...any) (pgx.Rows, error) {
return nil, tx.queryErr
}
func (tx *errorTx) QueryRow(context.Context, string, ...any) pgx.Row {
return &errorRow{err: tx.queryErr}
}
func (tx *errorTx) CopyFrom(context.Context, pgx.Identifier, []string, pgx.CopyFromSource) (int64, error) {
return 0, tx.queryErr
}
func (tx *errorTx) SendBatch(context.Context, *pgx.Batch) pgx.BatchResults {
return nil
}
func (tx *errorTx) Savepoint(context.Context, pg.ExecFunc[pg.Tx]) error {
return tx.queryErr
}