Documentation
¶
Overview ¶
Package privacy: engine implementation of the Service contract in service.go.
Layout:
policy.go policy data model, built-in policies, merge/validate/resolve requests.go DSR create/get/list/cancel (§2.9 grace, idempotency) consent.go append-only consent ledger + reconfirm scanner (§2.8, §4) destinations.go, holds.go management-plane CRUD pipeline.go erasure pipeline steps 100–1000 (§2.9) tasks.go webhook/connector delivery with HMAC signing (§3.2) outbox.go transactional outbox dispatcher (§2.5) retention.go retention scanner (§2.8) workers.go pollers
Package privacy is the compliance engine (project.md §2.8–§2.10). This file is the CONTRACT between the engine (implementer: agent C) and the HTTP layer (consumer: agent D). Do not modify without lead approval.
Index ¶
- Constants
- func ParsePIIFields(b []byte) (map[string]FieldHint, error)
- type AudienceMember
- type ConsentChange
- type ConsentSection
- type ConsentSegmentFilter
- type ConsentState
- type CreateDestinationInput
- type CreateHoldInput
- type CreateRequestInput
- type Destination
- type DestinationType
- type Duration
- type Engine
- func (e *Engine) CancelRequest(ctx context.Context, id string) (*Request, error)
- func (e *Engine) CreateDestination(ctx context.Context, in CreateDestinationInput) (*Destination, error)
- func (e *Engine) CreateHold(ctx context.Context, in CreateHoldInput) (*LegalHold, error)
- func (e *Engine) CreateRequest(ctx context.Context, in CreateRequestInput) (*Request, error)
- func (e *Engine) DeleteDestination(ctx context.Context, id string) error
- func (e *Engine) ExportConsentAudience(ctx context.Context, purpose string, p httpapi.ListParams) (httpapi.Page[AudienceMember], error)
- func (e *Engine) GetConsents(ctx context.Context, userID string) ([]ConsentState, error)
- func (e *Engine) GetDestination(ctx context.Context, id string) (*Destination, error)
- func (e *Engine) GetProfile(ctx context.Context, userID string, full bool) (*Profile, error)
- func (e *Engine) GetRequest(ctx context.Context, id string) (*Request, error)
- func (e *Engine) ListConsentStates(ctx context.Context, f ConsentSegmentFilter, p httpapi.ListParams) (httpapi.Page[SubjectConsent], error)
- func (e *Engine) ListDestinations(ctx context.Context, p httpapi.ListParams) (httpapi.Page[Destination], error)
- func (e *Engine) ListHolds(ctx context.Context, f HoldFilter, p httpapi.ListParams) (httpapi.Page[LegalHold], error)
- func (e *Engine) ListRequests(ctx context.Context, f RequestFilter, p httpapi.ListParams) (httpapi.Page[Request], error)
- func (e *Engine) PIIFieldDefs() map[string]FieldHint
- func (e *Engine) Policies() *PolicySet
- func (e *Engine) ReleaseHold(ctx context.Context, id, releasedBy string) (*LegalHold, error)
- func (e *Engine) RunWorkers(ctx context.Context)
- func (e *Engine) SearchUsers(ctx context.Context, q UserSearchQuery, p httpapi.ListParams) (httpapi.Page[UserMatch], error)
- func (e *Engine) UpdateConsent(ctx context.Context, userID string, ch ConsentChange) (*ConsentState, error)
- func (e *Engine) UpdateDestination(ctx context.Context, id string, enabled *bool, config map[string]any) (*Destination, error)
- func (e *Engine) UpdateProfile(ctx context.Context, userID string, set map[string]ProfileField, ...) (*Profile, error)
- type EngineDeps
- type ErasureAction
- type ErasureSection
- type Error
- type FieldHint
- type HoldFilter
- type LegalHold
- type Policy
- func (p *Policy) ActionFor(domain string, def ErasureAction) ErasureAction
- func (p *Policy) BasisFor(domain string) string
- func (p *Policy) GraceDays() int
- func (p *Policy) ManualReview() bool
- func (p *Policy) ReconfirmFor(purpose string) (Duration, bool)
- func (p *Policy) RequiredConsentKeys() []string
- func (p *Policy) RequiresConsent(purpose string) bool
- func (p *Policy) RetentionFor(domain string) []RetentionRule
- func (p *Policy) RetentionRules() []RetentionRule
- func (p *Policy) Snapshot() ([]byte, error)
- type PolicySet
- type Profile
- type ProfileField
- type ProfileView
- type Request
- type RequestFilter
- type RequestStatus
- type RequestType
- type RetentionRule
- type Service
- type SubjectConsent
- type UserMatch
- type UserSearchQuery
Constants ¶
const ( ConsentGrant = "GRANT" ConsentWithdraw = "WITHDRAW" ConsentReconfirmNotice = "RECONFIRM_NOTICE" )
Consent ledger actions (§4 — append-only ledger, not current state).
const ( EventUserDeleted = "user.deleted" EventReconfirmDue = "consent.reconfirm_due" )
Outbox event types (§2.5, §3.2).
const ( DomainCredential = "credential" DomainRefreshToken = "refresh-token" DomainSession = "session" DomainMFAFactor = "mfa-factor" DomainPasskey = "passkey" DomainOAuthIdentity = "oauth-identity" DomainExternalSystem = "external-system" DomainAuditLog = "audit-log" DomainSubjectKey = "subject-key" DomainAccount = "account" DomainConsentEvidence = "consent-evidence" // retention-only domain (no erasure step) )
Erasure domains, in pipeline order. The order values match §2.9.
const ( FromCreated = "created" FromErasure = "erasure" )
RetentionFrom is the clock the retention period is measured from.
const ( MatchAuthEmail = "AUTH_EMAIL" MatchAuthPhone = "AUTH_PHONE" MatchProfileField = "PROFILE_FIELD" )
UserMatch sources.
const ( TaskActionDelete = "DELETE" TaskActionReconfirm = "RECONFIRM_NOTICE" )
Task actions.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AudienceMember ¶
type AudienceMember struct {
UserID string `json:"user_id"`
Email string `json:"email"` // "" when the account has none
Phone string `json:"phone"` // "" when the account has none
}
AudienceMember is one recipient of a consent-based audience export: a subject whose latest ledger entry for the purpose is GRANT, joined with the contact identifiers from auth.users. Erased/deleted accounts are excluded.
type ConsentChange ¶
type ConsentSection ¶
type ConsentSection struct {
RequiredKeys []string `yaml:"required-keys" json:"required_keys,omitempty"`
Reconfirm map[string]string `yaml:"reconfirm" json:"reconfirm,omitempty"` // glob pattern -> ISO-8601
}
ConsentSection carries the consent knowledge of a policy.
type ConsentSegmentFilter ¶
ConsentSegmentFilter narrows ListConsentStates. Purpose "" means every purpose. ReconfirmDueBefore keeps only rows whose reconfirm notice is due before the given time (rows with no reconfirm schedule never match).
type ConsentState ¶
type CreateDestinationInput ¶
type CreateDestinationInput struct {
Type DestinationType
Name string
Config map[string]any
Secret string // webhook HMAC secret (저장은 hash/암호화, 응답 미노출)
}
type CreateHoldInput ¶
type CreateRequestInput ¶
type CreateRequestInput struct {
UserID string
Type RequestType
Immediate bool // 즉시 파기 경로 (§2.9): grace 생략, scheduled_at = now
IdempotencyKey string // optional
RequestedBy string // actor id (audit용)
}
type Destination ¶
type DestinationType ¶
type DestinationType string
const ( DestinationWebhook DestinationType = "WEBHOOK" DestinationConnector DestinationType = "CONNECTOR" )
type Duration ¶
Duration is an ISO-8601 duration (P3Y, P30D, PT12H...). Calendar components are kept separate from clock components so that "P3Y" means three calendar years rather than 3*365 days (§2.8 retention periods are legal periods).
func ParseISODuration ¶
ParseISODuration parses an ISO-8601 duration. Fractional and negative values are rejected: retention periods must be unambiguous.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine implements Service.
func NewEngine ¶
func NewEngine(d EngineDeps) (*Engine, error)
NewEngine validates dependencies and loads/validates the policy data. Invalid policy data is a startup failure (§2.8).
func (*Engine) CancelRequest ¶
CancelRequest withdraws a request that is still inside the grace period.
func (*Engine) CreateDestination ¶
func (e *Engine) CreateDestination(ctx context.Context, in CreateDestinationInput) (*Destination, error)
CreateDestination registers a delivery target. The HMAC secret is stored encrypted under the system KMS subject and never returned.
func (*Engine) CreateHold ¶
CreateHold places a legal hold. Holds gate the erasure pipeline, the retention scanner and restore-time replay (§2.9 triple gate).
func (*Engine) CreateRequest ¶
CreateRequest creates a data subject request (§2.9).
func (*Engine) DeleteDestination ¶
func (*Engine) ExportConsentAudience ¶
func (e *Engine) ExportConsentAudience(ctx context.Context, purpose string, p httpapi.ListParams) (httpapi.Page[AudienceMember], error)
ExportConsentAudience pages the granted segment of one purpose joined with auth.users contact identifiers, ordered by user_id. Deleted/erased accounts (deleted_at set, or no auth row) are excluded — an audience export must never resurrect an erased subject.
func (*Engine) GetConsents ¶
GetConsents projects the ledger into the current state per purpose and computes reconfirm_due from the subject's policy (§2.8 reconfirm).
func (*Engine) GetDestination ¶
func (*Engine) GetProfile ¶
GetProfile returns the subject's vault profile. full=false is the default projection: values are masked per field hint (§2.6). full=true reveals the raw values and is gated by the pii_reveal hook; the caller is responsible for the pii.reveal permission check and the PII_FULL_READ audit event.
func (*Engine) GetRequest ¶
GetRequest returns one request; a missing id is "not found" per api-conventions.
func (*Engine) ListConsentStates ¶
func (e *Engine) ListConsentStates(ctx context.Context, f ConsentSegmentFilter, p httpapi.ListParams) (httpapi.Page[SubjectConsent], error)
ListConsentStates pages the current consent state across all subjects, ordered by (user_id, purpose).
func (*Engine) ListDestinations ¶
func (e *Engine) ListDestinations(ctx context.Context, p httpapi.ListParams) (httpapi.Page[Destination], error)
func (*Engine) ListHolds ¶
func (e *Engine) ListHolds(ctx context.Context, f HoldFilter, p httpapi.ListParams) (httpapi.Page[LegalHold], error)
func (*Engine) ListRequests ¶
func (e *Engine) ListRequests(ctx context.Context, f RequestFilter, p httpapi.ListParams) (httpapi.Page[Request], error)
ListRequests pages requests newest-first, narrowed by the filter (status, type, subject, requested_at window — use-cases.md 제안 P3).
func (*Engine) PIIFieldDefs ¶
PIIFieldDefs exposes the instance's field definitions (nil = free-form).
func (*Engine) Policies ¶
Policies exposes the loaded policy set (read-only; used by tests and by the API layer to render effective policy).
func (*Engine) ReleaseHold ¶
ReleaseHold lifts a hold and resumes requests that the hold had parked (§2.9: "해제 시 보류된 요청이 자동으로 재개됩니다").
func (*Engine) RunWorkers ¶
RunWorkers starts the background pollers and blocks until ctx is done:
outbox dispatcher — account deletions and reconfirm notices (§2.5) pipeline runner — erasure steps 100–1000 (§2.9) task sender — webhook/connector delivery with retry + DLQ (§3.2) reconfirm scanner — consent reconfirmation notices (§2.8) retention scanner — retention periods / crypto-shred (§2.8)
func (*Engine) SearchUsers ¶
func (e *Engine) SearchUsers(ctx context.Context, q UserSearchQuery, p httpapi.ListParams) (httpapi.Page[UserMatch], error)
SearchUsers looks up subjects by exactly one criterion and pages the matches by user_id. Matches carry ids only: reading any value stays a separate, audited profile read.
func (*Engine) UpdateConsent ¶
func (e *Engine) UpdateConsent(ctx context.Context, userID string, ch ConsentChange) (*ConsentState, error)
UpdateConsent appends a GRANT/WITHDRAW event and returns the resulting state. Nothing is ever updated in place — the ledger is the record (§4).
func (*Engine) UpdateDestination ¶
func (e *Engine) UpdateDestination(ctx context.Context, id string, enabled *bool, config map[string]any) (*Destination, error)
UpdateDestination patches enabled and/or config (config is replaced whole).
func (*Engine) UpdateProfile ¶
func (e *Engine) UpdateProfile(ctx context.Context, userID string, set map[string]ProfileField, remove []string) (*Profile, error)
UpdateProfile upserts the keys in set, deletes the keys in remove and returns the masked projection of the result. Read-modify-write: the document is decrypted, patched and re-sealed. An empty result deletes the row.
type EngineDeps ¶
type EngineDeps struct {
Pool *pgxpool.Pool
KMS ports.KMS
Hooks *hooks.Registry
Clock ports.Clock
PolicyYAML []byte
// PIIFieldsYAML pins the instance's PII field definitions:
//
// pii-fields:
// email: {hint: EMAIL}
// full_name: {hint: NAME}
//
// When set, profile writes may only use the defined keys and the stored
// masking hint always comes from the definition. nil = free-form fields
// (the single-instance default).
PIIFieldsYAML []byte
Connectors map[string]ports.Connector
TombstoneKey []byte
}
EngineDeps is the injection surface of the compliance engine. Every field is instance-scoped: one Engine serves exactly one instance (one database), and internal/instances constructs one Engine per instance id.
type ErasureAction ¶
type ErasureAction string
const ( ActionDelete ErasureAction = "DELETE" ActionAnonymize ErasureAction = "ANONYMIZE" ActionCryptoShred ErasureAction = "CRYPTO_SHRED" ActionKeep ErasureAction = "KEEP" )
type ErasureSection ¶
type ErasureSection struct {
GracePeriodDays int `yaml:"grace-period-days" json:"grace_period_days"`
ManualReview bool `yaml:"manual-review" json:"manual_review"`
Domains map[string]ErasureAction `yaml:"domains" json:"domains,omitempty"`
}
ErasureSection overrides pipeline behaviour for a policy.
type Error ¶
type Error string
const ( ErrInvalidInput Error = "privacy: invalid input" // ErrUnsupported marks contract surface that wave 1 does not implement // (EXPORT request pipeline). Map to 501/validation_failed. ErrUnsupported Error = "privacy: unsupported operation" )
Additional sentinel errors. service.go (the contract) defines ErrNotFound, ErrConflict, ErrIdempotencyReplay, ErrLegalHold and ErrPolicyViolation; the engine needs one more for malformed input so the API layer can map it to httpapi.CodeValidationFailed (422) instead of a 500.
const ( ErrNotFound Error = "privacy: not found" ErrConflict Error = "privacy: conflict" // 진행 중 요청 중복 등 ErrIdempotencyReplay Error = "privacy: idempotency conflict" // 같은 키, 다른 body ErrLegalHold Error = "privacy: legal hold active" ErrPolicyViolation Error = "privacy: policy violation" // required consent 위반 등 )
type HoldFilter ¶
HoldFilter narrows ListHolds. Active=true keeps un-released holds only, Active=false released ones only; nil returns both.
type Policy ¶
type Policy struct {
ID string `yaml:"-" json:"id"`
Erasure *ErasureSection `yaml:"erasure" json:"erasure,omitempty"`
Retention *[]RetentionRule `yaml:"retention" json:"retention,omitempty"`
Consent *ConsentSection `yaml:"consent" json:"consent,omitempty"`
}
Policy is one compliance code (kr, gdpr, hipaa, custom...). Sections are pointers so "absent" (inherit built-in) is distinguishable from "provided but empty" (replace built-in with nothing) — see SECTION-REPLACE in §2.8.
func (*Policy) ActionFor ¶
func (p *Policy) ActionFor(domain string, def ErasureAction) ErasureAction
ActionFor returns the effective action for an erasure domain: the policy override if present, otherwise the step's default action.
func (*Policy) BasisFor ¶
BasisFor returns the evidence string recorded in destruction_logs for a domain (retention basis of the same domain, if the policy declares one).
func (*Policy) ManualReview ¶
func (*Policy) ReconfirmFor ¶
ReconfirmFor returns the reconfirmation period for a purpose. Patterns are globs ("marketing.*"); the most specific (longest) matching pattern wins.
func (*Policy) RequiredConsentKeys ¶
func (*Policy) RequiresConsent ¶
func (*Policy) RetentionFor ¶
func (p *Policy) RetentionFor(domain string) []RetentionRule
RetentionFor returns the retention rules that apply to a domain.
func (*Policy) RetentionRules ¶
func (p *Policy) RetentionRules() []RetentionRule
RetentionRules returns every retention rule of the policy.
type PolicySet ¶
PolicySet is the loaded, validated and merged policy data.
func LoadPolicies ¶
LoadPolicies parses the built-in policies, merges userYAML over them and validates the result. Unknown domains/actions are a startup error (§2.8: "런타임에 조용히 무시 금지").
type Profile ¶
type Profile struct {
UserID string `json:"user_id"`
Fields map[string]ProfileField `json:"fields"`
View ProfileView `json:"view"`
UpdatedAt *time.Time `json:"updated_at"`
}
Profile is the decrypted projection of dilion_pii.user_profiles. Fields is an arbitrary key→field map (custom PII fields supported).
type ProfileField ¶
type ProfileView ¶
type ProfileView string
const ( ViewMasked ProfileView = "MASKED" ViewFull ProfileView = "FULL" )
type Request ¶
type Request struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Type RequestType `json:"type"`
Status RequestStatus `json:"status"`
PolicyID string `json:"policy_id"`
ScheduledAt time.Time `json:"scheduled_at"`
RequestedAt time.Time `json:"requested_at"`
CompletedAt *time.Time `json:"completed_at"`
}
type RequestFilter ¶
type RequestFilter struct {
Status *RequestStatus
Type *RequestType
UserID *string
RequestedAfter *time.Time // requested_at >= (inclusive)
RequestedBefore *time.Time // requested_at < (exclusive)
}
RequestFilter narrows ListRequests. Nil fields mean "no filter".
type RequestStatus ¶
type RequestStatus string
const ( StatusRequested RequestStatus = "REQUESTED" StatusProcessing RequestStatus = "PROCESSING" StatusDone RequestStatus = "DONE" StatusManualReview RequestStatus = "MANUAL_REVIEW" StatusCanceled RequestStatus = "CANCELED" )
type RequestType ¶
type RequestType string
const ( RequestDeletion RequestType = "DELETION" RequestExport RequestType = "EXPORT" RequestConsentWithdrawal RequestType = "CONSENT_WITHDRAWAL" )
type RetentionRule ¶
type RetentionRule struct {
Domain string `yaml:"domain" json:"domain"`
Period string `yaml:"period" json:"period"` // ISO-8601 duration
From string `yaml:"from" json:"from"` // created | erasure
Action ErasureAction `yaml:"action" json:"action"`
Basis string `yaml:"basis" json:"basis,omitempty"` // evidence string, never used in logic
}
RetentionRule is one row of the policy's retention table.
type Service ¶
type Service interface {
// Requests
CreateRequest(ctx context.Context, in CreateRequestInput) (*Request, error)
GetRequest(ctx context.Context, id string) (*Request, error)
ListRequests(ctx context.Context, f RequestFilter, p httpapi.ListParams) (httpapi.Page[Request], error)
CancelRequest(ctx context.Context, id string) (*Request, error) // REQUESTED(유예 중)만 가능
// Consents (user 단위 현재 상태 projection + append-only ledger 기록)
GetConsents(ctx context.Context, userID string) ([]ConsentState, error)
UpdateConsent(ctx context.Context, userID string, ch ConsentChange) (*ConsentState, error)
// ListConsentStates is the cross-user segment projection ("who currently
// grants marketing?", use-cases.md P1). Pages by (user_id, purpose).
ListConsentStates(ctx context.Context, f ConsentSegmentFilter, p httpapi.ListParams) (httpapi.Page[SubjectConsent], error)
// ExportConsentAudience joins the granted segment of one purpose with
// auth.users contact identifiers. The caller is responsible for the
// pii.export permission, the mandatory reason and the audit event.
ExportConsentAudience(ctx context.Context, purpose string, p httpapi.ListParams) (httpapi.Page[AudienceMember], error)
// SearchUsers is an exact-match lookup by auth email/phone or by a vault
// profile field (blind index). Results carry ids only, never field values.
SearchUsers(ctx context.Context, q UserSearchQuery, p httpapi.ListParams) (httpapi.Page[UserMatch], error)
// Destinations
CreateDestination(ctx context.Context, in CreateDestinationInput) (*Destination, error)
GetDestination(ctx context.Context, id string) (*Destination, error)
ListDestinations(ctx context.Context, p httpapi.ListParams) (httpapi.Page[Destination], error)
UpdateDestination(ctx context.Context, id string, enabled *bool, config map[string]any) (*Destination, error)
DeleteDestination(ctx context.Context, id string) error
// PII Profile (custom field 지원; full=false는 hint 기반 masked 프로젝션.
// full=true는 호출자가 pii.reveal 권한·사유·PII_FULL_READ 감사를 책임진다.)
GetProfile(ctx context.Context, userID string, full bool) (*Profile, error)
// UpdateProfile: set은 upsert, remove는 키 삭제. masked 프로젝션을 반환.
UpdateProfile(ctx context.Context, userID string, set map[string]ProfileField, remove []string) (*Profile, error)
// Legal holds (§2.9)
CreateHold(ctx context.Context, in CreateHoldInput) (*LegalHold, error)
ReleaseHold(ctx context.Context, id, releasedBy string) (*LegalHold, error)
ListHolds(ctx context.Context, f HoldFilter, p httpapi.ListParams) (httpapi.Page[LegalHold], error)
}
type SubjectConsent ¶
type SubjectConsent struct {
UserID string `json:"user_id"`
ConsentState
}
SubjectConsent is one row of the cross-user consent segment projection (use-cases.md 제안 P1): the current state of one purpose for one subject.
type UserMatch ¶
type UserMatch struct {
UserID string `json:"user_id"`
Source string `json:"source"` // AUTH_EMAIL | AUTH_PHONE | PROFILE_FIELD
FieldKey string `json:"field_key"` // set for PROFILE_FIELD matches
}
UserMatch is one search hit. It carries no field values — the caller follows up with the masked profile (or a privileged reveal) as a separate, audited read.
type UserSearchQuery ¶
UserSearchQuery is an exact-match user lookup (use-cases.md 제안 P4). Exactly one criterion must be set: Email, Phone, or FieldKey+FieldValue (a vault profile field, matched via the blind search index).