package governance import ( "context" "errors" "fmt" "strings" "time" "unicode" "unicode/utf8" "github.com/samcharles93/archie-core/internal/platform/stableid" ) // OrgID and WorkspaceID identify an organisation and a workspace. type ( OrgID string WorkspaceID string ) // DefaultOrgID and DefaultWorkspaceID identify the default operating // organisation and workspace. const ( DefaultOrgID OrgID = "org-sys" DefaultWorkspaceID WorkspaceID = "default" ) var ( ErrInvalidRole = errors.New("org: invalid role") ErrInvalidOrg = errors.New("org: invalid org") ErrInvalidMembership = errors.New("org: invalid membership") ErrInvalidWorkspace = errors.New("org: invalid workspace") ErrInvalidAssignment = errors.New("org: invalid agent assignment") ErrOrgNotFound = errors.New("org: org not found") ErrWorkspaceNotFound = errors.New("org: workspace not found") ErrOrgExists = errors.New("org: org already exists") ErrWorkspaceExists = errors.New("org: workspace already exists") ErrMembershipExists = errors.New("org: membership already exists") ErrLastOwner = errors.New("org: this is the organisation's last active owner; make another member owner first") ErrNotOwner = errors.New("org: only an owner may change this") ErrNameChanged = errors.New("org: the name changed after it was read") ) // MaxNameLength bounds a display name so it stays a label, not a paragraph. const MaxNameLength = 80 // ValidateName trims a display name and rejects one that is blank, longer than // MaxNameLength, or carries control or format characters: a name is rendered // as text, and a bidi override could make it read as a different name. func ValidateName(name string) (string, error) { trimmed := strings.TrimSpace(name) switch { case trimmed == "": return "", errors.New("a name is required") case utf8.RuneCountInString(trimmed) > MaxNameLength: return "", fmt.Errorf("a name is at most %d characters", MaxNameLength) } for _, r := range trimmed { if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { return "", errors.New("a name contains a character that is not allowed") } } return trimmed, nil } // Role is a member's role in an organisation or one of its workspaces. type Role string // Default role names used by the starter org policies seeded at org creation. const ( RoleOwner Role = "owner" RoleAdmin Role = "admin" RoleDeveloper Role = "developer" RoleViewer Role = "viewer" // RoleWorkload is the role of the principal background work acts as. No // member holds it. RoleWorkload Role = "workload" ) // Validate reports whether r is a valid role identifier. func (r Role) Validate() error { if !stableid.Valid(string(r)) { return fmt.Errorf("%w: %q (must match %s)", ErrInvalidRole, r, stableid.Pattern) } return nil } // Org is a tenant. Version is the revision a rename is guarded by. type Org struct { ID OrgID `json:"id"` Name string `json:"name"` Version int64 `json:"version"` } // Validate requires an org to have an ID and a well-formed name. func (o Org) Validate() error { if o.ID == "" { return fmt.Errorf("%w: an ID is required", ErrInvalidOrg) } if strings.Contains(string(o.ID), "/") { return fmt.Errorf("%w: the ID must not contain a slash", ErrInvalidOrg) } if _, err := ValidateName(o.Name); err != nil { return fmt.Errorf("%w: %w", ErrInvalidOrg, err) } return nil } // Workspace divides an organisation. Environment is a free-form attribute // policies can test, and Version is the revision a rename is guarded by. type Workspace struct { ID WorkspaceID `json:"id"` OrgID OrgID `json:"org_id"` Name string `json:"name"` Environment string `json:"environment,omitempty"` Version int64 `json:"version"` } // Validate requires a workspace to belong to an org and have a well-formed name. func (w Workspace) Validate() error { if w.OrgID == "" { return fmt.Errorf("%w: no org", ErrInvalidWorkspace) } if _, err := ValidateName(w.Name); err != nil { return fmt.Errorf("%w: %w", ErrInvalidWorkspace, err) } if strings.Contains(string(w.ID), "/") || strings.Contains(string(w.OrgID), "/") { return fmt.Errorf("%w: the IDs must not contain a slash", ErrInvalidWorkspace) } return nil } // mayRename reports whether p is a person who owns id org-wide. A shared token, // a bot or service account, an admin, and a workspace owner may not. func (p Principal) mayRename(id OrgID) bool { return p.Kind == KindUser && p.RoleIn(id) == RoleOwner } // OrgEvent is one appended name change: the organisation itself when // WorkspaceID is empty, otherwise one of its workspaces. type OrgEvent struct { ID int64 `json:"id"` Kind string `json:"kind"` WorkspaceID WorkspaceID `json:"workspace_id,omitempty"` ActorID IdentityID `json:"actor_id"` ActorName string `json:"actor_name"` OldName string `json:"old_name"` NewName string `json:"new_name"` At time.Time `json:"at"` } // Membership gives an identity a role in an org, or in one workspace of it // when WorkspaceID is set. type Membership struct { IdentityID IdentityID `json:"identity_id"` OrgID OrgID `json:"org_id"` WorkspaceID WorkspaceID `json:"workspace_id,omitempty"` Role Role `json:"role"` } // Validate requires an identity, an org and a valid role. func (m Membership) Validate() error { if m.IdentityID == "" { return fmt.Errorf("%w: no identity", ErrInvalidMembership) } if m.OrgID == "" { return fmt.Errorf("%w: no org", ErrInvalidMembership) } return m.Role.Validate() } // Member is one identity's membership in an org or workspace. type Member struct { IdentityID IdentityID `json:"identity_id"` Kind Kind `json:"kind"` DisplayName string `json:"display_name"` WorkspaceID WorkspaceID `json:"workspace_id,omitempty"` Role Role `json:"role"` } // AgentAssignment records the one org an agent or service identity serves. type AgentAssignment struct { IdentityID IdentityID `json:"identity_id"` OrgID OrgID `json:"org_id"` } // Validate requires an identity and an org. func (a AgentAssignment) Validate() error { if a.IdentityID == "" || a.OrgID == "" { return fmt.Errorf("%w: identity and org are required", ErrInvalidAssignment) } return nil } type ( orgContextKey struct{} scopeContextKey struct{} ) // WithOrg attaches the organisation a request acts in. func WithOrg(ctx context.Context, id OrgID) context.Context { return context.WithValue(ctx, orgContextKey{}, id) } // OrgFromContext returns the organisation a request acts in, or DefaultOrgID // when the context carries none. func OrgFromContext(ctx context.Context) OrgID { if id, ok := ctx.Value(orgContextKey{}).(OrgID); ok && id != "" { return id } return DefaultOrgID } // WithScope confines a request's reads to one org. func WithScope(ctx context.Context, id OrgID) context.Context { return context.WithValue(ctx, scopeContextKey{}, id) } // WithoutScope lifts a request's org confinement for instance-wide reads. func WithoutScope(ctx context.Context) context.Context { return context.WithValue(ctx, scopeContextKey{}, OrgID("")) } // InstanceScope reports whether ctx may read instance-wide records. func InstanceScope(ctx context.Context) bool { id, ok := Scope(ctx) return !ok || id == DefaultOrgID } // Scope returns the org WithScope confined ctx to. func Scope(ctx context.Context) (OrgID, bool) { id, ok := ctx.Value(scopeContextKey{}).(OrgID) return id, ok && id != "" } // OrgRepository persists organisations, workspaces, memberships and agent assignments. type OrgRepository interface { //nolint:interfacebloat // one tenant-boundary store contract: orgs, workspaces, memberships and agent assignments CreateOrg(context.Context, Org, IdentityID) (Org, error) GetOrg(context.Context, OrgID) (Org, error) ListOrgs(context.Context) ([]Org, error) CreateWorkspace(context.Context, Workspace) (Workspace, error) ListWorkspaces(context.Context, OrgID) ([]Workspace, error) EnsureMembership(context.Context, Membership) error ListMembers(context.Context, OrgID) ([]Member, error) RemoveMembership(context.Context, Membership) error ListOrgAgents(context.Context, OrgID) ([]AgentAssignment, error) AssignAgent(context.Context, AgentAssignment) error OrgForIdentity(context.Context, IdentityID) (OrgID, error) } // OrgAPI is the read and write org surface exposed to callers. type OrgAPI interface { //nolint:interfacebloat // one tenant-boundary API: orgs, workspaces and name history ListOrgs(context.Context) ([]Org, error) GetOrg(context.Context, OrgID) (Org, error) RenameOrg(context.Context, OrgID, string, int64, IdentityID) (Org, error) ListWorkspaces(context.Context, OrgID) ([]Workspace, error) CreateWorkspace(context.Context, Workspace) (Workspace, error) RenameWorkspace(context.Context, OrgID, WorkspaceID, string, int64, IdentityID) (Workspace, error) ListOrgEvents(context.Context, OrgID, int) ([]OrgEvent, error) ListMembers(context.Context, OrgID) ([]Member, error) EnsureMembership(context.Context, Membership) error RemoveMembership(context.Context, Membership) error AssignAgent(context.Context, AgentAssignment) error } // OrgCreator creates an org with its default workspace and first owner. type OrgCreator interface { CreateOrg(context.Context, Org, IdentityID) (Org, error) } // AgentAssignments reads authoritative agent ownership. type AgentAssignments interface { ListOrgAgents(context.Context, OrgID) ([]AgentAssignment, error) }