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>
345 lines
7.8 KiB
Go
345 lines
7.8 KiB
Go
// Copyright (c) 2025-2026 Probo Inc <hello@getprobo.com>.
|
|
//
|
|
// Permission to use, copy, modify, and/or distribute this software for any
|
|
// purpose with or without fee is hereby granted, provided that the above
|
|
// copyright notice and this permission notice appear in all copies.
|
|
//
|
|
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
// PERFORMANCE OF THIS SOFTWARE.
|
|
|
|
package coredata
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"go.gearno.de/kit/pg"
|
|
"go.probo.inc/probo/pkg/gid"
|
|
"go.probo.inc/probo/pkg/iam/policy"
|
|
"go.probo.inc/probo/pkg/mail"
|
|
"go.probo.inc/probo/pkg/page"
|
|
)
|
|
|
|
type (
|
|
Identity struct {
|
|
ID gid.GID `db:"id"`
|
|
EmailAddress mail.Addr `db:"email_address"`
|
|
FullName string `db:"full_name"`
|
|
HashedPassword []byte `db:"hashed_password"`
|
|
EmailAddressVerified bool `db:"email_address_verified"`
|
|
SAMLSubject *string `db:"saml_subject"`
|
|
CreatedAt time.Time `db:"created_at"`
|
|
UpdatedAt time.Time `db:"updated_at"`
|
|
}
|
|
|
|
Identities []*Identity
|
|
)
|
|
|
|
func (i Identity) CursorKey(orderBy IdentityOrderField) page.CursorKey {
|
|
switch orderBy {
|
|
case IdentityOrderFieldCreatedAt:
|
|
return page.NewCursorKey(i.ID, i.CreatedAt)
|
|
}
|
|
|
|
panic(fmt.Sprintf("unsupported order by: %s", orderBy))
|
|
}
|
|
|
|
// Tenant id scope is not applied because we want to access identities across all tenants for authentication purposes.
|
|
func (i *Identity) LoadByEmail(
|
|
ctx context.Context,
|
|
conn pg.Querier,
|
|
email mail.Addr,
|
|
) error {
|
|
q := `
|
|
SELECT
|
|
id,
|
|
email_address,
|
|
full_name,
|
|
hashed_password,
|
|
email_address_verified,
|
|
saml_subject,
|
|
created_at,
|
|
updated_at
|
|
FROM
|
|
identities
|
|
WHERE
|
|
email_address = @identity_email
|
|
LIMIT 1;
|
|
`
|
|
|
|
args := pgx.StrictNamedArgs{"identity_email": email}
|
|
|
|
rows, err := conn.Query(ctx, q, args)
|
|
if err != nil {
|
|
return fmt.Errorf("cannot query identity: %w", err)
|
|
}
|
|
|
|
identity, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Identity])
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return ErrResourceNotFound
|
|
}
|
|
|
|
return fmt.Errorf("cannot collect identity: %w", err)
|
|
}
|
|
|
|
*i = identity
|
|
|
|
return nil
|
|
}
|
|
|
|
// Tenant id scope is not applied because we want to access identities across all tenants for authentication purposes.
|
|
func (i *Identity) LoadByID(
|
|
ctx context.Context,
|
|
conn pg.Querier,
|
|
identityID gid.GID,
|
|
) error {
|
|
q := `
|
|
SELECT
|
|
id,
|
|
email_address,
|
|
full_name,
|
|
hashed_password,
|
|
email_address_verified,
|
|
saml_subject,
|
|
created_at,
|
|
updated_at
|
|
FROM
|
|
identities
|
|
WHERE
|
|
id = @identity_id
|
|
LIMIT 1;
|
|
`
|
|
|
|
args := pgx.StrictNamedArgs{"identity_id": identityID}
|
|
|
|
rows, err := conn.Query(ctx, q, args)
|
|
if err != nil {
|
|
return fmt.Errorf("cannot query identity: %w", err)
|
|
}
|
|
|
|
identity, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Identity])
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return ErrResourceNotFound
|
|
}
|
|
|
|
return fmt.Errorf("cannot collect identity: %w", err)
|
|
}
|
|
|
|
*i = identity
|
|
|
|
return nil
|
|
}
|
|
|
|
// AuthorizationAttributes loads the minimal authorization attributes for policy condition evaluation.
|
|
// It is intentionally lightweight and does not populate the Identity struct.
|
|
func (i *Identity) AuthorizationAttributes(
|
|
ctx context.Context,
|
|
conn pg.Querier,
|
|
resourceIDs []gid.GID,
|
|
) (policy.AttributesByID, error) {
|
|
q := `
|
|
SELECT
|
|
id,
|
|
email_address
|
|
FROM
|
|
identities
|
|
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 identity authorization attributes: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
attrsByID := make(policy.AttributesByID, len(resourceIDs))
|
|
for rows.Next() {
|
|
var (
|
|
id gid.GID
|
|
emailAddress string
|
|
)
|
|
|
|
if err := rows.Scan(&id, &emailAddress); err != nil {
|
|
return nil, fmt.Errorf("cannot scan identity authorization attributes: %w", err)
|
|
}
|
|
|
|
attrsByID[id] = policy.Attributes{
|
|
"identity_id": id.String(),
|
|
"email": emailAddress,
|
|
}
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("cannot iterate identity authorization attributes: %w", err)
|
|
}
|
|
|
|
return attrsByID, nil
|
|
}
|
|
|
|
func (i *Identity) Insert(
|
|
ctx context.Context,
|
|
conn pg.Tx,
|
|
) error {
|
|
q := `
|
|
INSERT INTO
|
|
identities (id, email_address, full_name, hashed_password, email_address_verified, saml_subject, created_at, updated_at)
|
|
VALUES (
|
|
@identity_id,
|
|
@email_address,
|
|
@full_name,
|
|
@hashed_password,
|
|
@email_address_verified,
|
|
@saml_subject,
|
|
@created_at,
|
|
@updated_at
|
|
)
|
|
`
|
|
|
|
args := pgx.StrictNamedArgs{
|
|
"identity_id": i.ID,
|
|
"email_address": i.EmailAddress,
|
|
"full_name": i.FullName,
|
|
"hashed_password": i.HashedPassword,
|
|
"saml_subject": i.SAMLSubject,
|
|
"created_at": i.CreatedAt,
|
|
"updated_at": i.UpdatedAt,
|
|
"email_address_verified": i.EmailAddressVerified,
|
|
}
|
|
|
|
_, err := conn.Exec(ctx, q, args)
|
|
if err != nil {
|
|
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
|
if pgErr.Code == "23505" && strings.Contains(pgErr.ConstraintName, "email_address") {
|
|
return ErrResourceAlreadyExists
|
|
}
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (i *Identity) Update(ctx context.Context, conn pg.Tx) error {
|
|
q := `
|
|
UPDATE
|
|
identities
|
|
SET
|
|
email_address = @email_address,
|
|
full_name = @full_name,
|
|
email_address_verified = @email_address_verified,
|
|
saml_subject = @saml_subject,
|
|
hashed_password = @hashed_password,
|
|
updated_at = @updated_at
|
|
WHERE
|
|
id = @identity_id
|
|
`
|
|
|
|
args := pgx.StrictNamedArgs{
|
|
"identity_id": i.ID,
|
|
"email_address": i.EmailAddress,
|
|
"full_name": i.FullName,
|
|
"email_address_verified": i.EmailAddressVerified,
|
|
"saml_subject": i.SAMLSubject,
|
|
"updated_at": i.UpdatedAt,
|
|
"hashed_password": i.HashedPassword,
|
|
}
|
|
|
|
result, err := conn.Exec(ctx, q, args)
|
|
if err != nil {
|
|
return fmt.Errorf("cannot update identity: %w", err)
|
|
}
|
|
|
|
if result.RowsAffected() == 0 {
|
|
return ErrResourceNotFound
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// LoadBySAMLSubject loads an identity by their SAML subject (NameID)
|
|
func (i *Identity) LoadBySAMLSubject(
|
|
ctx context.Context,
|
|
conn pg.Querier,
|
|
samlSubject string,
|
|
) error {
|
|
q := `
|
|
SELECT
|
|
id,
|
|
email_address,
|
|
full_name,
|
|
hashed_password,
|
|
email_address_verified,
|
|
saml_subject,
|
|
created_at,
|
|
updated_at
|
|
FROM
|
|
identities
|
|
WHERE
|
|
saml_subject = @saml_subject
|
|
LIMIT 1;
|
|
`
|
|
|
|
args := pgx.StrictNamedArgs{"saml_subject": samlSubject}
|
|
|
|
rows, err := conn.Query(ctx, q, args)
|
|
if err != nil {
|
|
return fmt.Errorf("cannot query identity by SAML subject: %w", err)
|
|
}
|
|
|
|
identity, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Identity])
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return ErrResourceNotFound
|
|
}
|
|
|
|
return fmt.Errorf("cannot collect identity: %w", err)
|
|
}
|
|
|
|
*i = identity
|
|
|
|
return nil
|
|
}
|
|
|
|
func (i *Identity) CountMemberships(
|
|
ctx context.Context,
|
|
conn pg.Querier,
|
|
) (int, error) {
|
|
q := `
|
|
SELECT
|
|
COUNT(*)
|
|
FROM
|
|
iam_memberships
|
|
WHERE
|
|
identity_id = @identity_id
|
|
`
|
|
|
|
args := pgx.StrictNamedArgs{"identity_id": i.ID}
|
|
|
|
var count int
|
|
|
|
err := conn.QueryRow(ctx, q, args).Scan(&count)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("cannot count identity memberships: %w", err)
|
|
}
|
|
|
|
return count, nil
|
|
}
|