iam

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package iam implements the management-plane RBAC of project.md §2.11: flat permission strings bundled into roles, history-preserving role assignments (grant/revoke rows are never deleted — 안전성 확보조치 기준 제5조), scoped API keys, and the default Authorizer.

The Authorizer only decides. Audit logging and masked-by-default projections are enforced by callers (internal/api) regardless of which Authorizer is installed.

Index

Constants

View Source
const (
	ActorTypeAdmin  = "admin"
	ActorTypeAPIKey = "api_key"
	// ActorTypeUser is a regular end-user access token (`role=authenticated`)
	// acting on the management plane. Its authority comes exclusively from
	// role_assignments keyed by the user UUID (§2.11, deny-by-default).
	ActorTypeUser        = "user"
	ActorTypeServiceRole = "service_role"
)

Actor types (ports.Actor.Type).

View Source
const (
	PermUsersRead = "users.read"
	PermPIIRead   = "pii.read"
	PermPIIReveal = "pii.reveal"
	PermPIIExport = "pii.export"
	// PermPIIWrite guards mutation of a subject's stored personal data
	// (§5.2 "개인정보 수정"). Seeded by migration 0302.
	PermPIIWrite = "pii.write"
	// PermConsentsWrite guards recording a consent change (ledger append). It
	// is deliberately separate from privacy.requests.manage so a signup-flow
	// API key can record consent without holding DSR authority. Seeded by
	// migration 0304.
	PermConsentsWrite         = "consents.write"
	PermPrivacyRequestsManage = "privacy.requests.manage"
	PermHoldsManage           = "holds.manage"
	PermPoliciesManage        = "policies.manage"
	PermDestinationsManage    = "destinations.manage"
	PermKeysManage            = "keys.manage"
	// PermRolesManage guards defining roles and permissions and granting or
	// revoking role assignments. It was split from keys.manage (migration
	// 0305) so issuing API keys and administering who holds which role are
	// separate duties. Either way a caller can only grant what it holds
	// itself (internal/api grantCeiling).
	PermRolesManage = "roles.manage"
	PermAuditRead   = "audit.read"
	// PermUsersAdmin authorises the Supabase-compatible admin surface
	// (/auth/v1/admin/*) for a regular user access token. Seeded by migration
	// 0303 and bundled into the builtin `owner` role only.
	PermUsersAdmin = "users.admin"
	// PermAuthSettingsManage guards the instance's auth configuration kept
	// in its database: auth hooks, custom OAuth/OIDC providers, SSO
	// providers and OAuth server clients. Any of them reaches every account
	// (a send_email hook reads every OTP; a provider can sign in as anyone
	// it names), so it is held by the builtin owner role only and cannot be
	// put in a custom role or an API key (OwnerOnlyPermissions). Seeded by
	// migration 0306.
	PermAuthSettingsManage = "auth.settings.manage"
)

Builtin permissions (§2.11). Un-namespaced names are reserved: custom permissions must be namespaced and may not collide with these.

View Source
const (
	RoleViewer         = "role_00000000000000000000000000000001"
	RoleSupport        = "role_00000000000000000000000000000002"
	RolePrivacyOfficer = "role_00000000000000000000000000000003"
	RoleSecurityAdmin  = "role_00000000000000000000000000000004"
	RoleOwner          = "role_00000000000000000000000000000005"
)

Builtin role ids seeded by migration 0300.

View Source
const ActorTypeUnknown = "unknown"

ActorTypeUnknown marks an actor id that matches no user and no API key.

View Source
const RoleAuthenticated = "authenticated"

RoleAuthenticated is the Supabase JWT `role` claim of a regular signed-in user. It mirrors auth.RoleAuthenticated (the packages must not import each other).

View Source
const TokenPrefix = "dk_"

TokenPrefix is the scoped API key prefix (docs/api-conventions.md).

Variables

BuiltinPermissions is the authoritative list seeded by migrations 0300 (all but pii.write), 0302 (pii.write), 0303 (users.admin), 0304 (consents.write) and 0305 (roles.manage).

View Source
var OwnerOnlyPermissions = []string{PermAuthSettingsManage}

OwnerOnlyPermissions are held by the builtin owner role alone: they cannot be bundled into a custom role or scoped into an API key.

Functions

func HashToken

func HashToken(token string) []byte

HashToken returns the stored representation of a token.

func NewAuthorizer

func NewAuthorizer(pool *pgxpool.Pool) ports.Authorizer

NewAuthorizer returns the builtin RBAC Authorizer (§2.11): deny-by-default, decided from active role assignments plus (for API key actors) the key's own scopes. It decides only — callers still audit the decision and apply masked-by-default projections.

The pool is fixed: every decision is made against it. Multi-instance deployments use NewAuthorizerFor instead, which resolves the pool of the instance selected on the request context.

func NewAuthorizerFor

func NewAuthorizerFor(pools PoolFunc) ports.Authorizer

NewAuthorizerFor returns the builtin RBAC Authorizer over a per-request pool provider (internal/instances.Registry.Pool).

func NewToken

func NewToken() string

NewToken mints a `dk_<48 url-safe random>` token. The plaintext token is returned to the caller exactly once; only SHA-256(token) is persisted.

func UserActorIDs added in v0.0.5

func UserActorIDs(details map[string]ActorDetail, ids []string) []string

UserActorIDs is the subset of ids that name a data subject, which is what an access record's subject manifest may contain (§5.3). Order follows ids and duplicates are collapsed.

func ValidTokenFormat

func ValidTokenFormat(token string) bool

ValidTokenFormat reports whether a string looks like a Dilion API key.

func ValidateCustomPermission

func ValidateCustomPermission(name string) error

ValidateCustomPermission enforces §2.11: custom permissions must be namespaced and must not collide with a builtin (un-namespaced) permission.

Types

type APIKey

type APIKey struct {
	ID         string
	Name       *string
	Scopes     []string
	CreatedAt  time.Time
	CreatedBy  *string
	ExpiresAt  *time.Time
	RevokedAt  *time.Time
	LastUsedAt *time.Time
}

func (APIKey) Active

func (k APIKey) Active(now time.Time) bool

Active reports whether the key may still authenticate at time now.

type ActorDetail added in v0.0.5

type ActorDetail struct {
	ActorID string
	// Type is ActorTypeUser, ActorTypeAPIKey, or ActorTypeUnknown when the id
	// resolves to neither — a grant to an actor that no longer exists, which is
	// exactly what a recertification review needs to see.
	Type string

	CreatedAt *time.Time

	// User members.
	LastSignInAt *time.Time
	BannedUntil  *time.Time
	DeletedAt    *time.Time

	// API key member.
	RevokedAt *time.Time
}

ActorDetail is the non-PII operational view of one actor. Which members are populated depends on Type; the rest stay nil.

func (ActorDetail) Active added in v0.0.5

func (d ActorDetail) Active(t time.Time) bool

Active reports whether the actor can still exercise the grant at t. An unknown actor is never active.

type Assignment

type Assignment struct {
	ID        int64
	ActorID   string
	RoleID    string
	GrantedBy *string
	GrantedAt time.Time
	RevokedBy *string
	RevokedAt *time.Time
}

type AssignmentFilter

type AssignmentFilter struct {
	RoleID         string
	ActorID        string
	IncludeRevoked bool // history view (권한 이력 = 컴플라이언스 데이터)
}

AssignmentFilter narrows ListAssignments. Zero value = every active assignment.

type Error

type Error string
const (
	ErrNotFound        Error = "iam: not found"
	ErrConflict        Error = "iam: conflict"
	ErrInvalid         Error = "iam: invalid argument"
	ErrUnauthenticated Error = "iam: invalid credentials"
	ErrBuiltin         Error = "iam: builtin object is immutable"
)

func (Error) Error

func (e Error) Error() string

type Holder

type Holder struct {
	ActorID   string
	RoleID    string
	RoleName  string
	GrantedBy *string
	GrantedAt time.Time
}

Holder is one row of the CC6.3 recertification report: an actor currently holding a permission, together with the grant metadata that justifies it.

type Permission

type Permission struct {
	Name      string
	Builtin   bool
	CreatedAt time.Time
}

type PoolFunc

type PoolFunc func(context.Context) (*pgxpool.Pool, error)

PoolFunc resolves the database pool for a request. It is structurally identical to instances.PoolFunc, which is what production wires in; the type is declared locally so this package stays free of an instances import.

func StaticPool

func StaticPool(pool *pgxpool.Pool) PoolFunc

StaticPool is the single-instance PoolFunc: it always answers with pool. A nil pool yields an error at use time (spec generation constructs services with a nil pool and never calls them).

type Role

type Role struct {
	ID          string
	Name        string
	Permissions []string
	Builtin     bool
	CreatedAt   time.Time
}

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the RBAC + API key store. It is safe for concurrent use.

func New

func New(pool *pgxpool.Pool) *Service

New builds the service over one fixed pool (single-instance default).

func NewFor

func NewFor(pools PoolFunc) *Service

NewFor builds the service over a per-request pool provider, so each call is served by the database of the instance selected on the context.

func (*Service) ActorDetails added in v0.0.5

func (s *Service) ActorDetails(ctx context.Context, ids []string) (map[string]ActorDetail, error)

ActorDetails resolves actor ids to their operational view, keyed by actor id. Ids that resolve to nothing come back with Type ActorTypeUnknown rather than being dropped, so a caller can always pair every id it asked about with an answer. Duplicate ids are collapsed. An empty input is not an error.

Two queries total, regardless of how many actors are asked about: one over auth.users for the id shaped like a UUID, one over the API key table for the rest.

func (*Service) CreateKey

func (s *Service) CreateKey(ctx context.Context, name string, scopes []string, expires *time.Time) (string, APIKey, error)

CreateKey issues a scoped API key (§2.11 "Machine key"). The returned token is the only time the plaintext is available.

func (*Service) CreateKeyBy

func (s *Service) CreateKeyBy(ctx context.Context, name string, scopes []string, expires *time.Time, createdBy, createdByType string) (string, APIKey, error)

CreateKeyBy is CreateKey with the granting actor recorded. createdByType is the creator's actor type: a key issued by a user (ActorTypeUser) never holds more than that user currently does.

func (*Service) CreatePermission

func (s *Service) CreatePermission(ctx context.Context, name string) (Permission, error)

CreatePermission registers a custom (namespaced) permission.

func (*Service) CreateRole

func (s *Service) CreateRole(ctx context.Context, name string, permissions []string) (Role, error)

CreateRole registers a custom role. Every listed permission must already be registered (builtin seed or a custom permission).

func (*Service) GetAssignment added in v0.0.5

func (s *Service) GetAssignment(ctx context.Context, id int64) (Assignment, error)

GetAssignment reads one assignment, active or revoked.

func (*Service) GetKey added in v0.0.5

func (s *Service) GetKey(ctx context.Context, keyID string) (APIKey, error)

GetKey reads one key, active or not.

func (*Service) GetRole

func (s *Service) GetRole(ctx context.Context, roleID string) (Role, error)

func (*Service) GrantRole

func (s *Service) GrantRole(ctx context.Context, roleID, actorID, grantedBy string) (Assignment, error)

GrantRole records a new active assignment. Re-granting an already active (actor, role) pair is a conflict — the history table must stay unambiguous.

func (*Service) ListAssignments

func (*Service) ListKeys

func (s *Service) ListKeys(ctx context.Context, p httpapi.ListParams) (httpapi.Page[APIKey], error)

func (*Service) ListPermissions

func (s *Service) ListPermissions(ctx context.Context, p httpapi.ListParams) (httpapi.Page[Permission], error)

func (*Service) ListRoles

func (s *Service) ListRoles(ctx context.Context, p httpapi.ListParams) (httpapi.Page[Role], error)

func (*Service) Recertification

func (s *Service) Recertification(ctx context.Context, permission string) ([]Holder, error)

Recertification answers "who currently holds permission X, and on what grant basis" (CC6.3 recertification report, §2.11).

func (*Service) RevokeAssignment

func (s *Service) RevokeAssignment(ctx context.Context, id int64, revokedBy string) (Assignment, error)

RevokeAssignment marks an assignment revoked. The row is preserved.

func (*Service) RevokeKey

func (s *Service) RevokeKey(ctx context.Context, keyID, revokedBy string) (APIKey, error)

RevokeKey revokes a key. Idempotency is intentionally not offered: revoking an already revoked key is a conflict so operators notice stale automation.

func (*Service) UpdateRole added in v0.0.5

func (s *Service) UpdateRole(ctx context.Context, roleID string, permissions []string) (Role, error)

UpdateRole replaces a custom role's permission set. Builtin roles are immutable: their contents are what the documentation and every deployment rely on (§2.11).

func (*Service) VerifyKey

func (s *Service) VerifyKey(ctx context.Context, token string) (*ports.Actor, []string, error)

VerifyKey authenticates a plaintext API key token. It returns the actor and the key's scopes, and bumps last_used_at. Unknown / revoked / expired keys all fail with ErrUnauthenticated (no oracle about which).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL