Merge branch 'worktree-agent-a124e124e24c6a56b'
This commit is contained in:
46 files changed
+1802
-873
No files matched your search
+129
-79
@@ -374,6 +374,8 @@ components:
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
links_accounts:
|
||||
type: boolean
|
||||
listens:
|
||||
type: boolean
|
||||
lookups:
|
||||
@@ -391,6 +393,7 @@ components:
|
||||
- lookups
|
||||
- listens
|
||||
- target_facts
|
||||
- links_accounts
|
||||
type: object
|
||||
ConnectorsCapability:
|
||||
additionalProperties: false
|
||||
@@ -1235,6 +1238,43 @@ components:
|
||||
required:
|
||||
- sections
|
||||
type: object
|
||||
GovernanceChannelLink:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
connector:
|
||||
type: string
|
||||
linked_at:
|
||||
format: date-time
|
||||
type: string
|
||||
name:
|
||||
type: string
|
||||
subject:
|
||||
type: string
|
||||
required:
|
||||
- connector
|
||||
- subject
|
||||
- name
|
||||
- linked_at
|
||||
type: object
|
||||
GovernanceChannelsBody:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
connectors:
|
||||
items:
|
||||
type: string
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
linked:
|
||||
items:
|
||||
$ref: "#/components/schemas/GovernanceChannelLink"
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
required:
|
||||
- connectors
|
||||
- linked
|
||||
type: object
|
||||
GovernanceCreatedToken:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -1275,6 +1315,18 @@ components:
|
||||
- created_at
|
||||
- updated_at
|
||||
type: object
|
||||
GovernanceLinkStart:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
expires_at:
|
||||
format: date-time
|
||||
type: string
|
||||
url:
|
||||
type: string
|
||||
required:
|
||||
- url
|
||||
- expires_at
|
||||
type: object
|
||||
GovernanceModel:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -1426,27 +1478,6 @@ components:
|
||||
required:
|
||||
- passkeys
|
||||
type: object
|
||||
GovernancePersonRequest:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
authority:
|
||||
type: boolean
|
||||
id:
|
||||
description: Empty for a new person
|
||||
type: string
|
||||
identities:
|
||||
items:
|
||||
type: string
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
name:
|
||||
type: string
|
||||
required:
|
||||
- name
|
||||
- authority
|
||||
- identities
|
||||
type: object
|
||||
GovernancePersonalToken:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -1543,12 +1574,12 @@ components:
|
||||
GovernanceStepRequest:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
account:
|
||||
type: string
|
||||
deadline:
|
||||
type: string
|
||||
person:
|
||||
type: string
|
||||
required:
|
||||
- person
|
||||
- account
|
||||
- deadline
|
||||
type: object
|
||||
GovernanceTiming:
|
||||
@@ -2915,6 +2946,80 @@ info:
|
||||
version: dev
|
||||
openapi: 3.1.0
|
||||
paths:
|
||||
/api/account/channels:
|
||||
get:
|
||||
operationId: list-channel-links
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/GovernanceChannelsBody"
|
||||
description: OK
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: List the channels you can link and your linked accounts
|
||||
tags:
|
||||
- Accounts
|
||||
/api/account/channels/{connector}/link:
|
||||
post:
|
||||
operationId: begin-channel-link
|
||||
parameters:
|
||||
- in: path
|
||||
name: connector
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/GovernanceLinkStart"
|
||||
description: OK
|
||||
headers:
|
||||
Cache-Control:
|
||||
schema:
|
||||
type: string
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: Start linking a channel account
|
||||
tags:
|
||||
- Accounts
|
||||
/api/account/channels/{connector}/{subject}:
|
||||
delete:
|
||||
operationId: unlink-channel
|
||||
parameters:
|
||||
- in: path
|
||||
name: connector
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
- in: path
|
||||
name: subject
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: Unlink a channel account
|
||||
tags:
|
||||
- Accounts
|
||||
/api/account/passkeys:
|
||||
get:
|
||||
operationId: list-passkeys
|
||||
@@ -5078,61 +5183,6 @@ paths:
|
||||
summary: Rename a workspace
|
||||
tags:
|
||||
- Organisations
|
||||
/api/people:
|
||||
get:
|
||||
operationId: list-people
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
items:
|
||||
$ref: "#/components/schemas/GovernancePersonRequest"
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
description: OK
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: List the people
|
||||
tags:
|
||||
- Governance
|
||||
put:
|
||||
operationId: put-people
|
||||
requestBody:
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
items:
|
||||
$ref: "#/components/schemas/GovernancePersonRequest"
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
required: true
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
items:
|
||||
$ref: "#/components/schemas/GovernancePersonRequest"
|
||||
type:
|
||||
- array
|
||||
- "null"
|
||||
description: OK
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: Replace the people
|
||||
tags:
|
||||
- Governance
|
||||
/api/policies/change-request:
|
||||
get:
|
||||
operationId: get-change-request-rules
|
||||
|
||||
@@ -79,6 +79,7 @@ func (o *operations) Start(ctx context.Context) error {
|
||||
// Administrative writes are checked against the same live policy chain as
|
||||
// every other request.
|
||||
o.settings.UseAuthorizer(access)
|
||||
o.allow.UseAuthorizer(access)
|
||||
o.talk.Use(chat.Deps{
|
||||
People: o.settings, Access: access, Settings: o.settings, Toolbox: o.conns, Judge: o.judge,
|
||||
Approver: o.allow, Memory: o.remember, Runs: o.engine, Notifier: o.tell,
|
||||
|
||||
@@ -161,6 +161,8 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
||||
}
|
||||
// A model's key is a credential name resolved through the sealed store.
|
||||
settings.UseCredentials(conns)
|
||||
// An account links a channel account on the connectors that can link.
|
||||
settings.UseChannels(conns)
|
||||
|
||||
sys := system.New(system.Bootstrap{
|
||||
Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas),
|
||||
@@ -189,7 +191,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, tell)
|
||||
hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, settings, tell)
|
||||
hear.Routes(mux)
|
||||
judge := newJudgement(db, log, conns, classes, policies, settings, hear)
|
||||
// The record of deletions outlives this process and its database, so the
|
||||
@@ -250,7 +252,7 @@ func (a answers) Signal(ctx context.Context, id uuid.UUID, key string, payload j
|
||||
// and change-request rules. A failed action tightens its class.
|
||||
func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, classes *judgement.Classes, policies *judgement.Policies, settings *governance.Module, heard judgement.Events) *judgement.Module {
|
||||
guards := []judgement.Guard{
|
||||
judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, People: settings}, Defaults: settings},
|
||||
judgement.Impact{Lookup: judgement.RecordedFacts{Source: conns, Accounts: settings}, Defaults: settings},
|
||||
judgement.Reversibility{},
|
||||
judgement.Precedent{Classes: classes},
|
||||
judgement.Provenance{Events: heard},
|
||||
|
||||
@@ -281,7 +281,10 @@ type DescribeResponse struct {
|
||||
// which the dashboard renders as a form.
|
||||
Settings []*Setting `protobuf:"bytes,8,rep,name=settings,proto3" json:"settings,omitempty"`
|
||||
// version is the connector's own release.
|
||||
Version string `protobuf:"bytes,9,opt,name=version,proto3" json:"version,omitempty"`
|
||||
Version string `protobuf:"bytes,9,opt,name=version,proto3" json:"version,omitempty"`
|
||||
// links_accounts says the connector serves LinkURL and emits account.link
|
||||
// events, so a person can link their channel identity to an account.
|
||||
LinksAccounts bool `protobuf:"varint,10,opt,name=links_accounts,json=linksAccounts,proto3" json:"links_accounts,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -379,6 +382,13 @@ func (x *DescribeResponse) GetVersion() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *DescribeResponse) GetLinksAccounts() bool {
|
||||
if x != nil {
|
||||
return x.LinksAccounts
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Setting is one value an operator enters for an extension to run.
|
||||
type Setting struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
@@ -1746,6 +1756,96 @@ func (x *ListenResponse) GetCursor() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
type LinkURLRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// code is the single-use link code the person sends to the connector.
|
||||
Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LinkURLRequest) Reset() {
|
||||
*x = LinkURLRequest{}
|
||||
mi := &file_connector_v1_connector_proto_msgTypes[26]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LinkURLRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LinkURLRequest) ProtoMessage() {}
|
||||
|
||||
func (x *LinkURLRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_connector_v1_connector_proto_msgTypes[26]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LinkURLRequest.ProtoReflect.Descriptor instead.
|
||||
func (*LinkURLRequest) Descriptor() ([]byte, []int) {
|
||||
return file_connector_v1_connector_proto_rawDescGZIP(), []int{26}
|
||||
}
|
||||
|
||||
func (x *LinkURLRequest) GetCode() string {
|
||||
if x != nil {
|
||||
return x.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type LinkURLResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// url opens the connector's channel with the code attached.
|
||||
Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LinkURLResponse) Reset() {
|
||||
*x = LinkURLResponse{}
|
||||
mi := &file_connector_v1_connector_proto_msgTypes[27]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LinkURLResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LinkURLResponse) ProtoMessage() {}
|
||||
|
||||
func (x *LinkURLResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_connector_v1_connector_proto_msgTypes[27]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LinkURLResponse.ProtoReflect.Descriptor instead.
|
||||
func (*LinkURLResponse) Descriptor() ([]byte, []int) {
|
||||
return file_connector_v1_connector_proto_rawDescGZIP(), []int{27}
|
||||
}
|
||||
|
||||
func (x *LinkURLResponse) GetUrl() string {
|
||||
if x != nil {
|
||||
return x.Url
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_connector_v1_connector_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
@@ -1761,7 +1861,7 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x13\n" +
|
||||
"\x11ConfigureResponse\"\x11\n" +
|
||||
"\x0fDescribeRequest\"\x8d\x03\n" +
|
||||
"\x0fDescribeRequest\"\xb4\x03\n" +
|
||||
"\x10DescribeResponse\x12\x1a\n" +
|
||||
"\bcontract\x18\x01 \x01(\tR\bcontract\x12/\n" +
|
||||
"\x06events\x18\x02 \x03(\v2\x17.connector.v1.EventTypeR\x06events\x122\n" +
|
||||
@@ -1773,7 +1873,9 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\alistens\x18\x06 \x01(\bR\alistens\x12!\n" +
|
||||
"\ftarget_facts\x18\a \x01(\bR\vtargetFacts\x121\n" +
|
||||
"\bsettings\x18\b \x03(\v2\x15.connector.v1.SettingR\bsettings\x12\x18\n" +
|
||||
"\aversion\x18\t \x01(\tR\aversion\"\xd0\x01\n" +
|
||||
"\aversion\x18\t \x01(\tR\aversion\x12%\n" +
|
||||
"\x0elinks_accounts\x18\n" +
|
||||
" \x01(\bR\rlinksAccounts\"\xd0\x01\n" +
|
||||
"\aSetting\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05label\x18\x02 \x01(\tR\x05label\x12 \n" +
|
||||
@@ -1874,7 +1976,11 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\x06cursor\x18\x01 \x01(\tR\x06cursor\"U\n" +
|
||||
"\x0eListenResponse\x12+\n" +
|
||||
"\x06events\x18\x01 \x03(\v2\x13.connector.v1.EventR\x06events\x12\x16\n" +
|
||||
"\x06cursor\x18\x02 \x01(\tR\x06cursor*\xd9\x01\n" +
|
||||
"\x06cursor\x18\x02 \x01(\tR\x06cursor\"$\n" +
|
||||
"\x0eLinkURLRequest\x12\x12\n" +
|
||||
"\x04code\x18\x01 \x01(\tR\x04code\"#\n" +
|
||||
"\x0fLinkURLResponse\x12\x10\n" +
|
||||
"\x03url\x18\x01 \x01(\tR\x03url*\xd9\x01\n" +
|
||||
"\vSettingType\x12\x1c\n" +
|
||||
"\x18SETTING_TYPE_UNSPECIFIED\x10\x00\x12\x17\n" +
|
||||
"\x13SETTING_TYPE_STRING\x10\x01\x12\x17\n" +
|
||||
@@ -1888,7 +1994,7 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\x19REVERSIBILITY_UNSPECIFIED\x10\x00\x12&\n" +
|
||||
"\"REVERSIBILITY_UNDONE_AUTOMATICALLY\x10\x01\x12\x1d\n" +
|
||||
"\x19REVERSIBILITY_RECOVERABLE\x10\x02\x12\x1e\n" +
|
||||
"\x1aREVERSIBILITY_IRREVERSIBLE\x10\x032\xa2\x05\n" +
|
||||
"\x1aREVERSIBILITY_IRREVERSIBLE\x10\x032\xea\x05\n" +
|
||||
"\x10ConnectorService\x12L\n" +
|
||||
"\tConfigure\x12\x1e.connector.v1.ConfigureRequest\x1a\x1f.connector.v1.ConfigureResponse\x12I\n" +
|
||||
"\bDescribe\x12\x1d.connector.v1.DescribeRequest\x1a\x1e.connector.v1.DescribeResponse\x12@\n" +
|
||||
@@ -1898,7 +2004,8 @@ const file_connector_v1_connector_proto_rawDesc = "" +
|
||||
"\x06Lookup\x12\x1b.connector.v1.LookupRequest\x1a\x1c.connector.v1.LookupResponse\x12F\n" +
|
||||
"\aDeliver\x12\x1c.connector.v1.DeliverRequest\x1a\x1d.connector.v1.DeliverResponse\x12E\n" +
|
||||
"\x06Listen\x12\x1b.connector.v1.ListenRequest\x1a\x1c.connector.v1.ListenResponse0\x01\x12R\n" +
|
||||
"\vTargetFacts\x12 .connector.v1.TargetFactsRequest\x1a!.connector.v1.TargetFactsResponseB\xc4\x01\n" +
|
||||
"\vTargetFacts\x12 .connector.v1.TargetFactsRequest\x1a!.connector.v1.TargetFactsResponse\x12F\n" +
|
||||
"\aLinkURL\x12\x1c.connector.v1.LinkURLRequest\x1a\x1d.connector.v1.LinkURLResponseB\xc4\x01\n" +
|
||||
"\x10com.connector.v1B\x0eConnectorProtoP\x01ZOgithub.com/samcharles93/archie-core/internal/contracts/connector/v1;connectorv1\xa2\x02\x03CXX\xaa\x02\fConnector.V1\xca\x02\fConnector\\V1\xe2\x02\x18Connector\\V1\\GPBMetadata\xea\x02\rConnector::V1b\x06proto3"
|
||||
|
||||
var (
|
||||
@@ -1914,7 +2021,7 @@ func file_connector_v1_connector_proto_rawDescGZIP() []byte {
|
||||
}
|
||||
|
||||
var file_connector_v1_connector_proto_enumTypes = make([]protoimpl.EnumInfo, 2)
|
||||
var file_connector_v1_connector_proto_msgTypes = make([]protoimpl.MessageInfo, 29)
|
||||
var file_connector_v1_connector_proto_msgTypes = make([]protoimpl.MessageInfo, 31)
|
||||
var file_connector_v1_connector_proto_goTypes = []any{
|
||||
(SettingType)(0), // 0: connector.v1.SettingType
|
||||
(Reversibility)(0), // 1: connector.v1.Reversibility
|
||||
@@ -1944,14 +2051,16 @@ var file_connector_v1_connector_proto_goTypes = []any{
|
||||
(*TargetFactsResponse)(nil), // 25: connector.v1.TargetFactsResponse
|
||||
(*ListenRequest)(nil), // 26: connector.v1.ListenRequest
|
||||
(*ListenResponse)(nil), // 27: connector.v1.ListenResponse
|
||||
nil, // 28: connector.v1.ConfigureRequest.SettingsEntry
|
||||
nil, // 29: connector.v1.ConfigureRequest.SecretsEntry
|
||||
nil, // 30: connector.v1.ParseRequest.HeadersEntry
|
||||
(*timestamppb.Timestamp)(nil), // 31: google.protobuf.Timestamp
|
||||
(*LinkURLRequest)(nil), // 28: connector.v1.LinkURLRequest
|
||||
(*LinkURLResponse)(nil), // 29: connector.v1.LinkURLResponse
|
||||
nil, // 30: connector.v1.ConfigureRequest.SettingsEntry
|
||||
nil, // 31: connector.v1.ConfigureRequest.SecretsEntry
|
||||
nil, // 32: connector.v1.ParseRequest.HeadersEntry
|
||||
(*timestamppb.Timestamp)(nil), // 33: google.protobuf.Timestamp
|
||||
}
|
||||
var file_connector_v1_connector_proto_depIdxs = []int32{
|
||||
28, // 0: connector.v1.ConfigureRequest.settings:type_name -> connector.v1.ConfigureRequest.SettingsEntry
|
||||
29, // 1: connector.v1.ConfigureRequest.secrets:type_name -> connector.v1.ConfigureRequest.SecretsEntry
|
||||
30, // 0: connector.v1.ConfigureRequest.settings:type_name -> connector.v1.ConfigureRequest.SettingsEntry
|
||||
31, // 1: connector.v1.ConfigureRequest.secrets:type_name -> connector.v1.ConfigureRequest.SecretsEntry
|
||||
7, // 2: connector.v1.DescribeResponse.events:type_name -> connector.v1.EventType
|
||||
8, // 3: connector.v1.DescribeResponse.actions:type_name -> connector.v1.ActionType
|
||||
10, // 4: connector.v1.DescribeResponse.lookups:type_name -> connector.v1.LookupType
|
||||
@@ -1961,9 +2070,9 @@ var file_connector_v1_connector_proto_depIdxs = []int32{
|
||||
11, // 8: connector.v1.ActionType.effect:type_name -> connector.v1.Effect
|
||||
11, // 9: connector.v1.LookupType.effect:type_name -> connector.v1.Effect
|
||||
1, // 10: connector.v1.Effect.reversibility:type_name -> connector.v1.Reversibility
|
||||
30, // 11: connector.v1.ParseRequest.headers:type_name -> connector.v1.ParseRequest.HeadersEntry
|
||||
32, // 11: connector.v1.ParseRequest.headers:type_name -> connector.v1.ParseRequest.HeadersEntry
|
||||
15, // 12: connector.v1.ParseResponse.events:type_name -> connector.v1.Event
|
||||
31, // 13: connector.v1.Event.occurred_at:type_name -> google.protobuf.Timestamp
|
||||
33, // 13: connector.v1.Event.occurred_at:type_name -> google.protobuf.Timestamp
|
||||
12, // 14: connector.v1.ResolveResponse.target:type_name -> connector.v1.Target
|
||||
11, // 15: connector.v1.ResolveResponse.effect:type_name -> connector.v1.Effect
|
||||
12, // 16: connector.v1.TargetFactsRequest.target:type_name -> connector.v1.Target
|
||||
@@ -1977,17 +2086,19 @@ var file_connector_v1_connector_proto_depIdxs = []int32{
|
||||
22, // 24: connector.v1.ConnectorService.Deliver:input_type -> connector.v1.DeliverRequest
|
||||
26, // 25: connector.v1.ConnectorService.Listen:input_type -> connector.v1.ListenRequest
|
||||
24, // 26: connector.v1.ConnectorService.TargetFacts:input_type -> connector.v1.TargetFactsRequest
|
||||
3, // 27: connector.v1.ConnectorService.Configure:output_type -> connector.v1.ConfigureResponse
|
||||
5, // 28: connector.v1.ConnectorService.Describe:output_type -> connector.v1.DescribeResponse
|
||||
14, // 29: connector.v1.ConnectorService.Parse:output_type -> connector.v1.ParseResponse
|
||||
17, // 30: connector.v1.ConnectorService.Resolve:output_type -> connector.v1.ResolveResponse
|
||||
19, // 31: connector.v1.ConnectorService.Invoke:output_type -> connector.v1.InvokeResponse
|
||||
21, // 32: connector.v1.ConnectorService.Lookup:output_type -> connector.v1.LookupResponse
|
||||
23, // 33: connector.v1.ConnectorService.Deliver:output_type -> connector.v1.DeliverResponse
|
||||
27, // 34: connector.v1.ConnectorService.Listen:output_type -> connector.v1.ListenResponse
|
||||
25, // 35: connector.v1.ConnectorService.TargetFacts:output_type -> connector.v1.TargetFactsResponse
|
||||
27, // [27:36] is the sub-list for method output_type
|
||||
18, // [18:27] is the sub-list for method input_type
|
||||
28, // 27: connector.v1.ConnectorService.LinkURL:input_type -> connector.v1.LinkURLRequest
|
||||
3, // 28: connector.v1.ConnectorService.Configure:output_type -> connector.v1.ConfigureResponse
|
||||
5, // 29: connector.v1.ConnectorService.Describe:output_type -> connector.v1.DescribeResponse
|
||||
14, // 30: connector.v1.ConnectorService.Parse:output_type -> connector.v1.ParseResponse
|
||||
17, // 31: connector.v1.ConnectorService.Resolve:output_type -> connector.v1.ResolveResponse
|
||||
19, // 32: connector.v1.ConnectorService.Invoke:output_type -> connector.v1.InvokeResponse
|
||||
21, // 33: connector.v1.ConnectorService.Lookup:output_type -> connector.v1.LookupResponse
|
||||
23, // 34: connector.v1.ConnectorService.Deliver:output_type -> connector.v1.DeliverResponse
|
||||
27, // 35: connector.v1.ConnectorService.Listen:output_type -> connector.v1.ListenResponse
|
||||
25, // 36: connector.v1.ConnectorService.TargetFacts:output_type -> connector.v1.TargetFactsResponse
|
||||
29, // 37: connector.v1.ConnectorService.LinkURL:output_type -> connector.v1.LinkURLResponse
|
||||
28, // [28:38] is the sub-list for method output_type
|
||||
18, // [18:28] is the sub-list for method input_type
|
||||
18, // [18:18] is the sub-list for extension type_name
|
||||
18, // [18:18] is the sub-list for extension extendee
|
||||
0, // [0:18] is the sub-list for field type_name
|
||||
@@ -2004,7 +2115,7 @@ func file_connector_v1_connector_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_connector_v1_connector_proto_rawDesc), len(file_connector_v1_connector_proto_rawDesc)),
|
||||
NumEnums: 2,
|
||||
NumMessages: 29,
|
||||
NumMessages: 31,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -28,6 +28,7 @@ const (
|
||||
ConnectorService_Deliver_FullMethodName = "/connector.v1.ConnectorService/Deliver"
|
||||
ConnectorService_Listen_FullMethodName = "/connector.v1.ConnectorService/Listen"
|
||||
ConnectorService_TargetFacts_FullMethodName = "/connector.v1.ConnectorService/TargetFacts"
|
||||
ConnectorService_LinkURL_FullMethodName = "/connector.v1.ConnectorService/LinkURL"
|
||||
)
|
||||
|
||||
// ConnectorServiceClient is the client API for ConnectorService service.
|
||||
@@ -74,6 +75,12 @@ type ConnectorServiceClient interface {
|
||||
// host asks only connectors that declare target_facts, and never stores the
|
||||
// answer.
|
||||
TargetFacts(ctx context.Context, in *TargetFactsRequest, opts ...grpc.CallOption) (*TargetFactsResponse, error)
|
||||
// LinkURL returns the URL a person opens to send a link code to the
|
||||
// connector, such as a deep link into its bot. The host asks only
|
||||
// connectors that declare links_accounts. The connector then emits an
|
||||
// account.link event carrying the code and the sender's channel identity;
|
||||
// the host binds that identity to the account that issued the code.
|
||||
LinkURL(ctx context.Context, in *LinkURLRequest, opts ...grpc.CallOption) (*LinkURLResponse, error)
|
||||
}
|
||||
|
||||
type connectorServiceClient struct {
|
||||
@@ -183,6 +190,16 @@ func (c *connectorServiceClient) TargetFacts(ctx context.Context, in *TargetFact
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *connectorServiceClient) LinkURL(ctx context.Context, in *LinkURLRequest, opts ...grpc.CallOption) (*LinkURLResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(LinkURLResponse)
|
||||
err := c.cc.Invoke(ctx, ConnectorService_LinkURL_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ConnectorServiceServer is the server API for ConnectorService service.
|
||||
// All implementations must embed UnimplementedConnectorServiceServer
|
||||
// for forward compatibility.
|
||||
@@ -227,6 +244,12 @@ type ConnectorServiceServer interface {
|
||||
// host asks only connectors that declare target_facts, and never stores the
|
||||
// answer.
|
||||
TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error)
|
||||
// LinkURL returns the URL a person opens to send a link code to the
|
||||
// connector, such as a deep link into its bot. The host asks only
|
||||
// connectors that declare links_accounts. The connector then emits an
|
||||
// account.link event carrying the code and the sender's channel identity;
|
||||
// the host binds that identity to the account that issued the code.
|
||||
LinkURL(context.Context, *LinkURLRequest) (*LinkURLResponse, error)
|
||||
mustEmbedUnimplementedConnectorServiceServer()
|
||||
}
|
||||
|
||||
@@ -264,6 +287,9 @@ func (UnimplementedConnectorServiceServer) Listen(*ListenRequest, grpc.ServerStr
|
||||
func (UnimplementedConnectorServiceServer) TargetFacts(context.Context, *TargetFactsRequest) (*TargetFactsResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method TargetFacts not implemented")
|
||||
}
|
||||
func (UnimplementedConnectorServiceServer) LinkURL(context.Context, *LinkURLRequest) (*LinkURLResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method LinkURL not implemented")
|
||||
}
|
||||
func (UnimplementedConnectorServiceServer) mustEmbedUnimplementedConnectorServiceServer() {}
|
||||
func (UnimplementedConnectorServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
@@ -440,6 +466,24 @@ func _ConnectorService_TargetFacts_Handler(srv interface{}, ctx context.Context,
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _ConnectorService_LinkURL_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(LinkURLRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ConnectorServiceServer).LinkURL(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: ConnectorService_LinkURL_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ConnectorServiceServer).LinkURL(ctx, req.(*LinkURLRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// ConnectorService_ServiceDesc is the grpc.ServiceDesc for ConnectorService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -479,6 +523,10 @@ var ConnectorService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "TargetFacts",
|
||||
Handler: _ConnectorService_TargetFacts_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "LinkURL",
|
||||
Handler: _ConnectorService_LinkURL_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
-- +goose Up
|
||||
-- Who may approve is decided by role, and a channel identity is a credential of
|
||||
-- an account, so the people records go. A channel identity moves to the account
|
||||
-- its person maps to without doubt: the account the person already answered
|
||||
-- from on the dashboard, or the operating org's only owner when that owner
|
||||
-- and the person are the only ones. Any other identity is dropped and linked
|
||||
-- again from the account page. The default owner and escalation steps follow
|
||||
-- the same mapping, and a step that maps nowhere is cleared.
|
||||
CREATE TABLE governance.link_codes (
|
||||
code_hash text PRIMARY KEY,
|
||||
identity_id text NOT NULL REFERENCES governance.identities (id),
|
||||
issuer text NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
used_at timestamptz
|
||||
);
|
||||
CREATE INDEX idx_governance_link_codes_identity
|
||||
ON governance.link_codes (identity_id);
|
||||
|
||||
CREATE TEMPORARY TABLE person_account (
|
||||
person_id uuid PRIMARY KEY,
|
||||
account text NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO person_account (person_id, account)
|
||||
SELECT pi.person_id, min(substr(pi.identity, 9))
|
||||
FROM governance.person_identities pi
|
||||
JOIN governance.memberships m
|
||||
ON m.identity_id = substr(pi.identity, 9) AND m.org_id = 'org-sys' AND m.workspace_id IS NULL
|
||||
WHERE pi.identity LIKE 'account:%'
|
||||
GROUP BY pi.person_id
|
||||
HAVING count(*) = 1;
|
||||
|
||||
INSERT INTO person_account (person_id, account)
|
||||
SELECT p.id, sole.identity_id
|
||||
FROM governance.people p
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT min(m.identity_id) AS identity_id, count(*) AS owners
|
||||
FROM governance.memberships m
|
||||
JOIN governance.identities i ON i.id = m.identity_id
|
||||
WHERE m.org_id = 'org-sys' AND m.workspace_id IS NULL AND m.role = 'owner' AND i.kind = 'user'
|
||||
) sole
|
||||
WHERE sole.owners = 1
|
||||
AND (SELECT count(*) FROM governance.people) = 1
|
||||
AND p.id NOT IN (SELECT person_id FROM person_account);
|
||||
|
||||
INSERT INTO governance.identity_subjects (issuer, subject, identity_id, bound_at, name)
|
||||
SELECT split_part(pi.identity, ':', 1), substr(pi.identity, strpos(pi.identity, ':') + 1), pa.account, now(), ''
|
||||
FROM governance.person_identities pi
|
||||
JOIN person_account pa ON pa.person_id = pi.person_id
|
||||
WHERE pi.identity NOT LIKE 'account:%' AND strpos(pi.identity, ':') > 1
|
||||
ON CONFLICT (issuer, subject) DO NOTHING;
|
||||
|
||||
UPDATE governance.settings s
|
||||
SET default_owner = COALESCE((
|
||||
SELECT pa.account FROM person_account pa WHERE pa.person_id::text = s.default_owner
|
||||
), ''),
|
||||
escalation = COALESCE((
|
||||
SELECT jsonb_agg(jsonb_build_object('account', d.account, 'deadline_ms', d.deadline_ms) ORDER BY d.n)
|
||||
FROM (
|
||||
SELECT DISTINCT ON (pa.account) pa.account, e.step -> 'deadline_ms' AS deadline_ms, e.n
|
||||
FROM jsonb_array_elements(s.escalation) WITH ORDINALITY AS e (step, n)
|
||||
JOIN person_account pa ON pa.person_id::text = e.step ->> 'person'
|
||||
ORDER BY pa.account, e.n
|
||||
) d
|
||||
), '[]'::jsonb);
|
||||
|
||||
DROP TABLE person_account;
|
||||
DROP TABLE governance.person_identities;
|
||||
DROP TABLE governance.people;
|
||||
|
||||
ALTER TABLE approvals.requests DROP COLUMN asked;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE approvals.requests ADD COLUMN asked jsonb NOT NULL DEFAULT '[]';
|
||||
|
||||
CREATE TABLE governance.people (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
authority boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (org_id, name)
|
||||
);
|
||||
CREATE TABLE governance.person_identities (
|
||||
org_id text NOT NULL,
|
||||
identity text NOT NULL,
|
||||
person_id uuid NOT NULL REFERENCES governance.people (id) ON DELETE CASCADE,
|
||||
CONSTRAINT person_identities_pkey PRIMARY KEY (org_id, identity)
|
||||
);
|
||||
|
||||
UPDATE governance.settings SET default_owner = '', escalation = '[]'::jsonb;
|
||||
|
||||
DROP TABLE governance.link_codes;
|
||||
@@ -6,7 +6,7 @@ Dashboard pages:
|
||||
- Unmatched (/unmatched): event groups no trigger matched; a draft workflow can be made from one, dry-run, and published.
|
||||
- Events (/events): the events sources delivered, with the run each started.
|
||||
- Classes (/classes, /classes/ID): action classes and the autonomy each has earned; approvals count towards a raise a person must approve, and a denial or failure lowers it.
|
||||
- People (/people): the people approvals go to, with their channel identities.
|
||||
- Account (/account): passkeys, tokens and the channel accounts (such as Telegram) linked to the signed-in account. Any member whose role allows approve can answer an approval, from the dashboard or from a linked channel account.
|
||||
- Controls (/controls): hard rules and change-request policy, and the judges that weigh actions.
|
||||
- Extensions (/extensions): connectors, secret engines, guards and MCP servers, each accepted before it runs.
|
||||
- Sources (/sources) and Triggers (/triggers): where events come from and which workflow each kind starts.
|
||||
|
||||
@@ -43,25 +43,18 @@ var (
|
||||
ErrAnswered = errors.New("that request was already answered")
|
||||
// ErrExpired means the answer arrived after the request's deadline.
|
||||
ErrExpired = errors.New("that request has expired")
|
||||
// ErrUnverified means the answer came from an identity no person holds.
|
||||
ErrUnverified = errors.New("that identity isn't held by any person, so its answer is refused")
|
||||
// ErrNotApprover means the person may not answer approvals for actions.
|
||||
ErrNotApprover = errors.New("that person isn't the default owner, on the escalation path or an authority, so their answer is refused")
|
||||
// ErrNotAsked means the request hasn't yet reached that person on its
|
||||
// escalation path.
|
||||
ErrNotAsked = errors.New("that person hasn't been asked yet, so their answer is refused")
|
||||
// ErrNeedsAuthority means the action needs a person with authority, and
|
||||
// the answer came from one without.
|
||||
ErrNeedsAuthority = errors.New("that action needs a person with authority, so their answer is refused")
|
||||
// ErrUnlinked means the answer came from a channel account that no
|
||||
// account has linked.
|
||||
ErrUnlinked = errors.New("that channel account isn't linked to an account, so its answer is refused")
|
||||
// ErrNotApprover means the account's role doesn't let it answer this
|
||||
// request.
|
||||
ErrNotApprover = errors.New("that account isn't allowed to approve this request, so its answer is refused")
|
||||
// ErrNeedsFreshAuthentication means approving this action needs a passkey
|
||||
// assertion made for this request, and the answer carried none.
|
||||
ErrNeedsFreshAuthentication = errors.New("that action can't be undone, so approving it needs a fresh passkey confirmation")
|
||||
// ErrNotSignedIn means the answer came from no signed-in person: the
|
||||
// bootstrap admin token is not a person who may approve.
|
||||
ErrNotSignedIn = errors.New("only a signed-in person can answer an approval")
|
||||
// ErrNoAuthority means the answer to a raise came from a person without
|
||||
// authority over policy and ceilings.
|
||||
ErrNoAuthority = errors.New("that person holds no authority over policy and ceilings, so their answer to a raise is refused")
|
||||
)
|
||||
|
||||
// The kinds of request. A raise asks whether an action class may act with one
|
||||
@@ -179,30 +172,34 @@ type Policy interface {
|
||||
RaiseAfter(ctx context.Context) (int, error)
|
||||
}
|
||||
|
||||
// People resolves verified channel identities to people.
|
||||
type People interface {
|
||||
Verify(ctx context.Context, identity string) (governance.Verified, bool, error)
|
||||
// Accounts resolves who answered: the account a channel credential is linked
|
||||
// to, and the principal the access policies judge.
|
||||
type Accounts interface {
|
||||
ResolveSubject(ctx context.Context, s governance.Subject) (governance.Identity, error)
|
||||
PrincipalFor(ctx context.Context, id governance.IdentityID) (governance.Principal, error)
|
||||
Get(ctx context.Context, id governance.IdentityID) (governance.Identity, error)
|
||||
}
|
||||
|
||||
// Module owns one organisation's approval requests.
|
||||
type Module struct {
|
||||
orgID string
|
||||
store *store.Store
|
||||
tell Delivery
|
||||
wake Signaller
|
||||
classes Classes
|
||||
policy Policy
|
||||
people People
|
||||
confirm Confirmer
|
||||
changes ChangeRequests
|
||||
log *slog.Logger
|
||||
now func() time.Time
|
||||
orgID string
|
||||
store *store.Store
|
||||
tell Delivery
|
||||
wake Signaller
|
||||
classes Classes
|
||||
policy Policy
|
||||
accounts Accounts
|
||||
authz governance.Authorizer
|
||||
confirm Confirmer
|
||||
changes ChangeRequests
|
||||
log *slog.Logger
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewModule creates the approvals module for orgID.
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy, people People) *Module {
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake Signaller, classes Classes, policy Policy, accounts Accounts) *Module {
|
||||
return &Module{
|
||||
orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, people: people,
|
||||
orgID: orgID, store: store.New(db), tell: tell, wake: wake, classes: classes, policy: policy, accounts: accounts,
|
||||
log: log, now: time.Now,
|
||||
}
|
||||
}
|
||||
@@ -221,21 +218,13 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, d judgeme
|
||||
for _, st := range path {
|
||||
total += st.Deadline()
|
||||
}
|
||||
asked := []string{}
|
||||
if path[0].Person != "" {
|
||||
asked = append(asked, path[0].Person)
|
||||
}
|
||||
askedJSON, err := json.Marshal(asked)
|
||||
if err != nil {
|
||||
return Request{}, fmt.Errorf("encode asked: %w", err)
|
||||
}
|
||||
row, err := m.store.Put(ctx, store.Request{
|
||||
ID: uuid.New(), OrgID: m.orgID, RunID: runID, Key: key,
|
||||
DecisionID: d.ID, Kind: KindAction, Digest: d.Action.Digest, Level: d.Level.String(),
|
||||
Connector: d.Action.Connector, Action: d.Action.Name,
|
||||
TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, Irreversible: irreversible(d.Action),
|
||||
Summary: Summary(d), State: StatePending, Deadline: now.Add(total),
|
||||
StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true}, Asked: string(askedJSON),
|
||||
StepDeadline: sql.NullTime{Time: now.Add(path[0].Deadline()), Valid: true},
|
||||
ChangeRequest: changeRequest,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -364,11 +353,13 @@ func raiseSummary(r *judgement.Raise) string {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
// Settle processes a response from a channel identity such as "telegram:1001".
|
||||
// It records why it rejected an unverified or unauthorized response. It returns
|
||||
// false without an error for recorded rejections and for requests that are
|
||||
// missing, expired or already answered, since retrying won't help.
|
||||
func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, via string, approved bool) (bool, error) {
|
||||
// Settle processes a response from a channel account, such as the Telegram
|
||||
// user 1001 on the "telegram" connector. It records why it rejected an
|
||||
// unlinked or unauthorized response. It returns false without an error for
|
||||
// recorded rejections and for requests that are missing, expired or already
|
||||
// answered, since retrying won't help. An unlinked account returns
|
||||
// ErrUnlinked so the caller can tell it how to link.
|
||||
func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subject, via string, approved bool) (bool, error) {
|
||||
row, err := m.store.ByID(ctx, m.orgID, id)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return false, nil
|
||||
@@ -376,17 +367,24 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, via string,
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
who, err := m.verify(ctx, identity, row)
|
||||
name, err := m.channelAnswerer(ctx, who, row)
|
||||
if refusal(err) {
|
||||
identity := who.Issuer + ":" + who.Subject
|
||||
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
|
||||
return false, m.store.Refuse(ctx, store.Refusal{
|
||||
if rerr := m.store.Refuse(ctx, store.Refusal{
|
||||
ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: via, Reason: err.Error(), At: m.now().UTC(),
|
||||
})
|
||||
}); rerr != nil {
|
||||
return false, rerr
|
||||
}
|
||||
if errors.Is(err, ErrUnlinked) {
|
||||
return false, err
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err = m.answerAs(ctx, id, who.Name+" ("+identity+")", via, approved)
|
||||
_, err = m.answerAs(ctx, id, name, via, approved)
|
||||
switch {
|
||||
case err == nil:
|
||||
return true, nil
|
||||
@@ -396,46 +394,59 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, identity, via string,
|
||||
return false, err
|
||||
}
|
||||
|
||||
func (m *Module) verify(ctx context.Context, identity string, row store.Request) (governance.Verified, error) {
|
||||
who, ok, err := m.people.Verify(ctx, identity)
|
||||
// channelAnswerer returns the name of the account who holds the channel
|
||||
// credential when that account may answer row.
|
||||
func (m *Module) channelAnswerer(ctx context.Context, who governance.Subject, row store.Request) (string, error) {
|
||||
account, err := m.accounts.ResolveSubject(ctx, who)
|
||||
if errors.Is(err, governance.ErrIdentityNotFound) {
|
||||
return "", ErrUnlinked
|
||||
}
|
||||
if err != nil {
|
||||
return governance.Verified{}, fmt.Errorf("verify %s: %w", identity, err)
|
||||
return "", fmt.Errorf("resolve %s:%s: %w", who.Issuer, who.Subject, err)
|
||||
}
|
||||
if !ok {
|
||||
return governance.Verified{}, ErrUnverified
|
||||
if account.Kind != governance.KindUser || !account.CanAct() {
|
||||
return "", ErrNotApprover
|
||||
}
|
||||
return who, mayAnswer(who, row)
|
||||
p, err := m.accounts.PrincipalFor(ctx, account.ID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read access of %s: %w", account.ID, err)
|
||||
}
|
||||
p.Kind = account.Kind
|
||||
if err := m.mayAnswer(ctx, p, row); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return account.DisplayName, nil
|
||||
}
|
||||
|
||||
func mayAnswer(who governance.Verified, row store.Request) error {
|
||||
switch {
|
||||
case row.Kind == KindRaise && !who.Authority:
|
||||
return ErrNoAuthority
|
||||
case row.Kind == KindRaise:
|
||||
return nil
|
||||
case !who.Approver && !slices.Contains(askedOf(row), who.ID):
|
||||
// mayAnswer applies the access policies to an answer, as to any other
|
||||
// permission: approving needs the approve action on the request, and a raise
|
||||
// or an escalated action, which change what the organisation lets Archie do,
|
||||
// also need the policy-management action.
|
||||
func (m *Module) mayAnswer(ctx context.Context, p governance.Principal, row store.Request) error {
|
||||
if m.authz == nil {
|
||||
return ErrNotApprover
|
||||
case row.Level == judgement.Escalate.String() && !who.Authority:
|
||||
return ErrNeedsAuthority
|
||||
case !who.Authority && !slices.Contains(askedOf(row), who.ID):
|
||||
return ErrNotAsked
|
||||
}
|
||||
actions := []governance.Action{governance.ActionApprove}
|
||||
if row.Kind == KindRaise || row.Level == judgement.Escalate.String() {
|
||||
actions = append(actions, governance.ActionManagePolicies)
|
||||
}
|
||||
res := governance.Resource{Kind: governance.KindApproval, ID: row.ID.String(), Org: governance.DefaultOrgID, State: row.State}
|
||||
for _, a := range actions {
|
||||
d := m.authz.Authorize(ctx, p, a, res, governance.AccessContext{})
|
||||
if d.Err != nil {
|
||||
return fmt.Errorf("check access: %w", d.Err)
|
||||
}
|
||||
if !d.Allowed {
|
||||
return ErrNotApprover
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func askedOf(row store.Request) []string {
|
||||
var ids []string
|
||||
if err := json.Unmarshal([]byte(row.Asked), &ids); err != nil {
|
||||
return nil
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// refusal distinguishes a rejected response from an operational error.
|
||||
func refusal(err error) bool {
|
||||
return errors.Is(err, ErrUnverified) || errors.Is(err, ErrNotApprover) || errors.Is(err, ErrNoAuthority) ||
|
||||
errors.Is(err, ErrNotAsked) || errors.Is(err, ErrNeedsAuthority) || errors.Is(err, ErrNeedsFreshAuthentication) ||
|
||||
errors.Is(err, ErrNotSignedIn)
|
||||
return errors.Is(err, ErrUnlinked) || errors.Is(err, ErrNotApprover) ||
|
||||
errors.Is(err, ErrNeedsFreshAuthentication) || errors.Is(err, ErrNotSignedIn)
|
||||
}
|
||||
|
||||
// Expire records a timeout without reducing the action class's autonomy:
|
||||
|
||||
@@ -3,62 +3,129 @@ package approvals
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
)
|
||||
|
||||
type fakePeople map[string]governance.Verified
|
||||
|
||||
func (f fakePeople) Verify(_ context.Context, identity string) (governance.Verified, bool, error) {
|
||||
p, ok := f[identity]
|
||||
return p, ok, nil
|
||||
// fakeAccounts holds accounts by id, each with the role the shipped policies
|
||||
// read, and the channel credentials linked to them.
|
||||
type fakeAccounts struct {
|
||||
accounts map[governance.IdentityID]governance.Identity
|
||||
roles map[governance.IdentityID]governance.Role
|
||||
linked map[governance.Subject]governance.IdentityID
|
||||
}
|
||||
|
||||
// TestVerifyAcceptsAnAnswerOnlyFromAPersonWhoMayGiveIt checks that a verified
|
||||
// identity alone is not enough: the request kind, escalation step and required
|
||||
// authority also determine who can respond.
|
||||
func TestVerifyAcceptsAnAnswerOnlyFromAPersonWhoMayGiveIt(t *testing.T) {
|
||||
people := fakePeople{
|
||||
"telegram:1001": {ID: "owner", Name: "Owner", Approver: true},
|
||||
"telegram:1002": {ID: "lead", Name: "Authority", Approver: true, Authority: true},
|
||||
"telegram:1003": {ID: "bystander", Name: "Bystander"},
|
||||
"telegram:1004": {ID: "second", Name: "Second", Approver: true},
|
||||
func (f fakeAccounts) ResolveSubject(_ context.Context, s governance.Subject) (governance.Identity, error) {
|
||||
id, ok := f.linked[s]
|
||||
if !ok {
|
||||
return governance.Identity{}, governance.ErrIdentityNotFound
|
||||
}
|
||||
action := func(level string, asked ...string) store.Request {
|
||||
return store.Request{Kind: KindAction, Level: level, Asked: `["` + strings.Join(asked, `","`) + `"]`}
|
||||
return f.accounts[id], nil
|
||||
}
|
||||
|
||||
func (f fakeAccounts) Get(_ context.Context, id governance.IdentityID) (governance.Identity, error) {
|
||||
account, ok := f.accounts[id]
|
||||
if !ok {
|
||||
return governance.Identity{}, governance.ErrIdentityNotFound
|
||||
}
|
||||
return account, nil
|
||||
}
|
||||
|
||||
func (f fakeAccounts) PrincipalFor(_ context.Context, id governance.IdentityID) (governance.Principal, error) {
|
||||
return governance.Principal{
|
||||
IdentityID: id,
|
||||
Org: governance.DefaultOrgID,
|
||||
Memberships: []governance.Membership{{IdentityID: id, OrgID: governance.DefaultOrgID, Role: f.roles[id]}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newAccounts() fakeAccounts {
|
||||
f := fakeAccounts{
|
||||
accounts: map[governance.IdentityID]governance.Identity{},
|
||||
roles: map[governance.IdentityID]governance.Role{},
|
||||
linked: map[governance.Subject]governance.IdentityID{},
|
||||
}
|
||||
for id, role := range map[governance.IdentityID]governance.Role{
|
||||
"admin": governance.RoleAdmin, "owner": governance.RoleOwner,
|
||||
"developer": governance.RoleDeveloper, "viewer": governance.RoleViewer,
|
||||
} {
|
||||
f.accounts[id] = governance.Identity{ID: id, Kind: governance.KindUser, DisplayName: string(id), Lifecycle: governance.LifecycleActive}
|
||||
f.roles[id] = role
|
||||
f.linked[governance.Subject{Issuer: "telegram", Subject: "tg-" + string(id)}] = id
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// shipped is the access chain an install starts with: admin and owner may
|
||||
// approve, a developer or viewer may not.
|
||||
func shipped() governance.Authorizer {
|
||||
return governance.NewEngine(governance.ShippedOrgPolicies(governance.DefaultOrgID))
|
||||
}
|
||||
|
||||
// approveOnlyForDevelopers grants approve, and nothing about policy, to the
|
||||
// developer role.
|
||||
func approveOnlyForDevelopers() governance.Authorizer {
|
||||
return governance.NewEngine([]governance.Policy{{
|
||||
ID: "developers-approve", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID,
|
||||
Text: `permit(principal, action == Archie::Action::"approve", resource) when {
|
||||
resource.org == principal.org && principal.role == "developer"
|
||||
};`,
|
||||
}})
|
||||
}
|
||||
|
||||
// TestChannelAnswerComesFromALinkedAccountWhoseRoleMayApprove guards the
|
||||
// channel answer path: the channel credential resolves to an account, and
|
||||
// role alone decides whether that account may answer, as for any other
|
||||
// permission. A credential no account has linked is refused.
|
||||
func TestChannelAnswerComesFromALinkedAccountWhoseRoleMayApprove(t *testing.T) {
|
||||
action := func(level string) store.Request {
|
||||
return store.Request{ID: uuid.New(), Kind: KindAction, Level: level}
|
||||
}
|
||||
propose, escalate := judgement.ProposeAndWait.String(), judgement.Escalate.String()
|
||||
suspended := newAccounts()
|
||||
suspended.accounts["admin"] = governance.Identity{ID: "admin", Kind: governance.KindUser, DisplayName: "admin", Lifecycle: governance.LifecycleSuspended}
|
||||
bot := newAccounts()
|
||||
bot.accounts["admin"] = governance.Identity{ID: "admin", Kind: governance.KindBot, DisplayName: "admin", Lifecycle: governance.LifecycleActive}
|
||||
tests := []struct {
|
||||
name string
|
||||
identity string
|
||||
accounts fakeAccounts
|
||||
authz governance.Authorizer
|
||||
who string
|
||||
row store.Request
|
||||
wantName string
|
||||
wantErr error
|
||||
}{
|
||||
{name: "an approver can respond once notified", identity: "telegram:1001", row: action(propose, "owner")},
|
||||
{name: "an unmapped identity is refused", identity: "telegram:9999", row: action(propose, "owner"), wantErr: ErrUnverified},
|
||||
{name: "an unmapped identity can't answer a raise", identity: "telegram:9999", row: store.Request{Kind: KindRaise}, wantErr: ErrUnverified},
|
||||
{name: "an unlisted person who isn't an approver cannot respond", identity: "telegram:1003", row: action(propose, "owner"), wantErr: ErrNotApprover},
|
||||
{name: "the target owner can respond when explicitly asked", identity: "telegram:1003", row: action(propose, "bystander")},
|
||||
{name: "an approver without authority cannot respond to a raise", identity: "telegram:1001", row: store.Request{Kind: KindRaise}, wantErr: ErrNoAuthority},
|
||||
{name: "a person with authority can respond to a raise", identity: "telegram:1002", row: store.Request{Kind: KindRaise}},
|
||||
{name: "a later approver cannot respond before escalation", identity: "telegram:1004", row: action(propose, "owner"), wantErr: ErrNotAsked},
|
||||
{name: "a later approver can respond after escalation", identity: "telegram:1004", row: action(propose, "owner", "second")},
|
||||
{name: "a person with authority can respond without being asked", identity: "telegram:1002", row: action(propose, "owner")},
|
||||
{name: "the escalate level requires authority even when the approver was asked", identity: "telegram:1001", row: action(escalate, "owner"), wantErr: ErrNeedsAuthority},
|
||||
{name: "a person with authority can respond at the escalate level", identity: "telegram:1002", row: action(escalate, "owner")},
|
||||
{name: "an admin may approve", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: action(propose), wantName: "admin"},
|
||||
{name: "an owner may approve", accounts: newAccounts(), authz: shipped(), who: "tg-owner", row: action(propose), wantName: "owner"},
|
||||
{name: "an admin may answer an escalated action", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: action(escalate), wantName: "admin"},
|
||||
{name: "an admin may answer a raise", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: store.Request{ID: uuid.New(), Kind: KindRaise}, wantName: "admin"},
|
||||
{name: "a developer may not approve", accounts: newAccounts(), authz: shipped(), who: "tg-developer", row: action(propose), wantErr: ErrNotApprover},
|
||||
{name: "a viewer may not approve", accounts: newAccounts(), authz: shipped(), who: "tg-viewer", row: action(propose), wantErr: ErrNotApprover},
|
||||
{name: "a channel account no account has linked is refused", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: action(propose), wantErr: ErrUnlinked},
|
||||
{name: "an unlinked channel account can't answer a raise", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: store.Request{Kind: KindRaise}, wantErr: ErrUnlinked},
|
||||
{name: "a suspended account is refused", accounts: suspended, authz: shipped(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover},
|
||||
{name: "a bot is refused", accounts: bot, authz: shipped(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover},
|
||||
{name: "nobody may approve before access policies are attached", accounts: newAccounts(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover},
|
||||
{name: "a policy can grant approve to a role", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: action(propose), wantName: "developer"},
|
||||
{name: "approve alone does not answer an escalated action", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: action(escalate), wantErr: ErrNotApprover},
|
||||
{name: "approve alone does not answer a raise", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: store.Request{ID: uuid.New(), Kind: KindRaise}, wantErr: ErrNotApprover},
|
||||
}
|
||||
m := &Module{people: people}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
_, err := m.verify(context.Background(), tt.identity, tt.row)
|
||||
m := &Module{accounts: tt.accounts, authz: tt.authz}
|
||||
name, err := m.channelAnswerer(context.Background(), governance.Subject{Issuer: "telegram", Subject: tt.who}, tt.row)
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("err = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
if name != tt.wantName {
|
||||
t.Fatalf("name = %q, want %q", name, tt.wantName)
|
||||
}
|
||||
if tt.wantErr != nil && !refusal(err) {
|
||||
t.Fatalf("%v isn't recorded as a refusal", err)
|
||||
}
|
||||
|
||||
@@ -61,19 +61,27 @@ type Assertion struct {
|
||||
Credential jsontext.Value `json:"credential"`
|
||||
}
|
||||
|
||||
// caller returns the person the signed-in caller is, checked as a channel
|
||||
// identity is. The bootstrap token is no person, so it can't answer.
|
||||
// UseAuthorizer attaches the access policies an answer is judged against.
|
||||
// Until one is attached, no answer is accepted.
|
||||
func (m *Module) UseAuthorizer(a governance.Authorizer) { m.authz = a }
|
||||
|
||||
// caller returns the signed-in person, checked as a channel account is: their
|
||||
// role must let them answer. The bootstrap token is no person, so it can't
|
||||
// answer.
|
||||
func (m *Module) caller(ctx context.Context, row store.Request) (name, identity string, err error) {
|
||||
p, ok := governance.PrincipalFromContext(ctx)
|
||||
if !ok || p.IdentityID == governance.SystemID || p.Kind == governance.KindSystem {
|
||||
if !ok || p.IdentityID == governance.SystemID || p.Kind != governance.KindUser {
|
||||
return "", "", ErrNotSignedIn
|
||||
}
|
||||
identity = governance.AccountIdentity(p.IdentityID)
|
||||
who, err := m.verify(ctx, identity, row)
|
||||
if err != nil {
|
||||
identity = string(p.IdentityID)
|
||||
if err := m.mayAnswer(ctx, p, row); err != nil {
|
||||
return "", identity, err
|
||||
}
|
||||
return who.Name + " (" + identity + ")", identity, nil
|
||||
account, err := m.accounts.Get(ctx, p.IdentityID)
|
||||
if err != nil {
|
||||
return "", identity, fmt.Errorf("read account %s: %w", identity, err)
|
||||
}
|
||||
return account.DisplayName, identity, nil
|
||||
}
|
||||
|
||||
// authorise accepts an answer from the dashboard only from a person who may
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"encoding/json/jsontext"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -31,23 +30,22 @@ func (f *fakeConfirmer) Confirm(_ context.Context, _ string, _ []byte, subject s
|
||||
return f.err
|
||||
}
|
||||
|
||||
// TestDashboardAnswerComesFromAPersonWhoMayGiveIt guards the dashboard answer
|
||||
// path: the signed-in caller is checked as a channel identity is, so the
|
||||
// bootstrap token or an account no person holds can't approve, and approving
|
||||
// an action that can't be undone also needs a passkey assertion that the
|
||||
// confirmer accepts for this request.
|
||||
func TestDashboardAnswerComesFromAPersonWhoMayGiveIt(t *testing.T) {
|
||||
people := fakePeople{
|
||||
"account:owner": {ID: "owner", Name: "Owner", Approver: true},
|
||||
"account:bystander": {ID: "bystander", Name: "Bystander"},
|
||||
}
|
||||
// TestDashboardAnswerComesFromAnAccountWhoseRoleMayApprove guards the
|
||||
// dashboard answer path: the signed-in caller is judged by role as a channel
|
||||
// account is, so the bootstrap token or a member without approve can't answer,
|
||||
// and approving an action that can't be undone also needs a passkey assertion
|
||||
// that the confirmer accepts for this request.
|
||||
func TestDashboardAnswerComesFromAnAccountWhoseRoleMayApprove(t *testing.T) {
|
||||
signedIn := func(id string) *governance.Principal {
|
||||
return &governance.Principal{IdentityID: governance.IdentityID(id), Kind: governance.KindUser}
|
||||
p, _ := newAccounts().PrincipalFor(context.Background(), governance.IdentityID(id))
|
||||
p.Kind = governance.KindUser
|
||||
return &p
|
||||
}
|
||||
shared := governance.SharedTokenOwner()
|
||||
bot := &governance.Principal{IdentityID: "admin", Kind: governance.KindBot}
|
||||
request := uuid.New()
|
||||
row := func(irreversible bool) store.Request {
|
||||
return store.Request{ID: request, Kind: KindAction, Level: judgement.ProposeAndWait.String(), Asked: `["owner"]`, Irreversible: irreversible}
|
||||
return store.Request{ID: request, Kind: KindAction, Level: judgement.ProposeAndWait.String(), Irreversible: irreversible}
|
||||
}
|
||||
assertion := &Assertion{Token: "t", Credential: jsontext.Value(`{}`)}
|
||||
tests := []struct {
|
||||
@@ -59,22 +57,24 @@ func TestDashboardAnswerComesFromAPersonWhoMayGiveIt(t *testing.T) {
|
||||
confirmer *fakeConfirmer
|
||||
wantErr error
|
||||
}{
|
||||
{name: "a person on the path may approve", as: signedIn("owner"), row: row(false), approved: true},
|
||||
{name: "an admin may approve", as: signedIn("admin"), row: row(false), approved: true},
|
||||
{name: "an owner may approve", as: signedIn("owner"), row: row(false), approved: true},
|
||||
{name: "the bootstrap token is no person", as: &shared, row: row(false), approved: true, wantErr: ErrNotSignedIn},
|
||||
{name: "a bot is no person", as: bot, row: row(false), approved: true, wantErr: ErrNotSignedIn},
|
||||
{name: "a request with no one signed in is refused", as: nil, row: row(false), approved: true, wantErr: ErrNotSignedIn},
|
||||
{name: "an account no person holds is refused", as: signedIn("stranger"), row: row(false), approved: true, wantErr: ErrUnverified},
|
||||
{name: "a person who isn't an approver is refused", as: signedIn("bystander"), row: row(false), approved: true, wantErr: ErrNotApprover},
|
||||
{name: "a person who isn't an approver may not deny either", as: signedIn("bystander"), row: row(false), approved: false, wantErr: ErrNotApprover},
|
||||
{name: "an irreversible action needs an assertion", as: signedIn("owner"), row: row(true), approved: true, confirmer: &fakeConfirmer{}, wantErr: ErrNeedsFreshAuthentication},
|
||||
{name: "an irreversible action with no confirmer can't be approved", as: signedIn("owner"), row: row(true), approved: true, assertion: assertion, wantErr: ErrNeedsFreshAuthentication},
|
||||
{name: "a rejected assertion is refused", as: signedIn("owner"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{err: governance.ErrCredentialRejected}, wantErr: ErrFreshAuthenticationFailed},
|
||||
{name: "an accepted assertion approves", as: signedIn("owner"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}},
|
||||
{name: "a denial needs no assertion", as: signedIn("owner"), row: row(true), approved: false, confirmer: &fakeConfirmer{}},
|
||||
{name: "a person who isn't an approver can't approve with an assertion", as: signedIn("bystander"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}, wantErr: ErrNotApprover},
|
||||
{name: "a developer is refused", as: signedIn("developer"), row: row(false), approved: true, wantErr: ErrNotApprover},
|
||||
{name: "a viewer is refused", as: signedIn("viewer"), row: row(false), approved: true, wantErr: ErrNotApprover},
|
||||
{name: "a developer may not deny either", as: signedIn("developer"), row: row(false), approved: false, wantErr: ErrNotApprover},
|
||||
{name: "an irreversible action needs an assertion", as: signedIn("admin"), row: row(true), approved: true, confirmer: &fakeConfirmer{}, wantErr: ErrNeedsFreshAuthentication},
|
||||
{name: "an irreversible action with no confirmer can't be approved", as: signedIn("admin"), row: row(true), approved: true, assertion: assertion, wantErr: ErrNeedsFreshAuthentication},
|
||||
{name: "a rejected assertion is refused", as: signedIn("admin"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{err: governance.ErrCredentialRejected}, wantErr: ErrFreshAuthenticationFailed},
|
||||
{name: "an accepted assertion approves", as: signedIn("admin"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}},
|
||||
{name: "a denial needs no assertion", as: signedIn("admin"), row: row(true), approved: false, confirmer: &fakeConfirmer{}},
|
||||
{name: "a developer can't approve with an assertion", as: signedIn("developer"), row: row(true), approved: true, assertion: assertion, confirmer: &fakeConfirmer{}, wantErr: ErrNotApprover},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
m := &Module{people: people}
|
||||
m := &Module{accounts: newAccounts(), authz: shipped()}
|
||||
if tt.confirmer != nil {
|
||||
m.UseConfirmer(tt.confirmer)
|
||||
}
|
||||
@@ -86,8 +86,8 @@ func TestDashboardAnswerComesFromAPersonWhoMayGiveIt(t *testing.T) {
|
||||
if !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("err = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
if err == nil && !strings.Contains(by, "account:") {
|
||||
t.Fatalf("answered by %q, want the account's identity recorded", by)
|
||||
if err == nil && by != string(tt.as.IdentityID) {
|
||||
t.Fatalf("answered by %q, want the account's name recorded", by)
|
||||
}
|
||||
if tt.confirmer != nil && len(tt.confirmer.subjects) == 1 && tt.confirmer.subjects[0] != confirmationSubject(request) {
|
||||
t.Fatalf("confirmed %q, want the assertion confirmed for this request", tt.confirmer.subjects[0])
|
||||
|
||||
@@ -48,7 +48,7 @@ func (m *Module) Escalate(ctx context.Context, id uuid.UUID, n int, to governanc
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, _, err := m.store.Escalate(ctx, m.orgID, id, n, to.Person, until); err != nil {
|
||||
if _, _, err := m.store.Escalate(ctx, m.orgID, id, n, until); err != nil {
|
||||
return err
|
||||
}
|
||||
m.log.InfoContext(ctx, "approval request escalated", "request", id, "step", n)
|
||||
|
||||
@@ -37,11 +37,8 @@ type Request struct {
|
||||
AnsweredAt sql.NullTime `db:"answered_at"`
|
||||
AnsweredBy sql.NullString `db:"answered_by"`
|
||||
AnsweredVia sql.NullString `db:"answered_via"`
|
||||
// Asked is a JSON array of person IDs reached so far, not just the
|
||||
// person assigned to the current step.
|
||||
Step int `db:"step"`
|
||||
StepDeadline sql.NullTime `db:"step_deadline"`
|
||||
Asked string `db:"asked"`
|
||||
Step int `db:"step"`
|
||||
StepDeadline sql.NullTime `db:"step_deadline"`
|
||||
// ChangeRequest is whether the request went through a change request
|
||||
// rather than the approvers' channels.
|
||||
ChangeRequest bool `db:"change_request"`
|
||||
@@ -60,7 +57,7 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} }
|
||||
|
||||
const requestColumns = `id, org_id, run_id, key, decision_id, kind, digest, connector, action, target_kind,
|
||||
target_id, level, irreversible, summary, state, deadline, created_at, answered_at, answered_by, answered_via,
|
||||
step, step_deadline, asked::text AS asked, change_request, counted, discarded_because`
|
||||
step, step_deadline, change_request, counted, discarded_because`
|
||||
|
||||
// Put inserts r or returns the existing request for the same organisation,
|
||||
// run and key.
|
||||
@@ -68,12 +65,12 @@ func (s *Store) Put(ctx context.Context, r Request) (Request, error) {
|
||||
var out Request
|
||||
err := s.db.GetContext(ctx, &out, `
|
||||
INSERT INTO approvals.requests (id, org_id, run_id, key, decision_id, kind, digest, connector, action,
|
||||
target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, asked, change_request)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, CAST($18 AS jsonb), $19)
|
||||
target_kind, target_id, level, irreversible, summary, state, deadline, step_deadline, change_request)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
|
||||
ON CONFLICT (org_id, run_id, key) DO NOTHING
|
||||
RETURNING `+requestColumns,
|
||||
r.ID, r.OrgID, r.RunID, r.Key, r.DecisionID, r.Kind, r.Digest, r.Connector, r.Action, r.TargetKind,
|
||||
r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.askedOrEmpty(), r.ChangeRequest)
|
||||
r.TargetID, r.Level, r.Irreversible, r.Summary, r.State, r.Deadline, r.StepDeadline, r.ChangeRequest)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return s.Get(ctx, r.OrgID, r.RunID, r.Key)
|
||||
}
|
||||
@@ -83,13 +80,6 @@ func (s *Store) Put(ctx context.Context, r Request) (Request, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r Request) askedOrEmpty() string {
|
||||
if r.Asked == "" {
|
||||
return "[]"
|
||||
}
|
||||
return r.Asked
|
||||
}
|
||||
|
||||
// Get returns the request for one run's key.
|
||||
func (s *Store) Get(ctx context.Context, orgID string, runID uuid.UUID, key string) (Request, error) {
|
||||
var out Request
|
||||
@@ -122,17 +112,16 @@ func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, b
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Escalate advances a pending request to step, sets the deadline to until and
|
||||
// records person if supplied. It returns false if the request has already
|
||||
// reached that step or is no longer pending.
|
||||
func (s *Store) Escalate(ctx context.Context, orgID string, id uuid.UUID, step int, person string, until time.Time) (Request, bool, error) {
|
||||
// Escalate advances a pending request to step and sets the deadline to until.
|
||||
// It returns false if the request has already reached that step or is no
|
||||
// longer pending.
|
||||
func (s *Store) Escalate(ctx context.Context, orgID string, id uuid.UUID, step int, until time.Time) (Request, bool, error) {
|
||||
var out Request
|
||||
err := s.db.GetContext(ctx, &out, `
|
||||
UPDATE approvals.requests
|
||||
SET step = $3, step_deadline = $4,
|
||||
asked = CASE WHEN $5::text = '' OR asked @> to_jsonb($5::text) THEN asked ELSE asked || to_jsonb($5::text) END
|
||||
SET step = $3, step_deadline = $4
|
||||
WHERE org_id = $1 AND id = $2 AND state = 'pending' AND step < $3
|
||||
RETURNING `+requestColumns, orgID, id, step, until, person)
|
||||
RETURNING `+requestColumns, orgID, id, step, until)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Request{}, false, nil
|
||||
}
|
||||
|
||||
@@ -117,8 +117,8 @@ func bindingFor(orgID string, id, request uuid.UUID, t store.Turn, d judgement.D
|
||||
func approverIDs(path []governance.PathStep) []string {
|
||||
out := make([]string, 0, len(path))
|
||||
for _, st := range path {
|
||||
if st.Person != "" {
|
||||
out = append(out, st.Person)
|
||||
if st.Account != "" {
|
||||
out = append(out, st.Account)
|
||||
}
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -231,7 +231,7 @@ func newApprovalFixture(t *testing.T) *approvalFixture {
|
||||
f.d = Deps{
|
||||
People: fakePeople{alice: person(alice, governance.RoleAdmin)},
|
||||
Access: governance.NewEngine(governance.ShippedOrgPolicies(governance.DefaultOrgID)),
|
||||
Settings: runSettings{path: []governance.PathStep{{Person: alice}}},
|
||||
Settings: runSettings{path: []governance.PathStep{{Account: alice}}},
|
||||
Judge: f.judge, Approver: f.approver, Notifier: runNotifier{},
|
||||
}
|
||||
return f
|
||||
@@ -310,7 +310,7 @@ func TestRunApprovedRunsOnlyWhatWasApprovedAndOnlyOnce(t *testing.T) {
|
||||
{
|
||||
name: "the approvers changed while pending",
|
||||
change: func(f *approvalFixture) {
|
||||
f.d.Settings = runSettings{path: []governance.PathStep{{Person: bob}}}
|
||||
f.d.Settings = runSettings{path: []governance.PathStep{{Account: bob}}}
|
||||
},
|
||||
wantDiscard: "the people who may approve it changed",
|
||||
},
|
||||
|
||||
@@ -66,7 +66,7 @@ func (fakeApprover) Ask(_ context.Context, _ uuid.UUID, key string, _ judgement.
|
||||
type fakeSettings struct{ Settings }
|
||||
|
||||
func (fakeSettings) EscalationPath(context.Context, string, bool) ([]governance.PathStep, error) {
|
||||
return []governance.PathStep{{Person: alice}}, nil
|
||||
return []governance.PathStep{{Account: alice}}, nil
|
||||
}
|
||||
|
||||
// taintDeps builds the module dependencies around a store holding one
|
||||
|
||||
@@ -84,6 +84,9 @@ type Capabilities struct {
|
||||
Listens bool `json:"listens"`
|
||||
// TargetFacts says the connector answers target fact requests.
|
||||
TargetFacts bool `json:"target_facts"`
|
||||
// LinksAccounts says the connector can link a person's channel identity
|
||||
// to their account.
|
||||
LinksAccounts bool `json:"links_accounts"`
|
||||
}
|
||||
|
||||
// Event returns the named event type.
|
||||
@@ -109,12 +112,13 @@ func find(list []Capability, name string) (Capability, bool) {
|
||||
// capabilitiesOf lists what a connector described, each kind in name order.
|
||||
func capabilitiesOf(desc *pb.DescribeResponse) Capabilities {
|
||||
caps := Capabilities{
|
||||
Events: make([]Capability, 0, len(desc.GetEvents())),
|
||||
Actions: make([]Capability, 0, len(desc.GetActions())),
|
||||
Deliveries: make([]Capability, 0, len(desc.GetDeliveries())),
|
||||
Lookups: make([]Capability, 0, len(desc.GetLookups())),
|
||||
Listens: desc.GetListens(),
|
||||
TargetFacts: desc.GetTargetFacts(),
|
||||
Events: make([]Capability, 0, len(desc.GetEvents())),
|
||||
Actions: make([]Capability, 0, len(desc.GetActions())),
|
||||
Deliveries: make([]Capability, 0, len(desc.GetDeliveries())),
|
||||
Lookups: make([]Capability, 0, len(desc.GetLookups())),
|
||||
Listens: desc.GetListens(),
|
||||
TargetFacts: desc.GetTargetFacts(),
|
||||
LinksAccounts: desc.GetLinksAccounts(),
|
||||
}
|
||||
for _, e := range desc.GetEvents() {
|
||||
caps.Events = append(caps.Events, Capability{Name: e.GetName(), Description: e.GetDescription(), Schema: schemaOrEmpty(e.GetSchema())})
|
||||
|
||||
@@ -178,6 +178,8 @@ type Connector struct {
|
||||
listens bool
|
||||
// facts says it answers TargetFacts.
|
||||
facts bool
|
||||
// links says it serves LinkURL.
|
||||
links bool
|
||||
// settings is the schema it declared for its operator settings.
|
||||
settings []Setting
|
||||
// caps is everything it declared, in the form that is stored.
|
||||
@@ -204,6 +206,7 @@ func open(ctx context.Context, name string, client pb.ConnectorServiceClient, se
|
||||
deliveries: map[string]*jsonschema.Resolved{},
|
||||
listens: desc.GetListens(),
|
||||
facts: desc.GetTargetFacts(),
|
||||
links: desc.GetLinksAccounts(),
|
||||
settings: connectorSettings(desc.GetSettings()),
|
||||
caps: capabilitiesOf(desc),
|
||||
}
|
||||
@@ -348,6 +351,26 @@ func (c *Connector) TargetFacts(ctx context.Context, t Target) (TargetFacts, err
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LinksAccounts reports whether the connector can link a person's channel
|
||||
// identity to their account.
|
||||
func (c *Connector) LinksAccounts() bool { return c.links }
|
||||
|
||||
// LinkURL asks the connector for the URL that delivers a link code to it.
|
||||
func (c *Connector) LinkURL(ctx context.Context, code string) (string, error) {
|
||||
if !c.links {
|
||||
return "", fmt.Errorf("connector %q: %w", c.name, ErrUnknownName)
|
||||
}
|
||||
req := &pb.LinkURLRequest{Code: code}
|
||||
resp, err := c.client.LinkURL(ctx, req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("connector %q: link URL: %w", c.name, err)
|
||||
}
|
||||
if resp.GetUrl() == "" {
|
||||
return "", fmt.Errorf("connector %q: link URL: the connector returned none", c.name)
|
||||
}
|
||||
return resp.GetUrl(), nil
|
||||
}
|
||||
|
||||
// Declarations lists the connector's lookups and actions in name order.
|
||||
func (c *Connector) Declarations() []Declaration {
|
||||
out := make([]Declaration, 0, len(c.lookups)+len(c.actions))
|
||||
|
||||
@@ -203,6 +203,29 @@ func (m *Module) Delivering(delivery string) []*Connector {
|
||||
return out
|
||||
}
|
||||
|
||||
// LinkableChannels lists the running connectors that can link a person's
|
||||
// channel identity to their account, in name order.
|
||||
func (m *Module) LinkableChannels(context.Context) ([]string, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
var out []string
|
||||
for _, name := range slices.Sorted(maps.Keys(m.running)) {
|
||||
if m.running[name].LinksAccounts() {
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// LinkURL asks the running connector for the URL that delivers a link code.
|
||||
func (m *Module) LinkURL(ctx context.Context, connector, code string) (string, error) {
|
||||
c, ok := m.Get(connector)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("connector %q isn't running", connector)
|
||||
}
|
||||
return c.LinkURL(ctx, code)
|
||||
}
|
||||
|
||||
// Declarations lists every running connector's lookups and actions and every
|
||||
// MCP server's declared tools, ordered by name and then by tool name.
|
||||
func (m *Module) Declarations() []Declaration {
|
||||
|
||||
+111
-9
@@ -18,6 +18,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -25,9 +26,11 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/approvals"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/events/internal/match"
|
||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/runs"
|
||||
)
|
||||
|
||||
@@ -52,16 +55,31 @@ type Runs interface {
|
||||
// belonged to no run.
|
||||
type Deliveries interface {
|
||||
SentBy(ctx context.Context, channel string, ids ...string) (run uuid.UUID, found bool, err error)
|
||||
// Send writes text to one chat on a channel.
|
||||
Send(ctx context.Context, channel, chatID, text, key string) error
|
||||
}
|
||||
|
||||
// Answers settles the approval requests answer events name.
|
||||
type Answers interface {
|
||||
Settle(ctx context.Context, id uuid.UUID, identity, via string, approved bool) (bool, error)
|
||||
Settle(ctx context.Context, id uuid.UUID, who governance.Subject, via string, approved bool) (bool, error)
|
||||
}
|
||||
|
||||
// answerType is the event a channel emits when a person answers an approval
|
||||
// request.
|
||||
const answerType = "approval.answer"
|
||||
// Links binds the channel accounts that account.link events name to the
|
||||
// accounts that issued their codes.
|
||||
type Links interface {
|
||||
CompleteLink(ctx context.Context, issuer, subject, name, code string) (governance.Identity, error)
|
||||
// LinkingURL is the dashboard page where a person links a channel account.
|
||||
LinkingURL(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
// The events a channel emits. An answer carries the approval request and the
|
||||
// person's decision; a link carries the code the person sent to the channel.
|
||||
// Both name the sender as "<connector>:<channel user id>" in by, and may name
|
||||
// the chat to reply to in chat_id.
|
||||
const (
|
||||
answerType = "approval.answer"
|
||||
linkType = "account.link"
|
||||
)
|
||||
|
||||
// listenRetry is how long a listener waits after its stream breaks.
|
||||
const listenRetry = 5 * time.Second
|
||||
@@ -76,15 +94,16 @@ type Module struct {
|
||||
connectors Connectors
|
||||
runs Runs
|
||||
answers Answers
|
||||
links Links
|
||||
deliveries Deliveries
|
||||
log *slog.Logger
|
||||
poll time.Duration
|
||||
}
|
||||
|
||||
// NewModule returns the events module for orgID.
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Connectors, r Runs, a Answers, d Deliveries) *Module {
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Connectors, r Runs, a Answers, l Links, d Deliveries) *Module {
|
||||
st := store.New(db)
|
||||
m := &Module{orgID: orgID, store: st, reader: st, sealer: sealer, connectors: c, runs: r, answers: a, deliveries: d, log: log, poll: time.Second}
|
||||
m := &Module{orgID: orgID, store: st, reader: st, sealer: sealer, connectors: c, runs: r, answers: a, links: l, deliveries: d, log: log, poll: time.Second}
|
||||
m.parse = m.parseWith
|
||||
return m
|
||||
}
|
||||
@@ -291,18 +310,27 @@ func (m *Module) listen(ctx context.Context, src store.Source) {
|
||||
|
||||
// answer settles the approval request an answer event names. An answer that
|
||||
// can't settle it is logged and done with: the request's own record already
|
||||
// says why.
|
||||
// says why. A channel account no account has linked is told how to link it.
|
||||
func (m *Module) answer(ctx context.Context, e store.Event) error {
|
||||
var a struct {
|
||||
RequestID uuid.UUID `json:"request_id"`
|
||||
Approved bool `json:"approved"`
|
||||
By string `json:"by"`
|
||||
ChatID string `json:"chat_id"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Fields, &a); err != nil {
|
||||
m.log.WarnContext(ctx, "unreadable approval answer", "event", e.ID, "error", err)
|
||||
return nil
|
||||
}
|
||||
settled, err := m.answers.Settle(ctx, a.RequestID, a.By, e.Source, a.Approved)
|
||||
src, who, ok := m.sender(ctx, e, a.By)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
settled, err := m.answers.Settle(ctx, a.RequestID, who, e.Source, a.Approved)
|
||||
if errors.Is(err, approvals.ErrUnlinked) {
|
||||
m.replyUnlinked(ctx, e, src, a.ChatID)
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("settle approval %s: %w", a.RequestID, err)
|
||||
}
|
||||
@@ -312,6 +340,77 @@ func (m *Module) answer(ctx context.Context, e store.Event) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// link binds the channel account that sent a link code to the account that
|
||||
// issued the code, and tells the sender how it went. A code that doesn't work
|
||||
// is not retried.
|
||||
func (m *Module) link(ctx context.Context, e store.Event) error {
|
||||
var l struct {
|
||||
By string `json:"by"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
ChatID string `json:"chat_id"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Fields, &l); err != nil {
|
||||
m.log.WarnContext(ctx, "unreadable link request", "event", e.ID, "error", err)
|
||||
return nil
|
||||
}
|
||||
src, who, ok := m.sender(ctx, e, l.By)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
account, err := m.links.CompleteLink(ctx, who.Issuer, who.Subject, l.Name, l.Code)
|
||||
switch {
|
||||
case errors.Is(err, governance.ErrLinkCode):
|
||||
m.reply(ctx, e, src, l.ChatID, "That link code didn't work. Start again from your account page in the dashboard.")
|
||||
case errors.Is(err, governance.ErrLinkTaken):
|
||||
m.reply(ctx, e, src, l.ChatID, "That "+src.Connector+" account is already linked to another account.")
|
||||
case err != nil:
|
||||
return fmt.Errorf("link %s account: %w", src.Connector, err)
|
||||
default:
|
||||
m.log.InfoContext(ctx, "channel account linked", "event", e.ID, "connector", src.Connector, "account", account.ID)
|
||||
m.reply(ctx, e, src, l.ChatID, "Linked to "+account.DisplayName+".")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sender reads who sent a channel event. The connector comes from the event's
|
||||
// source, so a connector can only speak for its own accounts: by must name the
|
||||
// source's connector.
|
||||
func (m *Module) sender(ctx context.Context, e store.Event, by string) (store.Source, governance.Subject, bool) {
|
||||
src, err := m.reader.Source(ctx, e.OrgID, e.Source)
|
||||
if err != nil {
|
||||
m.log.WarnContext(ctx, "channel event from an unknown source", "event", e.ID, "source", e.Source, "error", err)
|
||||
return store.Source{}, governance.Subject{}, false
|
||||
}
|
||||
prefix, subject, found := strings.Cut(by, ":")
|
||||
if !found || prefix != src.Connector || subject == "" {
|
||||
m.log.WarnContext(ctx, "channel event names a sender outside its connector", "event", e.ID, "source", e.Source)
|
||||
return store.Source{}, governance.Subject{}, false
|
||||
}
|
||||
return src, governance.Subject{Issuer: src.Connector, Subject: subject}, true
|
||||
}
|
||||
|
||||
// replyUnlinked tells an unlinked channel account where to link it.
|
||||
func (m *Module) replyUnlinked(ctx context.Context, e store.Event, src store.Source, chatID string) {
|
||||
url, err := m.links.LinkingURL(ctx)
|
||||
if err != nil {
|
||||
m.log.WarnContext(ctx, "read the linking URL", "event", e.ID, "error", err)
|
||||
return
|
||||
}
|
||||
m.reply(ctx, e, src, chatID, "That "+src.Connector+" account isn't linked to an account, so your answer wasn't counted. Link it at "+url+" and answer again.")
|
||||
}
|
||||
|
||||
// reply sends text to the chat an event came from. A reply that fails is
|
||||
// logged and dropped: the event itself is already handled.
|
||||
func (m *Module) reply(ctx context.Context, e store.Event, src store.Source, chatID, text string) {
|
||||
if chatID == "" {
|
||||
return
|
||||
}
|
||||
if err := m.deliveries.Send(ctx, src.Connector, chatID, text, "reply:"+e.ID.String()); err != nil {
|
||||
m.log.WarnContext(ctx, "reply to a channel event", "event", e.ID, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// dispatch links a resolve to the event it resolves and starts no work for
|
||||
// it. Any other event starts one run per matching trigger, keyed so a retried
|
||||
// dispatch never starts a second run.
|
||||
@@ -321,8 +420,11 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
|
||||
// Archie's own message coming back starts nothing and proposes nothing.
|
||||
return false, nil
|
||||
}
|
||||
if e.Type == answerType {
|
||||
switch e.Type {
|
||||
case answerType:
|
||||
return false, m.answer(ctx, e)
|
||||
case linkType:
|
||||
return false, m.link(ctx, e)
|
||||
}
|
||||
linked, err := store.Link(ctx, tx, e)
|
||||
if err != nil || linked {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
type connectorSource struct{ src store.Source }
|
||||
|
||||
func (o connectorSource) Source(context.Context, string, string) (store.Source, error) {
|
||||
return o.src, nil
|
||||
}
|
||||
|
||||
// TestSenderMustBelongToTheSourcesConnector guards channel identities: the
|
||||
// issuer of a linked credential comes from the source's connector, so a
|
||||
// connector can't answer or link as an account of another connector.
|
||||
func TestSenderMustBelongToTheSourcesConnector(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
by string
|
||||
want governance.Subject
|
||||
ok bool
|
||||
}{
|
||||
{name: "its own account", by: "telegram:1001", want: governance.Subject{Issuer: "telegram", Subject: "1001"}, ok: true},
|
||||
{name: "an account with a colon in its id", by: "telegram:a:b", want: governance.Subject{Issuer: "telegram", Subject: "a:b"}, ok: true},
|
||||
{name: "another connector's account", by: "slack:1001"},
|
||||
{name: "no connector", by: "1001"},
|
||||
{name: "no account", by: "telegram:"},
|
||||
}
|
||||
m := &Module{reader: connectorSource{store.Source{Connector: "telegram"}}, log: slog.New(slog.DiscardHandler)}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
_, got, ok := m.sender(t.Context(), store.Event{Source: "chat"}, tt.by)
|
||||
if ok != tt.ok || got != tt.want {
|
||||
t.Fatalf("sender = %v %v, want %v %v", got, ok, tt.want, tt.ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,7 @@ func (m *Module) RegisterAccounts(api huma.API) {
|
||||
huma.Register(api, signedIn("list-personal-tokens", http.MethodGet, "/api/tokens", "List your personal API tokens", 0), m.listTokens)
|
||||
huma.Register(api, signedIn("create-personal-token", http.MethodPost, "/api/tokens", "Create a personal API token", http.StatusCreated), m.createToken)
|
||||
huma.Register(api, signedIn("revoke-personal-token", http.MethodDelete, "/api/tokens/{id}", "Revoke a personal API token", http.StatusNoContent), m.revokeToken)
|
||||
m.registerLinks(api, signedIn)
|
||||
huma.Register(api, signedIn("get-capabilities", http.MethodGet, "/api/capabilities", "Report which dashboard sections this binary serves", 0), m.capabilities)
|
||||
|
||||
huma.Register(api, admin("create-account", http.MethodPost, "/api/accounts", "Create an account", http.StatusCreated), m.createAccount)
|
||||
@@ -612,7 +613,7 @@ func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[
|
||||
p, signedIn := PrincipalFromContext(ctx)
|
||||
sections := map[string]bool{"chat": signedIn, "memory": signedIn}
|
||||
for _, name := range []string{
|
||||
"settings", "org_people", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "memory_admin",
|
||||
"settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "memory_admin",
|
||||
} {
|
||||
sections[name] = p.InstanceAdmin()
|
||||
}
|
||||
|
||||
@@ -15,10 +15,6 @@ import (
|
||||
// ErrNoPasskey means the signed-in person has no passkey to confirm with.
|
||||
var ErrNoPasskey = errors.New("no passkey is registered for this account")
|
||||
|
||||
// AccountIdentity is the channel identity a signed-in account answers as, so
|
||||
// a person is linked to an account in the same list as their channels.
|
||||
func AccountIdentity(id IdentityID) string { return "account:" + string(id) }
|
||||
|
||||
// BeginConfirmation starts a passkey assertion for the signed-in person. It
|
||||
// can be finished only by Confirm with the same subject, and only by that
|
||||
// person: a sign-in ceremony can't stand in for it, nor it for a sign-in.
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -117,10 +116,10 @@ type Settings struct {
|
||||
RecurrenceThreshold int
|
||||
// AttemptsPerRun is how many steps an agent may take in one run.
|
||||
AttemptsPerRun int
|
||||
// DefaultOwner is the id of the person who answers for what has no other
|
||||
// DefaultOwner is the id of the member who answers for what has no other
|
||||
// owner, or empty.
|
||||
DefaultOwner string
|
||||
// Escalation is the people an unanswered request moves through, in order,
|
||||
// Escalation is the members an unanswered request moves through, in order,
|
||||
// each with how long the request waits on them.
|
||||
Escalation []Step
|
||||
// Timing is when changing actions may run without asking.
|
||||
@@ -131,24 +130,24 @@ type Settings struct {
|
||||
ActionsPerDay int
|
||||
}
|
||||
|
||||
// Step is one stop on the escalation path: a person and how long an unanswered
|
||||
// Step is one stop on the escalation path: a member and how long an unanswered
|
||||
// request waits on them before it moves to the next.
|
||||
type Step struct {
|
||||
// Person is the id of the person the request is passed to.
|
||||
Person string
|
||||
// Account is the id of the member the request is passed to.
|
||||
Account string
|
||||
Deadline time.Duration
|
||||
}
|
||||
|
||||
// stepRow is a step as stored.
|
||||
type stepRow struct {
|
||||
Person string `json:"person"`
|
||||
Account string `json:"account"`
|
||||
DeadlineMS int64 `json:"deadline_ms"`
|
||||
}
|
||||
|
||||
// stepRequest is a step as the API shows and sets it. Its deadline travels as
|
||||
// a Go duration string, like the approval deadline.
|
||||
type stepRequest struct {
|
||||
Person string `json:"person"`
|
||||
Account string `json:"account"`
|
||||
Deadline string `json:"deadline"`
|
||||
}
|
||||
|
||||
@@ -180,7 +179,7 @@ func (s Settings) request() settingsRequest {
|
||||
func stepRequests(steps []Step) []stepRequest {
|
||||
out := make([]stepRequest, 0, len(steps))
|
||||
for _, st := range steps {
|
||||
out = append(out, stepRequest{Person: st.Person, Deadline: st.Deadline.String()})
|
||||
out = append(out, stepRequest{Account: st.Account, Deadline: st.Deadline.String()})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -194,7 +193,7 @@ func stepsOf(req []stepRequest) ([]Step, error) {
|
||||
if err != nil {
|
||||
return nil, errors.New("each escalation deadline is a duration, such as 4h")
|
||||
}
|
||||
out = append(out, Step{Person: r.Person, Deadline: d})
|
||||
out = append(out, Step{Account: r.Account, Deadline: d})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -259,6 +258,7 @@ type Module struct {
|
||||
authorizer Authorizer
|
||||
oidc *oidcLogin
|
||||
setup *SetupSignal
|
||||
channels ChannelLinks
|
||||
}
|
||||
|
||||
// NewModule returns the governance module for orgID. The ai-sdk provider
|
||||
@@ -320,7 +320,7 @@ func (m *Module) Settings(ctx context.Context) (Settings, error) {
|
||||
}
|
||||
escalation := make([]Step, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
escalation = append(escalation, Step{Person: r.Person, Deadline: time.Duration(r.DeadlineMS) * time.Millisecond})
|
||||
escalation = append(escalation, Step{Account: r.Account, Deadline: time.Duration(r.DeadlineMS) * time.Millisecond})
|
||||
}
|
||||
var timing Timing
|
||||
if err := json.Unmarshal(jsontext.Value(row.Timing), &timing); err != nil {
|
||||
@@ -385,8 +385,7 @@ func (m *Module) ApprovalDeadline(ctx context.Context) (time.Duration, error) {
|
||||
return set.ApprovalDeadline, nil
|
||||
}
|
||||
|
||||
// Register adds the settings API: organisation settings, the agent model and
|
||||
// people.
|
||||
// Register adds the settings API: organisation settings and the agent model.
|
||||
func (m *Module) Register(api huma.API) {
|
||||
tags := []string{"Governance"}
|
||||
huma.Register(api, huma.Operation{
|
||||
@@ -417,14 +416,6 @@ func (m *Module) Register(api huma.API) {
|
||||
OperationID: "test-agent-model", Method: http.MethodPost, Path: "/api/settings/agent-model/test",
|
||||
Summary: "Ask a model one question before saving it", Tags: tags,
|
||||
}, m.testAgentModel)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "list-people", Method: http.MethodGet, Path: "/api/people",
|
||||
Summary: "List the people", Tags: tags,
|
||||
}, m.getPeople)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "put-people", Method: http.MethodPut, Path: "/api/people",
|
||||
Summary: "Replace the people", Tags: tags,
|
||||
}, m.putPeople)
|
||||
}
|
||||
|
||||
func (m *Module) getSettings(ctx context.Context, _ *struct{}) (*httpapi.Reply[settingsRequest], error) {
|
||||
@@ -455,17 +446,17 @@ func (m *Module) putSettings(ctx context.Context, in *struct{ Body settingsReque
|
||||
if err := set.validate(); err != nil {
|
||||
return nil, huma.NewError(http.StatusBadRequest, err.Error())
|
||||
}
|
||||
people, err := m.store.People(ctx, m.orgID)
|
||||
members, err := m.memberNames(ctx)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(ctx, "read people", "error", err)
|
||||
m.log.ErrorContext(ctx, "read members", "error", err)
|
||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the settings")
|
||||
}
|
||||
if err := set.knows(people); err != nil {
|
||||
if err := set.knows(members); err != nil {
|
||||
return nil, huma.NewError(http.StatusBadRequest, err.Error())
|
||||
}
|
||||
rows := make([]stepRow, 0, len(set.Escalation))
|
||||
for _, st := range set.Escalation {
|
||||
rows = append(rows, stepRow{Person: st.Person, DeadlineMS: st.Deadline.Milliseconds()})
|
||||
rows = append(rows, stepRow{Account: st.Account, DeadlineMS: st.Deadline.Milliseconds()})
|
||||
}
|
||||
escalation, err := json.Marshal(rows)
|
||||
if err != nil {
|
||||
@@ -523,28 +514,41 @@ func validDeadlines(path []Step) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// knows checks that the default owner and every person on the escalation path
|
||||
// is one of people, and that no one is on the path twice.
|
||||
func (s Settings) knows(people []store.Person) error {
|
||||
known := func(id string) bool {
|
||||
return slices.ContainsFunc(people, func(p store.Person) bool { return p.ID.String() == id })
|
||||
}
|
||||
if s.DefaultOwner != "" && !known(s.DefaultOwner) {
|
||||
return errors.New("the default owner must be one of the people")
|
||||
// knows checks that the default owner and every account on the escalation
|
||||
// path is one of members, and that no one is on the path twice.
|
||||
func (s Settings) knows(members map[string]string) error {
|
||||
if _, ok := members[s.DefaultOwner]; s.DefaultOwner != "" && !ok {
|
||||
return errors.New("the default owner must be a member")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, st := range s.Escalation {
|
||||
if !known(st.Person) {
|
||||
return errors.New("everyone on the escalation path must be one of the people")
|
||||
if _, ok := members[st.Account]; !ok {
|
||||
return errors.New("everyone on the escalation path must be a member")
|
||||
}
|
||||
if seen[st.Person] {
|
||||
return errors.New("a person can be on the escalation path once")
|
||||
if seen[st.Account] {
|
||||
return errors.New("a member can be on the escalation path once")
|
||||
}
|
||||
seen[st.Person] = true
|
||||
seen[st.Account] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// memberNames returns the display name of each person who holds an org-wide
|
||||
// membership, by account id. Agents and service accounts never answer.
|
||||
func (m *Module) memberNames(ctx context.Context) (map[string]string, error) {
|
||||
members, err := m.ListMembers(ctx, DefaultOrgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]string, len(members))
|
||||
for _, member := range members {
|
||||
if member.Kind == KindUser && member.WorkspaceID == "" {
|
||||
out[string(member.IdentityID)] = member.DisplayName
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Module) listAgentModels(ctx context.Context, _ *struct{}) (*httpapi.Reply[map[string]Model], error) {
|
||||
rows, err := m.store.AgentModelRoles(ctx, m.orgID)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// LinkCode is a stored single-use code that links a channel credential to the
|
||||
// account that issued it.
|
||||
type LinkCode struct {
|
||||
IdentityID string `db:"identity_id"`
|
||||
Issuer string `db:"issuer"`
|
||||
ExpiresAt time.Time `db:"expires_at"`
|
||||
UsedAt sql.NullTime `db:"used_at"`
|
||||
Lifecycle string `db:"lifecycle"`
|
||||
}
|
||||
|
||||
// PutLinkCode stores the hash of a code issued by an account for one channel
|
||||
// connector, and drops that account's codes that have run out.
|
||||
func (s *Store) PutLinkCode(ctx context.Context, hash, identityID, issuer string, now, expires time.Time) error {
|
||||
return s.withTx(ctx, func(tx *sqlx.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM governance.link_codes WHERE identity_id = $1 AND (expires_at <= $2 OR used_at IS NOT NULL)`,
|
||||
identityID, now); err != nil {
|
||||
return fmt.Errorf("drop spent link codes: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO governance.link_codes (code_hash, identity_id, issuer, expires_at) VALUES ($1, $2, $3, $4)`,
|
||||
hash, identityID, issuer, expires); err != nil {
|
||||
return fmt.Errorf("store link code: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// RedeemLinkCode links the channel credential (issuer, subject) to the account
|
||||
// that issued the code, once. The code row is locked while check judges it, so
|
||||
// two redemptions of one code can't both pass. check also gets the account the
|
||||
// credential is already linked to, empty when none; a refusal leaves the code
|
||||
// unspent.
|
||||
func (s *Store) RedeemLinkCode(ctx context.Context, hash, subject, name string, now time.Time, check func(code LinkCode, linkedTo string) error) (string, error) {
|
||||
var account string
|
||||
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
|
||||
var code LinkCode
|
||||
err := tx.GetContext(ctx, &code, `
|
||||
SELECT c.identity_id, c.issuer, c.expires_at, c.used_at, i.lifecycle
|
||||
FROM governance.link_codes c JOIN governance.identities i ON i.id = c.identity_id
|
||||
WHERE c.code_hash = $1
|
||||
FOR UPDATE OF c`, hash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("read link code: %w", err)
|
||||
}
|
||||
var bound string
|
||||
err = tx.GetContext(ctx, &bound, `
|
||||
SELECT identity_id FROM governance.identity_subjects WHERE issuer = $1 AND subject = $2 FOR UPDATE`,
|
||||
code.Issuer, subject)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("read channel credential: %w", err)
|
||||
}
|
||||
if err := check(code, bound); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE governance.link_codes SET used_at = $2 WHERE code_hash = $1`, hash, now); err != nil {
|
||||
return fmt.Errorf("spend link code: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO governance.identity_subjects (issuer, subject, identity_id, bound_at, name)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (issuer, subject) DO UPDATE SET name = EXCLUDED.name`,
|
||||
code.Issuer, subject, code.IdentityID, now, name); err != nil {
|
||||
return fmt.Errorf("link channel credential: %w", err)
|
||||
}
|
||||
orgID, err := auditSubjectOrg(ctx, tx, "", code.IdentityID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
account = code.IdentityID
|
||||
return insertIdentityEvent(ctx, tx, IdentityEventRow{
|
||||
IdentityID: account, EventType: "bind_subject",
|
||||
FromLifecycle: code.Lifecycle, ToLifecycle: code.Lifecycle,
|
||||
DisplayName: code.Issuer + ":" + subject, ActorID: account, Source: "channel link",
|
||||
RequestID: "link:" + hash, At: now, OrgID: orgID,
|
||||
})
|
||||
})
|
||||
return account, err
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Person is one person of the organisation with the identities that are
|
||||
// theirs.
|
||||
type Person struct {
|
||||
ID uuid.UUID `db:"id"`
|
||||
Name string `db:"name"`
|
||||
Authority bool `db:"authority"`
|
||||
Identities []string `db:"-"`
|
||||
}
|
||||
|
||||
// People returns the organisation's people by name, each with their identities.
|
||||
func (s *Store) People(ctx context.Context, orgID string) ([]Person, error) {
|
||||
var people []Person
|
||||
if err := s.db.SelectContext(ctx, &people, `
|
||||
SELECT id, name, authority FROM governance.people WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list people: %w", err)
|
||||
}
|
||||
var ids []struct {
|
||||
PersonID uuid.UUID `db:"person_id"`
|
||||
Identity string `db:"identity"`
|
||||
}
|
||||
if err := s.db.SelectContext(ctx, &ids, `
|
||||
SELECT person_id, identity FROM governance.person_identities WHERE org_id = $1 ORDER BY identity`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list identities: %w", err)
|
||||
}
|
||||
byID := make(map[uuid.UUID]int, len(people))
|
||||
for i := range people {
|
||||
people[i].Identities = []string{}
|
||||
byID[people[i].ID] = i
|
||||
}
|
||||
for _, id := range ids {
|
||||
if i, ok := byID[id.PersonID]; ok {
|
||||
people[i].Identities = append(people[i].Identities, id.Identity)
|
||||
}
|
||||
}
|
||||
return people, nil
|
||||
}
|
||||
|
||||
// PersonByIdentity returns the person who holds identity; ok is false when no
|
||||
// one does.
|
||||
func (s *Store) PersonByIdentity(ctx context.Context, orgID, identity string) (Person, bool, error) {
|
||||
var p Person
|
||||
err := s.db.GetContext(ctx, &p, `
|
||||
SELECT p.id, p.name, p.authority FROM governance.people p
|
||||
JOIN governance.person_identities i ON i.person_id = p.id AND i.org_id = p.org_id
|
||||
WHERE i.org_id = $1 AND i.identity = $2`, orgID, identity)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Person{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return Person{}, false, fmt.Errorf("read person by identity: %w", err)
|
||||
}
|
||||
return p, true, nil
|
||||
}
|
||||
|
||||
// ReplacePeople makes people the organisation's whole set: it adds or updates
|
||||
// each one, and removes anyone not listed.
|
||||
func (s *Store) ReplacePeople(ctx context.Context, orgID string, people []Person) error {
|
||||
tx, err := s.db.BeginTxx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin replace people: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
keep := make([]uuid.UUID, 0, len(people))
|
||||
for _, p := range people {
|
||||
keep = append(keep, p.ID)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
DELETE FROM governance.people WHERE org_id = $1 AND NOT (id = ANY($2))`, orgID, keep); err != nil {
|
||||
return fmt.Errorf("remove people: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM governance.person_identities WHERE org_id = $1`, orgID); err != nil {
|
||||
return fmt.Errorf("clear identities: %w", err)
|
||||
}
|
||||
for _, p := range people {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO governance.people (id, org_id, name, authority) VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, authority = EXCLUDED.authority`,
|
||||
p.ID, orgID, p.Name, p.Authority); err != nil {
|
||||
return fmt.Errorf("save person %q: %w", p.Name, err)
|
||||
}
|
||||
for _, identity := range p.Identities {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO governance.person_identities (org_id, identity, person_id) VALUES ($1, $2, $3)`,
|
||||
orgID, identity, p.ID); err != nil {
|
||||
return fmt.Errorf("save identity %q: %w", identity, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit people: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/governance/internal/store"
|
||||
)
|
||||
|
||||
// linkCodeLifetime is how long a link code can be used after it is issued.
|
||||
const linkCodeLifetime = 10 * time.Minute
|
||||
|
||||
var (
|
||||
// ErrLinkCode means the link code is unknown, already used, expired or
|
||||
// was issued for another channel. The cases are not told apart, so a
|
||||
// guess learns nothing.
|
||||
ErrLinkCode = errors.New("that link code isn't valid")
|
||||
// ErrLinkTaken means the channel account is already linked to another
|
||||
// Archie account.
|
||||
ErrLinkTaken = errors.New("that channel account is already linked to another account")
|
||||
// ErrNoChannel means no installed connector can link accounts under that
|
||||
// name.
|
||||
ErrNoChannel = errors.New("no installed channel links accounts under that name")
|
||||
)
|
||||
|
||||
// ChannelLinks is what linking an account needs from the installed
|
||||
// connectors: which of them can link, and the URL a person opens to send a
|
||||
// code to the connector's bot.
|
||||
type ChannelLinks interface {
|
||||
// LinkableChannels returns the names of the connectors that can link.
|
||||
LinkableChannels(ctx context.Context) ([]string, error)
|
||||
// LinkURL asks the named connector for the URL that delivers code to it.
|
||||
LinkURL(ctx context.Context, connector, code string) (string, error)
|
||||
}
|
||||
|
||||
// UseChannels gives the module the connectors an account links channels on.
|
||||
func (m *Module) UseChannels(c ChannelLinks) { m.channels = c }
|
||||
|
||||
// linkCode is a stored link code, as redeeming judges it.
|
||||
type linkCode struct {
|
||||
account string
|
||||
issuer string
|
||||
expiresAt time.Time
|
||||
used bool
|
||||
active bool
|
||||
}
|
||||
|
||||
// redeem says whether the code may link a credential from the connector issuer
|
||||
// at now. linkedTo is the account that already holds the credential, empty
|
||||
// when none does: a credential is never moved from one account to another.
|
||||
func (c linkCode) redeem(issuer, linkedTo string, now time.Time) error {
|
||||
if c.used || !c.active || c.issuer != issuer || !now.Before(c.expiresAt) {
|
||||
return ErrLinkCode
|
||||
}
|
||||
if linkedTo != "" && linkedTo != c.account {
|
||||
return ErrLinkTaken
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LinkStart is a link code ready to be opened in a channel.
|
||||
type LinkStart struct {
|
||||
URL string `json:"url"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// BeginLink issues the signed-in account a single-use code for the named
|
||||
// connector and returns the URL that delivers it.
|
||||
func (m *Module) BeginLink(ctx context.Context, connector string) (LinkStart, error) {
|
||||
p, ok := PrincipalFromContext(ctx)
|
||||
if !ok || p.Kind != KindUser {
|
||||
return LinkStart{}, ErrCredentialRejected
|
||||
}
|
||||
if err := m.linkable(ctx, connector); err != nil {
|
||||
return LinkStart{}, err
|
||||
}
|
||||
code := rand.Text()
|
||||
now := time.Now().UTC()
|
||||
expires := now.Add(linkCodeLifetime)
|
||||
if err := m.store.PutLinkCode(ctx, sessionHash(code), string(p.IdentityID), connector, now, expires); err != nil {
|
||||
return LinkStart{}, err
|
||||
}
|
||||
url, err := m.channels.LinkURL(ctx, connector, code)
|
||||
if err != nil {
|
||||
return LinkStart{}, fmt.Errorf("ask %s for the link URL: %w", connector, err)
|
||||
}
|
||||
return LinkStart{URL: url, ExpiresAt: expires}, nil
|
||||
}
|
||||
|
||||
func (m *Module) linkable(ctx context.Context, connector string) error {
|
||||
if m.channels == nil {
|
||||
return ErrNoChannel
|
||||
}
|
||||
names, err := m.channels.LinkableChannels(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !slices.Contains(names, connector) {
|
||||
return ErrNoChannel
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CompleteLink links the channel account subject on the connector issuer to
|
||||
// the account that issued code, and returns that account. The credential
|
||||
// comes from the connector's own event, so the person never proves it here.
|
||||
func (m *Module) CompleteLink(ctx context.Context, issuer, subject, name, code string) (Identity, error) {
|
||||
subj := Subject{Issuer: issuer, Subject: subject}
|
||||
if err := subj.Validate(); err != nil || code == "" {
|
||||
return Identity{}, ErrLinkCode
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
account, err := m.store.RedeemLinkCode(ctx, sessionHash(code), subject, strings.TrimSpace(name), now, func(row store.LinkCode, linkedTo string) error {
|
||||
return linkCode{
|
||||
account: row.IdentityID, issuer: row.Issuer, expiresAt: row.ExpiresAt,
|
||||
used: row.UsedAt.Valid, active: row.Lifecycle == string(LifecycleActive),
|
||||
}.redeem(issuer, linkedTo, now)
|
||||
})
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return Identity{}, ErrLinkCode
|
||||
}
|
||||
if err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
return m.Get(ctx, IdentityID(account))
|
||||
}
|
||||
|
||||
// ChannelLink is one channel account linked to the signed-in account.
|
||||
type ChannelLink struct {
|
||||
Connector string `json:"connector"`
|
||||
Subject string `json:"subject"`
|
||||
Name string `json:"name"`
|
||||
LinkedAt time.Time `json:"linked_at"`
|
||||
}
|
||||
|
||||
// ChannelsBody is what the account page shows: the connectors that can link,
|
||||
// and the channel accounts already linked.
|
||||
type ChannelsBody struct {
|
||||
Connectors []string `json:"connectors"`
|
||||
Linked []ChannelLink `json:"linked"`
|
||||
}
|
||||
|
||||
// Channels returns the connectors that can link and the signed-in account's
|
||||
// links on them.
|
||||
func (m *Module) Channels(ctx context.Context) (ChannelsBody, error) {
|
||||
body := ChannelsBody{Connectors: []string{}, Linked: []ChannelLink{}}
|
||||
p, ok := PrincipalFromContext(ctx)
|
||||
if !ok || p.Kind != KindUser || m.channels == nil {
|
||||
return body, nil
|
||||
}
|
||||
names, err := m.channels.LinkableChannels(ctx)
|
||||
if err != nil {
|
||||
return ChannelsBody{}, err
|
||||
}
|
||||
for _, name := range names {
|
||||
rows, err := m.store.ListIdentitySubjects(ctx, string(p.IdentityID), name)
|
||||
if err != nil {
|
||||
return ChannelsBody{}, err
|
||||
}
|
||||
body.Connectors = append(body.Connectors, name)
|
||||
for _, r := range rows {
|
||||
body.Linked = append(body.Linked, ChannelLink{Connector: name, Subject: r.Subject, Name: r.Name, LinkedAt: r.BoundAt})
|
||||
}
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// Unlink removes one of the signed-in account's channel links.
|
||||
func (m *Module) Unlink(ctx context.Context, connector, subject string) error {
|
||||
p, ok := PrincipalFromContext(ctx)
|
||||
if !ok || p.Kind != KindUser {
|
||||
return ErrCredentialRejected
|
||||
}
|
||||
if err := m.linkable(ctx, connector); err != nil {
|
||||
return err
|
||||
}
|
||||
return m.UnbindSubject(ctx, p.IdentityID, Subject{Issuer: connector, Subject: subject}, IdentityAudit{
|
||||
ActorID: p.IdentityID, Source: "channel link", RequestID: newRequestID("unlink"),
|
||||
})
|
||||
}
|
||||
|
||||
// LinkingURL is the dashboard page where a person links their channel
|
||||
// accounts, which a channel tells an unlinked person to open.
|
||||
func (m *Module) LinkingURL(ctx context.Context) (string, error) {
|
||||
settings, err := m.AuthenticationSettings(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimRight(settings.PublicURL, "/") + "/account", nil
|
||||
}
|
||||
|
||||
type channelPath struct {
|
||||
Connector string `path:"connector"`
|
||||
}
|
||||
|
||||
type unlinkInput struct {
|
||||
Connector string `path:"connector"`
|
||||
Subject string `path:"subject"`
|
||||
}
|
||||
|
||||
func (m *Module) listChannels(ctx context.Context, _ *struct{}) (*httpapi.Reply[ChannelsBody], error) {
|
||||
body, err := m.Channels(ctx)
|
||||
if err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
}
|
||||
return httpapi.OK(body), nil
|
||||
}
|
||||
|
||||
type linkReply struct {
|
||||
CacheControl string `header:"Cache-Control"`
|
||||
Body LinkStart
|
||||
}
|
||||
|
||||
func (m *Module) beginChannelLink(ctx context.Context, in *channelPath) (*linkReply, error) {
|
||||
start, err := m.BeginLink(ctx, in.Connector)
|
||||
if err != nil {
|
||||
return nil, m.linkError(ctx, err)
|
||||
}
|
||||
return &linkReply{CacheControl: "no-store", Body: start}, nil
|
||||
}
|
||||
|
||||
func (m *Module) unlinkChannel(ctx context.Context, in *unlinkInput) (*struct{}, error) {
|
||||
if err := m.Unlink(ctx, in.Connector, in.Subject); err != nil {
|
||||
return nil, m.linkError(ctx, err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *Module) linkError(ctx context.Context, err error) error {
|
||||
switch {
|
||||
case errors.Is(err, ErrNoChannel):
|
||||
return huma.Error404NotFound(ErrNoChannel.Error())
|
||||
case errors.Is(err, ErrIdentityNotFound):
|
||||
return huma.Error404NotFound("That channel account isn't linked.")
|
||||
}
|
||||
return m.accountError(ctx, err)
|
||||
}
|
||||
|
||||
func (m *Module) registerLinks(api huma.API, signedIn func(id, method, path, summary string, status int) huma.Operation) {
|
||||
huma.Register(api, signedIn("list-channel-links", http.MethodGet, "/api/account/channels", "List the channels you can link and your linked accounts", 0), m.listChannels)
|
||||
huma.Register(api, signedIn("begin-channel-link", http.MethodPost, "/api/account/channels/{connector}/link", "Start linking a channel account", 0), m.beginChannelLink)
|
||||
huma.Register(api, signedIn("unlink-channel", http.MethodDelete, "/api/account/channels/{connector}/{subject}", "Unlink a channel account", http.StatusNoContent), m.unlinkChannel)
|
||||
}
|
||||
|
||||
// AccountOf returns the id of the account that holds identity, written as
|
||||
// the connector and the account on it, such as "servicenow:jdoe"; ok is false
|
||||
// when no account holds it.
|
||||
func (m *Module) AccountOf(ctx context.Context, identity string) (string, bool, error) {
|
||||
issuer, subject, found := strings.Cut(identity, ":")
|
||||
if !found {
|
||||
return "", false, nil
|
||||
}
|
||||
account, err := m.ResolveSubject(ctx, Subject{Issuer: issuer, Subject: subject})
|
||||
if errors.Is(err, ErrIdentityNotFound) {
|
||||
return "", false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return string(account.ID), true, nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestLinkCodeLinksOnlyOnceToItsIssuer guards linking a channel account: a
|
||||
// code works once, before it expires, for the connector it was issued for and
|
||||
// for an active account, and a channel account that another account already
|
||||
// holds is never moved to the issuer.
|
||||
func TestLinkCodeLinksOnlyOnceToItsIssuer(t *testing.T) {
|
||||
now := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC)
|
||||
fresh := linkCode{account: "alice", issuer: "telegram", expiresAt: now.Add(time.Minute), active: true}
|
||||
tests := []struct {
|
||||
name string
|
||||
code linkCode
|
||||
issuer string
|
||||
linkedTo string
|
||||
want error
|
||||
}{
|
||||
{name: "a fresh code links", code: fresh, issuer: "telegram"},
|
||||
{name: "a channel account already linked to the issuer links again", code: fresh, issuer: "telegram", linkedTo: "alice"},
|
||||
{name: "a used code is refused", code: func() linkCode { c := fresh; c.used = true; return c }(), issuer: "telegram", want: ErrLinkCode},
|
||||
{name: "an expired code is refused", code: func() linkCode { c := fresh; c.expiresAt = now; return c }(), issuer: "telegram", want: ErrLinkCode},
|
||||
{name: "a code for another connector is refused", code: fresh, issuer: "slack", want: ErrLinkCode},
|
||||
{name: "a suspended account's code is refused", code: func() linkCode { c := fresh; c.active = false; return c }(), issuer: "telegram", want: ErrLinkCode},
|
||||
{name: "a channel account held by another account is refused", code: fresh, issuer: "telegram", linkedTo: "bob", want: ErrLinkTaken},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := tt.code.redeem(tt.issuer, tt.linkedTo, now); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("redeem = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+67
-30
@@ -4,17 +4,15 @@ import (
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/governance/internal/store"
|
||||
)
|
||||
|
||||
// PathStep is one stop on the route an unanswered approval request takes: who
|
||||
// it is passed to, and how long it waits there. The first step is the target's
|
||||
// owner when there is one, otherwise the default owner, who may be nobody, and
|
||||
// then anyone with authority.
|
||||
// then each member on the escalation path who may answer it.
|
||||
type PathStep struct {
|
||||
// Person is the id of the person asked at this step, or empty.
|
||||
Person string `json:"person"`
|
||||
// Account is the id of the member asked at this step, or empty.
|
||||
Account string `json:"account"`
|
||||
Name string `json:"name"`
|
||||
DeadlineMS int64 `json:"deadline_ms"`
|
||||
}
|
||||
@@ -32,51 +30,90 @@ func (m *Module) HasDefaultOwner(ctx context.Context) (bool, error) {
|
||||
}
|
||||
|
||||
// EscalationPath returns the route an approval request takes. owner is the
|
||||
// person who answers for the action's target, or empty when none is known. A
|
||||
// known owner is asked first and the default owner is the next step; an unknown
|
||||
// owner leaves the default owner first. Every later step is a person on the
|
||||
// escalation path. When the action needs authority, a step held by someone
|
||||
// without it is left out, so the request never moves to a person who could not
|
||||
// answer it.
|
||||
// account that answers for the action's target, or empty when none is known.
|
||||
// A known owner is asked first and the default owner is the next step; an
|
||||
// unknown owner leaves the default owner first. Every later step is a member
|
||||
// on the escalation path. A member the access policies don't let approve is
|
||||
// left out, so the request never moves to someone who could not answer it.
|
||||
// When the action needs authority over policy as well, so must they be allowed
|
||||
// to manage policies.
|
||||
func (m *Module) EscalationPath(ctx context.Context, owner string, needAuthority bool) ([]PathStep, error) {
|
||||
set, err := m.Settings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
people, err := m.store.People(ctx, m.orgID)
|
||||
names, err := m.memberNames(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return set.path(people, owner, needAuthority), nil
|
||||
actions := []Action{ActionApprove}
|
||||
if needAuthority {
|
||||
actions = append(actions, ActionManagePolicies)
|
||||
}
|
||||
candidates := []string{owner, set.DefaultOwner}
|
||||
for _, st := range set.Escalation {
|
||||
candidates = append(candidates, st.Account)
|
||||
}
|
||||
eligible := map[string]string{}
|
||||
for _, id := range candidates {
|
||||
name, member := names[id]
|
||||
if id == "" || !member {
|
||||
continue
|
||||
}
|
||||
may, err := m.Holds(ctx, IdentityID(id), Resource{Kind: KindApproval, ID: "path", Org: DefaultOrgID}, actions...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if may {
|
||||
eligible[id] = name
|
||||
}
|
||||
}
|
||||
return set.path(eligible, owner), nil
|
||||
}
|
||||
|
||||
func (s Settings) path(people []store.Person, owner string, needAuthority bool) []PathStep {
|
||||
find := func(id string) (store.Person, bool) {
|
||||
i := slices.IndexFunc(people, func(p store.Person) bool { return p.ID.String() == id })
|
||||
if i < 0 {
|
||||
return store.Person{}, false
|
||||
}
|
||||
return people[i], true
|
||||
}
|
||||
defaultOwner := PathStep{Person: s.DefaultOwner, DeadlineMS: s.ApprovalDeadline.Milliseconds()}
|
||||
if p, ok := find(s.DefaultOwner); ok {
|
||||
defaultOwner.Name = p.Name
|
||||
// path lays the route out over eligible, the members who may answer by id.
|
||||
func (s Settings) path(eligible map[string]string, owner string) []PathStep {
|
||||
defaultOwner := PathStep{DeadlineMS: s.ApprovalDeadline.Milliseconds()}
|
||||
if name, ok := eligible[s.DefaultOwner]; ok {
|
||||
defaultOwner.Account, defaultOwner.Name = s.DefaultOwner, name
|
||||
}
|
||||
var out []PathStep
|
||||
if p, ok := find(owner); ok && owner != "" && (p.Authority || !needAuthority) {
|
||||
out = append(out, PathStep{Person: owner, Name: p.Name, DeadlineMS: s.ApprovalDeadline.Milliseconds()})
|
||||
if name, ok := eligible[owner]; ok && owner != "" {
|
||||
out = append(out, PathStep{Account: owner, Name: name, DeadlineMS: s.ApprovalDeadline.Milliseconds()})
|
||||
}
|
||||
// With no owner to ask, the default owner leads even when nobody is set,
|
||||
// so the request still goes to anyone who may answer it.
|
||||
if len(out) == 0 || (s.DefaultOwner != "" && s.DefaultOwner != owner) {
|
||||
if len(out) == 0 || (defaultOwner.Account != "" && defaultOwner.Account != owner) {
|
||||
out = append(out, defaultOwner)
|
||||
}
|
||||
for _, st := range s.Escalation {
|
||||
p, ok := find(st.Person)
|
||||
if !ok || (needAuthority && !p.Authority) || slices.ContainsFunc(out, func(o PathStep) bool { return o.Person == st.Person }) {
|
||||
name, ok := eligible[st.Account]
|
||||
if !ok || slices.ContainsFunc(out, func(o PathStep) bool { return o.Account == st.Account }) {
|
||||
continue
|
||||
}
|
||||
out = append(out, PathStep{Person: st.Person, Name: p.Name, DeadlineMS: st.Deadline.Milliseconds()})
|
||||
out = append(out, PathStep{Account: st.Account, Name: name, DeadlineMS: st.Deadline.Milliseconds()})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Holds reports whether the account is allowed every one of actions on r by
|
||||
// the live access policies. It is false while no policy chain is attached.
|
||||
func (m *Module) Holds(ctx context.Context, account IdentityID, r Resource, actions ...Action) (bool, error) {
|
||||
if m.authorizer == nil {
|
||||
return false, nil
|
||||
}
|
||||
p, err := m.PrincipalFor(ctx, account)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, a := range actions {
|
||||
d := m.authorizer.Authorize(ctx, p, a, r, AccessContext{})
|
||||
if d.Err != nil {
|
||||
return false, d.Err
|
||||
}
|
||||
if !d.Allowed {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -4,62 +4,60 @@ import (
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/governance/internal/store"
|
||||
)
|
||||
|
||||
// TestPathNeverDropsBelowTheAuthorityTheActionNeeds guards the escalation
|
||||
// path: an action that needs authority is never passed to a person without
|
||||
// it, however the path is set, every step keeps its own deadline, and a target's
|
||||
// known owner is asked before the default owner, which an unknown owner leaves first.
|
||||
func TestPathNeverDropsBelowTheAuthorityTheActionNeeds(t *testing.T) {
|
||||
owner := store.Person{ID: uuid.New(), Name: "Owner"}
|
||||
peer := store.Person{ID: uuid.New(), Name: "Peer"}
|
||||
lead := store.Person{ID: uuid.New(), Name: "Lead", Authority: true}
|
||||
// TestPathAsksOnlyMembersWhoMayAnswer guards the escalation path: it never
|
||||
// passes a request to an account that was left out as unable to answer, every
|
||||
// step keeps its own deadline, and a target's known owner is asked before the
|
||||
// default owner, which an unknown owner leaves first.
|
||||
func TestPathAsksOnlyMembersWhoMayAnswer(t *testing.T) {
|
||||
set := Settings{
|
||||
ApprovalDeadline: time.Hour, DefaultOwner: owner.ID.String(),
|
||||
ApprovalDeadline: time.Hour, DefaultOwner: "owner",
|
||||
Escalation: []Step{
|
||||
{Person: peer.ID.String(), Deadline: 2 * time.Hour},
|
||||
{Person: lead.ID.String(), Deadline: 3 * time.Hour},
|
||||
{Account: "peer", Deadline: 2 * time.Hour},
|
||||
{Account: "lead", Deadline: 3 * time.Hour},
|
||||
},
|
||||
}
|
||||
people := []store.Person{owner, peer, lead}
|
||||
everyone := map[string]string{"owner": "Owner", "peer": "Peer", "lead": "Lead"}
|
||||
leadOnly := map[string]string{"owner": "Owner", "lead": "Lead"}
|
||||
tests := []struct {
|
||||
name string
|
||||
needAuthority bool
|
||||
// target is the person who answers for the action's target.
|
||||
name string
|
||||
eligible map[string]string
|
||||
// target is the account that answers for the action's target.
|
||||
target string
|
||||
want []string
|
||||
wantDeadlines []time.Duration
|
||||
}{
|
||||
{
|
||||
name: "an ordinary action goes through every step", want: []string{"Owner", "Peer", "Lead"},
|
||||
name: "an ordinary action goes through every step", eligible: everyone, want: []string{"Owner", "Peer", "Lead"},
|
||||
wantDeadlines: []time.Duration{time.Hour, 2 * time.Hour, 3 * time.Hour},
|
||||
},
|
||||
{
|
||||
name: "an action that needs authority skips a step without it", needAuthority: true,
|
||||
name: "a step that may not answer is skipped", eligible: leadOnly,
|
||||
want: []string{"Owner", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 3 * time.Hour},
|
||||
},
|
||||
{
|
||||
name: "the target's owner is asked first, then the default owner and the path", target: peer.ID.String(),
|
||||
name: "the target's owner is asked first, then the default owner and the path", eligible: everyone, target: "peer",
|
||||
want: []string{"Peer", "Owner", "Lead"}, wantDeadlines: []time.Duration{time.Hour, time.Hour, 3 * time.Hour},
|
||||
},
|
||||
{
|
||||
name: "a target owner without the authority an action needs is not asked", target: peer.ID.String(), needAuthority: true,
|
||||
name: "a target owner who may not answer is not asked", eligible: leadOnly, target: "peer",
|
||||
want: []string{"Owner", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 3 * time.Hour},
|
||||
},
|
||||
{
|
||||
name: "a target owner nobody knows leaves the default owner first", target: uuid.NewString(),
|
||||
name: "a target owner nobody knows leaves the default owner first", eligible: everyone, target: "stranger",
|
||||
want: []string{"Owner", "Peer", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 2 * time.Hour, 3 * time.Hour},
|
||||
},
|
||||
{
|
||||
name: "a default owner who may not answer leaves the first step open", eligible: map[string]string{"lead": "Lead"},
|
||||
want: []string{"", "Lead"}, wantDeadlines: []time.Duration{time.Hour, 3 * time.Hour},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var names []string
|
||||
var deadlines []time.Duration
|
||||
for _, st := range set.path(people, tt.target, tt.needAuthority) {
|
||||
for _, st := range set.path(tt.eligible, tt.target) {
|
||||
names = append(names, st.Name)
|
||||
deadlines = append(deadlines, st.Deadline())
|
||||
}
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/governance/internal/store"
|
||||
)
|
||||
|
||||
// Verified is a person an identity was verified as.
|
||||
type Verified struct {
|
||||
// ID is the person's id, as the settings name them.
|
||||
ID string
|
||||
Name string
|
||||
// Authority is whether the person may approve changes to policy and
|
||||
// ceilings, such as raising an action class.
|
||||
Authority bool
|
||||
// Approver is whether the person may answer an approval for an action:
|
||||
// they hold authority, are the default owner, or are on the escalation
|
||||
// path. A person a request was put to as the target's owner may answer
|
||||
// it without.
|
||||
Approver bool
|
||||
}
|
||||
|
||||
// Verify returns the person who holds identity, such as "telegram:1001"; ok is
|
||||
// false when no person does, so the identity is not verified.
|
||||
func (m *Module) Verify(ctx context.Context, identity string) (Verified, bool, error) {
|
||||
p, ok, err := m.store.PersonByIdentity(ctx, m.orgID, identity)
|
||||
if err != nil || !ok {
|
||||
return Verified{}, false, err
|
||||
}
|
||||
set, err := m.Settings(ctx)
|
||||
if err != nil {
|
||||
return Verified{}, false, err
|
||||
}
|
||||
id := p.ID.String()
|
||||
onPath := slices.ContainsFunc(set.Escalation, func(st Step) bool { return st.Person == id })
|
||||
approver := p.Authority || set.DefaultOwner == id || onPath
|
||||
return Verified{ID: id, Name: p.Name, Authority: p.Authority, Approver: approver}, true, nil
|
||||
}
|
||||
|
||||
// PersonID returns the id of the person who holds identity; ok is false when
|
||||
// nobody does.
|
||||
func (m *Module) PersonID(ctx context.Context, identity string) (string, bool, error) {
|
||||
p, ok, err := m.store.PersonByIdentity(ctx, m.orgID, identity)
|
||||
if err != nil || !ok {
|
||||
return "", false, err
|
||||
}
|
||||
return p.ID.String(), true, nil
|
||||
}
|
||||
|
||||
// personRequest is a person as the API shows and sets them. An empty id is a
|
||||
// new person.
|
||||
type personRequest struct {
|
||||
ID string `json:"id" required:"false" doc:"Empty for a new person"`
|
||||
Name string `json:"name"`
|
||||
Authority bool `json:"authority"`
|
||||
Identities []string `json:"identities"`
|
||||
}
|
||||
|
||||
func (m *Module) getPeople(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]personRequest], error) {
|
||||
people, err := m.store.People(ctx, m.orgID)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(ctx, "read people", "error", err)
|
||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't read the people")
|
||||
}
|
||||
out := make([]personRequest, 0, len(people))
|
||||
for _, p := range people {
|
||||
out = append(out, personRequest{ID: p.ID.String(), Name: p.Name, Authority: p.Authority, Identities: p.Identities})
|
||||
}
|
||||
return httpapi.OK(out), nil
|
||||
}
|
||||
|
||||
// putPeople replaces the organisation's people with the list in the request.
|
||||
func (m *Module) putPeople(ctx context.Context, in *struct{ Body []personRequest }) (*httpapi.Reply[[]personRequest], error) {
|
||||
req := in.Body
|
||||
people, err := peopleOf(req)
|
||||
if err != nil {
|
||||
return nil, huma.NewError(http.StatusBadRequest, err.Error())
|
||||
}
|
||||
set, err := m.Settings(ctx)
|
||||
if err != nil {
|
||||
m.log.ErrorContext(ctx, "read settings", "error", err)
|
||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the people")
|
||||
}
|
||||
if err := set.stillKnows(people); err != nil {
|
||||
return nil, huma.NewError(http.StatusConflict, err.Error())
|
||||
}
|
||||
if err := m.store.ReplacePeople(ctx, m.orgID, people); err != nil {
|
||||
m.log.ErrorContext(ctx, "put people", "error", err)
|
||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the people")
|
||||
}
|
||||
return m.getPeople(ctx, nil)
|
||||
}
|
||||
|
||||
// stillKnows refuses to remove a person the settings name.
|
||||
func (s Settings) stillKnows(people []store.Person) error {
|
||||
if err := s.knows(people); err != nil {
|
||||
return errors.New("a person the settings name can't be removed; change the settings first")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// peopleOf validates a request and returns the people it describes. A name is
|
||||
// kept once, and an identity belongs to one person.
|
||||
func peopleOf(req []personRequest) ([]store.Person, error) {
|
||||
people := make([]store.Person, 0, len(req))
|
||||
names := map[string]bool{}
|
||||
held := map[string]bool{}
|
||||
for _, pr := range req {
|
||||
name := strings.TrimSpace(pr.Name)
|
||||
if name == "" {
|
||||
return nil, errors.New("every person needs a name")
|
||||
}
|
||||
key := strings.ToLower(name)
|
||||
if names[key] {
|
||||
return nil, fmt.Errorf("%q is listed twice", name)
|
||||
}
|
||||
names[key] = true
|
||||
id := uuid.New()
|
||||
if pr.ID != "" {
|
||||
parsed, err := uuid.Parse(pr.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%q has an id that isn't valid", name)
|
||||
}
|
||||
id = parsed
|
||||
}
|
||||
idents := make([]string, 0, len(pr.Identities))
|
||||
for _, raw := range pr.Identities {
|
||||
identity, err := ParseIdentity(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if held[identity] {
|
||||
return nil, fmt.Errorf("%q belongs to one person only", identity)
|
||||
}
|
||||
held[identity] = true
|
||||
idents = append(idents, identity)
|
||||
}
|
||||
people = append(people, store.Person{ID: id, Name: name, Authority: pr.Authority, Identities: idents})
|
||||
}
|
||||
return people, nil
|
||||
}
|
||||
|
||||
// ParseIdentity returns raw as an identity: a channel and an account on it,
|
||||
// such as "telegram:1001".
|
||||
func ParseIdentity(raw string) (string, error) {
|
||||
identity := strings.TrimSpace(raw)
|
||||
channel, account, ok := strings.Cut(identity, ":")
|
||||
if !ok || channel == "" || account == "" || strings.ContainsAny(identity, " \t\n") {
|
||||
return "", fmt.Errorf("%q isn't an identity; write the channel and the account, such as telegram:1001", raw)
|
||||
}
|
||||
return identity, nil
|
||||
}
|
||||
@@ -13,20 +13,20 @@ type FactsSource interface {
|
||||
TargetFacts(ctx context.Context, t connectors.Target) (connectors.TargetFacts, error)
|
||||
}
|
||||
|
||||
// Identities says which person holds an identity, such as "servicenow:jdoe".
|
||||
// Identities says which account holds an identity, such as "servicenow:jdoe".
|
||||
type Identities interface {
|
||||
PersonID(ctx context.Context, identity string) (id string, ok bool, err error)
|
||||
AccountOf(ctx context.Context, identity string) (id string, ok bool, err error)
|
||||
}
|
||||
|
||||
// RecordedFacts looks a target's facts up in the connectors each time and
|
||||
// keeps none. The owner a connector names counts only when the identity is a
|
||||
// person Archie knows, so the request can be put to them.
|
||||
// keeps none. The owner a connector names counts only when the identity is
|
||||
// linked to an account, so the request can be put to them.
|
||||
type RecordedFacts struct {
|
||||
Source FactsSource
|
||||
People Identities
|
||||
Source FactsSource
|
||||
Accounts Identities
|
||||
}
|
||||
|
||||
// Facts asks the connectors about t and maps the owner they name to a person.
|
||||
// Facts asks the connectors about t and maps the owner they name to an account.
|
||||
func (r RecordedFacts) Facts(ctx context.Context, t connectors.Target) (TargetFacts, error) {
|
||||
got, err := r.Source.TargetFacts(ctx, t)
|
||||
if err != nil {
|
||||
@@ -36,7 +36,7 @@ func (r RecordedFacts) Facts(ctx context.Context, t connectors.Target) (TargetFa
|
||||
if got.OwnerIdentity == "" {
|
||||
return facts, nil
|
||||
}
|
||||
id, ok, err := r.People.PersonID(ctx, got.OwnerIdentity)
|
||||
id, ok, err := r.Accounts.AccountOf(ctx, got.OwnerIdentity)
|
||||
if err != nil {
|
||||
return TargetFacts{}, fmt.Errorf("match owner %s: %w", got.OwnerIdentity, err)
|
||||
}
|
||||
|
||||
+1
-1
@@ -206,7 +206,7 @@ func dryAction(d judgement.Decision, ask []string) DryAction {
|
||||
func pathNames(path []governance.PathStep) []string {
|
||||
names := make([]string, 0, len(path))
|
||||
for _, s := range path {
|
||||
names = append(names, firstText(s.Name, s.Person))
|
||||
names = append(names, firstText(s.Name, s.Account))
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ func (e *escalations) Discard(context.Context, uuid.UUID, string) error { return
|
||||
// answer at any step stops the escalation there.
|
||||
func TestWaitThroughPathMovesOnAtEachDeadlineAndExpiresAtTheEnd(t *testing.T) {
|
||||
// A zero deadline has passed by the time it is waited on.
|
||||
step := func(person string) governance.PathStep { return governance.PathStep{Person: person} }
|
||||
step := func(person string) governance.PathStep { return governance.PathStep{Account: person} }
|
||||
tests := []struct {
|
||||
name string
|
||||
path []governance.PathStep
|
||||
|
||||
@@ -99,7 +99,7 @@ func (investigateSettings) AttemptsPerRun(context.Context) (int, error) { return
|
||||
// EscalationPath waits long enough that the first attempt suspends, as a
|
||||
// person who has not answered yet does.
|
||||
func (investigateSettings) EscalationPath(context.Context, string, bool) ([]governance.PathStep, error) {
|
||||
return []governance.PathStep{{Person: "p", DeadlineMS: time.Hour.Milliseconds()}}, nil
|
||||
return []governance.PathStep{{Account: "p", DeadlineMS: time.Hour.Milliseconds()}}, nil
|
||||
}
|
||||
|
||||
// investigateBox declares one action so the model has something to call. The
|
||||
|
||||
@@ -97,7 +97,7 @@ func (onePersonPath) AgentProvider(context.Context, governance.Model) (chat.Prov
|
||||
}
|
||||
|
||||
func (onePersonPath) EscalationPath(context.Context, string, bool) ([]governance.PathStep, error) {
|
||||
return []governance.PathStep{{Person: "p"}}, nil
|
||||
return []governance.PathStep{{Account: "p"}}, nil
|
||||
}
|
||||
|
||||
func (onePersonPath) RecurrenceThreshold(context.Context) (int, error) { return 0, nil }
|
||||
|
||||
@@ -44,6 +44,12 @@ service ConnectorService {
|
||||
// host asks only connectors that declare target_facts, and never stores the
|
||||
// answer.
|
||||
rpc TargetFacts(TargetFactsRequest) returns (TargetFactsResponse);
|
||||
// LinkURL returns the URL a person opens to send a link code to the
|
||||
// connector, such as a deep link into its bot. The host asks only
|
||||
// connectors that declare links_accounts. The connector then emits an
|
||||
// account.link event carrying the code and the sender's channel identity;
|
||||
// the host binds that identity to the account that issued the code.
|
||||
rpc LinkURL(LinkURLRequest) returns (LinkURLResponse);
|
||||
}
|
||||
|
||||
message ConfigureRequest {
|
||||
@@ -69,6 +75,9 @@ message DescribeResponse {
|
||||
repeated Setting settings = 8;
|
||||
// version is the connector's own release.
|
||||
string version = 9;
|
||||
// links_accounts says the connector serves LinkURL and emits account.link
|
||||
// events, so a person can link their channel identity to an account.
|
||||
bool links_accounts = 10;
|
||||
}
|
||||
|
||||
// Setting is one value an operator enters for an extension to run.
|
||||
@@ -256,3 +265,12 @@ message ListenResponse {
|
||||
repeated Event events = 1;
|
||||
string cursor = 2;
|
||||
}
|
||||
|
||||
message LinkURLRequest {
|
||||
// code is the single-use link code the person sends to the connector.
|
||||
string code = 1;
|
||||
}
|
||||
message LinkURLResponse {
|
||||
// url opens the connector's channel with the code attached.
|
||||
string url = 1;
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
"clsx": "^2.1.1",
|
||||
"cn": "^0.5.1",
|
||||
"pinia": "^4.0.3",
|
||||
"qrcode": "^1.5.4",
|
||||
"reka-ui": "^2.10.5",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-parse": "^11.0.0",
|
||||
@@ -40,6 +41,7 @@
|
||||
"devDependencies": {
|
||||
"@types/hast": "^3.0.5",
|
||||
"@types/node": "^26.6.4",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^6.0.8",
|
||||
"@vue/tsconfig": "^0.9.1",
|
||||
"spotnote": "0.5.0",
|
||||
|
||||
@@ -99,11 +99,6 @@
|
||||
"label": "Members",
|
||||
"description": "People in the organisation and their roles."
|
||||
},
|
||||
{
|
||||
"path": "/org/people",
|
||||
"label": "People",
|
||||
"description": "Who answers approvals, and the accounts and channels they answer from."
|
||||
},
|
||||
{
|
||||
"path": "/org/agents",
|
||||
"label": "Agents",
|
||||
|
||||
Generated
+226
@@ -202,6 +202,9 @@ importers:
|
||||
pinia:
|
||||
specifier: ^4.0.3
|
||||
version: 4.1.0(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.44(typescript@6.0.3))
|
||||
qrcode:
|
||||
specifier: ^1.5.4
|
||||
version: 1.5.4
|
||||
reka-ui:
|
||||
specifier: ^2.10.5
|
||||
version: 2.11.0(vue@3.5.44(typescript@6.0.3))
|
||||
@@ -248,6 +251,9 @@ importers:
|
||||
'@types/node':
|
||||
specifier: ^26.6.4
|
||||
version: 26.6.5
|
||||
'@types/qrcode':
|
||||
specifier: ^1.5.6
|
||||
version: 1.5.6
|
||||
'@vitejs/plugin-vue':
|
||||
specifier: ^6.0.8
|
||||
version: 6.0.10(vite@8.3.5(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1))(vue@3.5.44(typescript@6.0.3))
|
||||
@@ -698,6 +704,9 @@ packages:
|
||||
'@types/node@26.6.5':
|
||||
resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==}
|
||||
|
||||
'@types/qrcode@1.5.6':
|
||||
resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==}
|
||||
|
||||
'@types/unist@3.0.3':
|
||||
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
|
||||
|
||||
@@ -847,6 +856,14 @@ packages:
|
||||
alien-signals@3.2.1:
|
||||
resolution: {integrity: sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==}
|
||||
|
||||
ansi-regex@5.0.1:
|
||||
resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
ansi-styles@4.3.0:
|
||||
resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
aria-hidden@1.2.6:
|
||||
resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -879,6 +896,10 @@ packages:
|
||||
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
|
||||
hasBin: true
|
||||
|
||||
camelcase@5.3.1:
|
||||
resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
caniuse-lite@1.0.30001826:
|
||||
resolution: {integrity: sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==}
|
||||
|
||||
@@ -901,6 +922,9 @@ packages:
|
||||
class-variance-authority@0.7.1:
|
||||
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
|
||||
|
||||
cliui@6.0.0:
|
||||
resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==}
|
||||
|
||||
clsx@2.1.1:
|
||||
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
|
||||
engines: {node: '>=6'}
|
||||
@@ -910,6 +934,13 @@ packages:
|
||||
engines: {node: '>=22'}
|
||||
hasBin: true
|
||||
|
||||
color-convert@2.0.1:
|
||||
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
|
||||
engines: {node: '>=7.0.0'}
|
||||
|
||||
color-name@1.1.4:
|
||||
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
|
||||
|
||||
comma-separated-tokens@2.0.3:
|
||||
resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
|
||||
|
||||
@@ -972,6 +1003,10 @@ packages:
|
||||
supports-color:
|
||||
optional: true
|
||||
|
||||
decamelize@1.2.0:
|
||||
resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
decode-named-character-reference@1.3.0:
|
||||
resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==}
|
||||
|
||||
@@ -989,9 +1024,15 @@ packages:
|
||||
devlop@1.1.0:
|
||||
resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
|
||||
|
||||
dijkstrajs@1.0.3:
|
||||
resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==}
|
||||
|
||||
electron-to-chromium@1.5.481:
|
||||
resolution: {integrity: sha512-dNUsbAP6E2S1dHIYEuN3cQ0dViThjMtpVRheGdvv5HgHFtzLi4Cu4Mbzms85YggP3Eh2VVZTl5+XxEN8ofCbmQ==}
|
||||
|
||||
emoji-regex@8.0.0:
|
||||
resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
|
||||
|
||||
enhanced-resolve@5.26.0:
|
||||
resolution: {integrity: sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
@@ -1029,6 +1070,10 @@ packages:
|
||||
picomatch:
|
||||
optional: true
|
||||
|
||||
find-up@4.1.0:
|
||||
resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
fsevents@2.3.3:
|
||||
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
@@ -1038,6 +1083,10 @@ packages:
|
||||
resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
get-caller-file@2.0.5:
|
||||
resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
|
||||
engines: {node: 6.* || 8.* || >= 10.*}
|
||||
|
||||
graceful-fs@4.2.11:
|
||||
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
|
||||
|
||||
@@ -1053,6 +1102,10 @@ packages:
|
||||
html-void-elements@3.0.0:
|
||||
resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
|
||||
|
||||
is-fullwidth-code-point@3.0.0:
|
||||
resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
is-plain-obj@4.1.0:
|
||||
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -1229,6 +1282,10 @@ packages:
|
||||
resolution: {integrity: sha512-++gUqRDEvcnN6Zhqrr+y/CkVEHhlrR96vZn3nZZPYzMcBUyBtTKzB9NadClFIsIVSsu+3i9tfk/erqy9kAmt7Q==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
locate-path@5.0.0:
|
||||
resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
longest-streak@3.1.0:
|
||||
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
|
||||
|
||||
@@ -1404,9 +1461,25 @@ packages:
|
||||
oniguruma-to-es@4.3.6:
|
||||
resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==}
|
||||
|
||||
p-limit@2.3.0:
|
||||
resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
p-locate@4.1.0:
|
||||
resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
p-try@2.2.0:
|
||||
resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
path-browserify@1.0.1:
|
||||
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
|
||||
|
||||
path-exists@4.0.0:
|
||||
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
pathe@2.0.3:
|
||||
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
|
||||
|
||||
@@ -1436,6 +1509,10 @@ packages:
|
||||
pkg-types@2.4.0:
|
||||
resolution: {integrity: sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==}
|
||||
|
||||
pngjs@5.0.0:
|
||||
resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
|
||||
postcss@8.5.31:
|
||||
resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
@@ -1443,6 +1520,11 @@ packages:
|
||||
property-information@7.2.0:
|
||||
resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==}
|
||||
|
||||
qrcode@1.5.4:
|
||||
resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
hasBin: true
|
||||
|
||||
quansync@0.2.11:
|
||||
resolution: {integrity: sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==}
|
||||
|
||||
@@ -1476,6 +1558,13 @@ packages:
|
||||
remark-stringify@11.0.0:
|
||||
resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}
|
||||
|
||||
require-directory@2.1.1:
|
||||
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
require-main-filename@2.0.0:
|
||||
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
|
||||
|
||||
rolldown@1.2.15:
|
||||
resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -1488,6 +1577,9 @@ packages:
|
||||
resolution: {integrity: sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==}
|
||||
hasBin: true
|
||||
|
||||
set-blocking@2.0.0:
|
||||
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
|
||||
|
||||
shell-quote@1.12.0:
|
||||
resolution: {integrity: sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -1509,9 +1601,17 @@ packages:
|
||||
peerDependencies:
|
||||
vite: '>=5'
|
||||
|
||||
string-width@4.2.3:
|
||||
resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
stringify-entities@4.0.4:
|
||||
resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}
|
||||
|
||||
strip-ansi@6.0.1:
|
||||
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
tailwind-merge@3.7.0:
|
||||
resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==}
|
||||
|
||||
@@ -1725,6 +1825,16 @@ packages:
|
||||
webpack-virtual-modules@0.6.2:
|
||||
resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==}
|
||||
|
||||
which-module@2.0.1:
|
||||
resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==}
|
||||
|
||||
wrap-ansi@6.2.0:
|
||||
resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
y18n@4.0.3:
|
||||
resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}
|
||||
|
||||
yallist@3.1.1:
|
||||
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
|
||||
|
||||
@@ -1733,6 +1843,14 @@ packages:
|
||||
engines: {node: '>= 14.6'}
|
||||
hasBin: true
|
||||
|
||||
yargs-parser@18.1.3:
|
||||
resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
yargs@15.4.1:
|
||||
resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
zwitch@2.0.4:
|
||||
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
|
||||
|
||||
@@ -2128,6 +2246,10 @@ snapshots:
|
||||
dependencies:
|
||||
undici-types: 8.9.0
|
||||
|
||||
'@types/qrcode@1.5.6':
|
||||
dependencies:
|
||||
'@types/node': 26.6.5
|
||||
|
||||
'@types/unist@3.0.3': {}
|
||||
|
||||
'@types/web-bluetooth@0.0.20': {}
|
||||
@@ -2313,6 +2435,12 @@ snapshots:
|
||||
|
||||
alien-signals@3.2.1: {}
|
||||
|
||||
ansi-regex@5.0.1: {}
|
||||
|
||||
ansi-styles@4.3.0:
|
||||
dependencies:
|
||||
color-convert: 2.0.1
|
||||
|
||||
aria-hidden@1.2.6:
|
||||
dependencies:
|
||||
tslib: 2.8.1
|
||||
@@ -2348,6 +2476,8 @@ snapshots:
|
||||
node-releases: 2.0.63
|
||||
update-browserslist-db: 1.3.4(browserslist@4.29.5)
|
||||
|
||||
camelcase@5.3.1: {}
|
||||
|
||||
caniuse-lite@1.0.30001826: {}
|
||||
|
||||
ccount@2.0.1: {}
|
||||
@@ -2366,10 +2496,22 @@ snapshots:
|
||||
dependencies:
|
||||
clsx: 2.1.1
|
||||
|
||||
cliui@6.0.0:
|
||||
dependencies:
|
||||
string-width: 4.2.3
|
||||
strip-ansi: 6.0.1
|
||||
wrap-ansi: 6.2.0
|
||||
|
||||
clsx@2.1.1: {}
|
||||
|
||||
cn@0.5.1: {}
|
||||
|
||||
color-convert@2.0.1:
|
||||
dependencies:
|
||||
color-name: 1.1.4
|
||||
|
||||
color-name@1.1.4: {}
|
||||
|
||||
comma-separated-tokens@2.0.3: {}
|
||||
|
||||
confbox@0.1.8: {}
|
||||
@@ -2420,6 +2562,8 @@ snapshots:
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
|
||||
decamelize@1.2.0: {}
|
||||
|
||||
decode-named-character-reference@1.3.0:
|
||||
dependencies:
|
||||
character-entities: 2.0.2
|
||||
@@ -2434,8 +2578,12 @@ snapshots:
|
||||
dependencies:
|
||||
dequal: 2.0.3
|
||||
|
||||
dijkstrajs@1.0.3: {}
|
||||
|
||||
electron-to-chromium@1.5.481: {}
|
||||
|
||||
emoji-regex@8.0.0: {}
|
||||
|
||||
enhanced-resolve@5.26.0:
|
||||
dependencies:
|
||||
graceful-fs: 4.2.11
|
||||
@@ -2461,11 +2609,18 @@ snapshots:
|
||||
optionalDependencies:
|
||||
picomatch: 4.0.7
|
||||
|
||||
find-up@4.1.0:
|
||||
dependencies:
|
||||
locate-path: 5.0.0
|
||||
path-exists: 4.0.0
|
||||
|
||||
fsevents@2.3.3:
|
||||
optional: true
|
||||
|
||||
gensync@1.0.0-beta.2: {}
|
||||
|
||||
get-caller-file@2.0.5: {}
|
||||
|
||||
graceful-fs@4.2.11: {}
|
||||
|
||||
hast-util-to-html@9.0.5:
|
||||
@@ -2490,6 +2645,8 @@ snapshots:
|
||||
|
||||
html-void-elements@3.0.0: {}
|
||||
|
||||
is-fullwidth-code-point@3.0.0: {}
|
||||
|
||||
is-plain-obj@4.1.0: {}
|
||||
|
||||
jiti@2.7.0: {}
|
||||
@@ -2609,6 +2766,10 @@ snapshots:
|
||||
pkg-types: 2.4.0
|
||||
quansync: 0.2.11
|
||||
|
||||
locate-path@5.0.0:
|
||||
dependencies:
|
||||
p-locate: 4.1.0
|
||||
|
||||
longest-streak@3.1.0: {}
|
||||
|
||||
lru-cache@5.1.1:
|
||||
@@ -2973,8 +3134,20 @@ snapshots:
|
||||
regex: 6.1.0
|
||||
regex-recursion: 6.0.2
|
||||
|
||||
p-limit@2.3.0:
|
||||
dependencies:
|
||||
p-try: 2.2.0
|
||||
|
||||
p-locate@4.1.0:
|
||||
dependencies:
|
||||
p-limit: 2.3.0
|
||||
|
||||
p-try@2.2.0: {}
|
||||
|
||||
path-browserify@1.0.1: {}
|
||||
|
||||
path-exists@4.0.0: {}
|
||||
|
||||
pathe@2.0.3: {}
|
||||
|
||||
perfect-debounce@2.1.0: {}
|
||||
@@ -3003,6 +3176,8 @@ snapshots:
|
||||
exsolve: 1.1.3
|
||||
pathe: 2.0.3
|
||||
|
||||
pngjs@5.0.0: {}
|
||||
|
||||
postcss@8.5.31:
|
||||
dependencies:
|
||||
nanoid: 3.3.20
|
||||
@@ -3011,6 +3186,12 @@ snapshots:
|
||||
|
||||
property-information@7.2.0: {}
|
||||
|
||||
qrcode@1.5.4:
|
||||
dependencies:
|
||||
dijkstrajs: 1.0.3
|
||||
pngjs: 5.0.0
|
||||
yargs: 15.4.1
|
||||
|
||||
quansync@0.2.11: {}
|
||||
|
||||
readdirp@5.1.1: {}
|
||||
@@ -3072,6 +3253,10 @@ snapshots:
|
||||
mdast-util-to-markdown: 2.2.3
|
||||
unified: 11.0.5
|
||||
|
||||
require-directory@2.1.1: {}
|
||||
|
||||
require-main-filename@2.0.0: {}
|
||||
|
||||
rolldown@1.2.15:
|
||||
dependencies:
|
||||
'@oxc-project/types': 0.155.0
|
||||
@@ -3097,6 +3282,8 @@ snapshots:
|
||||
|
||||
semver@6.3.2: {}
|
||||
|
||||
set-blocking@2.0.0: {}
|
||||
|
||||
shell-quote@1.12.0: {}
|
||||
|
||||
shiki@4.5.0:
|
||||
@@ -3124,11 +3311,21 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
string-width@4.2.3:
|
||||
dependencies:
|
||||
emoji-regex: 8.0.0
|
||||
is-fullwidth-code-point: 3.0.0
|
||||
strip-ansi: 6.0.1
|
||||
|
||||
stringify-entities@4.0.4:
|
||||
dependencies:
|
||||
character-entities-html4: 2.1.0
|
||||
character-entities-legacy: 3.0.0
|
||||
|
||||
strip-ansi@6.0.1:
|
||||
dependencies:
|
||||
ansi-regex: 5.0.1
|
||||
|
||||
tailwind-merge@3.7.0: {}
|
||||
|
||||
tailwindcss@4.3.3: {}
|
||||
@@ -3290,8 +3487,37 @@ snapshots:
|
||||
|
||||
webpack-virtual-modules@0.6.2: {}
|
||||
|
||||
which-module@2.0.1: {}
|
||||
|
||||
wrap-ansi@6.2.0:
|
||||
dependencies:
|
||||
ansi-styles: 4.3.0
|
||||
string-width: 4.2.3
|
||||
strip-ansi: 6.0.1
|
||||
|
||||
y18n@4.0.3: {}
|
||||
|
||||
yallist@3.1.1: {}
|
||||
|
||||
yaml@2.9.1: {}
|
||||
|
||||
yargs-parser@18.1.3:
|
||||
dependencies:
|
||||
camelcase: 5.3.1
|
||||
decamelize: 1.2.0
|
||||
|
||||
yargs@15.4.1:
|
||||
dependencies:
|
||||
cliui: 6.0.0
|
||||
decamelize: 1.2.0
|
||||
find-up: 4.1.0
|
||||
get-caller-file: 2.0.5
|
||||
require-directory: 2.1.1
|
||||
require-main-filename: 2.0.0
|
||||
set-blocking: 2.0.0
|
||||
string-width: 4.2.3
|
||||
which-module: 2.0.1
|
||||
y18n: 4.0.3
|
||||
yargs-parser: 18.1.3
|
||||
|
||||
zwitch@2.0.4: {}
|
||||
@@ -4,6 +4,7 @@ import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import LinkedChannels from "@/accounts/LinkedChannels.vue";
|
||||
import PersonalTokensCard from "@/accounts/PersonalTokensCard.vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
@@ -29,6 +30,7 @@ const change=()=>run(async()=>{await api.changePassword(current.value,next.value
|
||||
<PageHeader title="Your account"><span class="text-label text-fg-muted">{{accounts.status?.user?.display_name}}</span></PageHeader>
|
||||
<Alert v-if="$route.query.welcome" class="mb-4">Your organisation and admin account are ready. Add a passkey below, <RouterLink class="underline" to="/org/members">add members</RouterLink>, or <RouterLink class="underline" to="/settings/authentication">configure OIDC</RouterLink>.</Alert>
|
||||
<Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>{{error}}<a v-if="sessionExpired" class="underline" href="/?reauth=1"> Sign in again</a></AlertDescription></Alert>
|
||||
<LinkedChannels :welcome="Boolean($route.query.welcome)" />
|
||||
<Section title="Passkeys">
|
||||
<ItemGroup v-if="keys.length" class="mb-3"><Item v-for="key in keys" :key="key.id" as="li" variant="outline" size="xs"><ItemContent class="min-w-0 truncate"><span class="truncate">{{key.name}}</span></ItemContent><ItemActions><Button variant="ghost" size="sm" class="text-danger" :disabled="busy" @click="pending = key">Remove</Button></ItemActions></Item></ItemGroup>
|
||||
<form v-if="eligible" class="flex flex-wrap gap-2" @submit.prevent="enroll"><Input v-model="keyName" aria-label="Passkey name" placeholder="Passkey name (optional)" maxlength="200" class="min-w-40 flex-1"/><Button type="submit" :disabled="busy">Add passkey</Button></form>
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useIntervalFn } from "@vueuse/core";
|
||||
import QRCode from "qrcode";
|
||||
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Item, ItemActions, ItemContent, ItemGroup } from "@/components/ui/item";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { api, describeError, type ChannelLink, type ChannelLinks } from "@/lib/api";
|
||||
|
||||
/** Links the signed-in account to the channel accounts it answers approvals
|
||||
* from. Shown only while an installed connector can link. */
|
||||
const props = defineProps<{ welcome?: boolean }>();
|
||||
|
||||
interface Pending {
|
||||
url: string;
|
||||
qr: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
const links = ref<ChannelLinks | null>(null);
|
||||
const pending = ref<Record<string, Pending>>({});
|
||||
const error = ref("");
|
||||
const busy = ref(false);
|
||||
|
||||
const label = (connector: string) => connector.charAt(0).toUpperCase() + connector.slice(1);
|
||||
const linkedOn = (connector: string): ChannelLink[] => links.value?.linked.filter((l) => l.connector === connector) ?? [];
|
||||
const waiting = computed(() => Object.keys(pending.value).length > 0);
|
||||
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
links.value = await api.channelLinks();
|
||||
error.value = "";
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
return;
|
||||
}
|
||||
settle();
|
||||
}
|
||||
|
||||
/** A code that was used or ran out stops waiting. */
|
||||
function settle(): void {
|
||||
for (const connector of Object.keys(pending.value)) {
|
||||
const fresh = linkedOn(connector).some((l) => Date.parse(l.linked_at) >= pending.value[connector]!.expiresAt - CODE_LIFETIME_MS);
|
||||
if (fresh || Date.now() >= pending.value[connector]!.expiresAt) delete pending.value[connector];
|
||||
}
|
||||
if (!waiting.value) stop();
|
||||
}
|
||||
|
||||
/** Matches the server's link code lifetime. */
|
||||
const CODE_LIFETIME_MS = 10 * 60 * 1000;
|
||||
const { pause: stop, resume: poll } = useIntervalFn(() => void load(), 2_000, { immediate: false });
|
||||
|
||||
async function run(action: () => Promise<void>): Promise<void> {
|
||||
busy.value = true;
|
||||
try {
|
||||
await action();
|
||||
error.value = "";
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const begin = (connector: string) =>
|
||||
run(async () => {
|
||||
const start = await api.beginChannelLink(connector);
|
||||
pending.value[connector] = {
|
||||
url: start.url,
|
||||
qr: await QRCode.toDataURL(start.url, { margin: 1, width: 192 }),
|
||||
expiresAt: Date.parse(start.expires_at),
|
||||
};
|
||||
poll();
|
||||
});
|
||||
|
||||
const unlink = (link: ChannelLink) =>
|
||||
run(async () => {
|
||||
await api.unlinkChannel(link.connector, link.subject);
|
||||
await load();
|
||||
});
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Section v-if="links?.connectors.length || error" :title="props.welcome ? 'Link your channels' : 'Linked accounts'">
|
||||
<Alert v-if="error" variant="destructive" class="mb-3"><AlertDescription>{{ error }}</AlertDescription></Alert>
|
||||
<ItemGroup v-if="links" class="gap-3">
|
||||
<div v-for="connector in links.connectors" :key="connector" class="space-y-2">
|
||||
<Item v-for="link in linkedOn(connector)" :key="link.subject" as="li" variant="outline" size="xs">
|
||||
<ItemContent class="min-w-0 truncate">{{ label(connector) }}: Linked as {{ link.name || link.subject }}</ItemContent>
|
||||
<ItemActions>
|
||||
<Button variant="ghost" size="sm" class="text-danger" :disabled="busy" @click="unlink(link)">Unlink</Button>
|
||||
</ItemActions>
|
||||
</Item>
|
||||
<div v-if="pending[connector]" class="flex flex-wrap items-center gap-4">
|
||||
<img :src="pending[connector].qr" :alt="`QR code to link ${label(connector)}`" width="192" height="192" class="rounded-md bg-white" />
|
||||
<div class="space-y-2">
|
||||
<Button as-child><a :href="pending[connector].url" target="_blank" rel="noopener">Open in {{ label(connector) }}</a></Button>
|
||||
<p class="text-caption text-fg-muted">Scan the code or open the link, then press Start.</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button v-else-if="!linkedOn(connector).length" :disabled="busy" @click="begin(connector)">Link your {{ label(connector) }}</Button>
|
||||
<Button v-else variant="outline" size="sm" :disabled="busy" @click="begin(connector)">Link another {{ label(connector) }} account</Button>
|
||||
</div>
|
||||
</ItemGroup>
|
||||
</Section>
|
||||
</template>
|
||||
+26
-9
@@ -367,9 +367,15 @@ export const api = {
|
||||
alerts: <T = unknown>() => request<T>("/api/alerts"),
|
||||
dismissAlert: (id: number) =>
|
||||
request<void>(`/api/alerts/${id}/dismiss`, { method: "POST", parse: false }),
|
||||
people: () => request<Person[]>("/api/people"),
|
||||
/** Replaces the organisation's people with the list. */
|
||||
putPeople: (people: Person[]) => request<Person[]>("/api/people", { method: "PUT", body: people }),
|
||||
channelLinks: () => request<ChannelLinks>("/api/account/channels"),
|
||||
/** Issues a single-use code and returns the URL that sends it to the channel. */
|
||||
beginChannelLink: (connector: string) =>
|
||||
request<ChannelLinkStart>(`/api/account/channels/${encodeURIComponent(connector)}/link`, { method: "POST" }),
|
||||
unlinkChannel: (connector: string, subject: string) =>
|
||||
request<void>(`/api/account/channels/${encodeURIComponent(connector)}/${encodeURIComponent(subject)}`, {
|
||||
method: "DELETE",
|
||||
parse: false,
|
||||
}),
|
||||
identities: <T = unknown>() => request<T>("/api/identities"),
|
||||
identityCreate: <T = unknown>(identity: { display_name: string; kind: string }) =>
|
||||
request<T>("/api/identities", { method: "POST", body: identity }),
|
||||
@@ -683,13 +689,24 @@ export interface Run {
|
||||
result?: unknown;
|
||||
}
|
||||
|
||||
/** A person who may answer approvals, and the identities they answer as. */
|
||||
export interface Person {
|
||||
/** Empty for a new person. */
|
||||
id: string;
|
||||
/** A channel account linked to the signed-in account. */
|
||||
export interface ChannelLink {
|
||||
connector: string;
|
||||
subject: string;
|
||||
name: string;
|
||||
authority: boolean;
|
||||
identities: string[];
|
||||
linked_at: string;
|
||||
}
|
||||
|
||||
/** The connectors that can link, and the channel accounts already linked. */
|
||||
export interface ChannelLinks {
|
||||
connectors: string[];
|
||||
linked: ChannelLink[];
|
||||
}
|
||||
|
||||
/** A link code ready to open in a channel. */
|
||||
export interface ChannelLinkStart {
|
||||
url: string;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
/** A passkey assertion made for one approval request. */
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ const orgSpecs: NavSpec[] = [
|
||||
sections: [
|
||||
{
|
||||
label: "People & access",
|
||||
paths: ["/org/members", "/org/people", "/org/agents", "/org/workspaces", "/org/policies", "/org/denials", "/org/audit"],
|
||||
paths: ["/org/members", "/org/agents", "/org/workspaces", "/org/policies", "/org/denials", "/org/audit"],
|
||||
},
|
||||
{
|
||||
label: "Connections & models",
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { Link, Plus, Trash2, X } from "@lucide/vue";
|
||||
|
||||
import { useAccountsStore } from "@/accounts/accounts";
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { api, describeError, type Person } from "@/lib/api";
|
||||
import { useOrgStore } from "@/stores/org";
|
||||
|
||||
/** The people who answer approvals. Saving replaces the whole list, so each
|
||||
* change sends the list with that one change and shows what the server kept. */
|
||||
const people = ref<Person[]>([]);
|
||||
const error = ref("");
|
||||
const loading = ref(true);
|
||||
const busy = ref(false);
|
||||
const name = ref("");
|
||||
const identity = ref<Record<string, string>>({});
|
||||
|
||||
const accounts = useAccountsStore();
|
||||
const orgStore = useOrgStore();
|
||||
orgStore.watchIdentities();
|
||||
|
||||
const accountPrefix = "account:";
|
||||
const mine = () => (accounts.status?.user ? accountPrefix + accounts.status.user.id : "");
|
||||
|
||||
/** An account identity reads as the account's name; a channel identity as written. */
|
||||
function label(value: string): string {
|
||||
return value.startsWith(accountPrefix) ? orgStore.identityName(value.slice(accountPrefix.length)) : value;
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
people.value = await api.people();
|
||||
error.value = "";
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (!accounts.status) await accounts.load();
|
||||
await load();
|
||||
});
|
||||
|
||||
async function save(next: Person[]): Promise<void> {
|
||||
busy.value = true;
|
||||
try {
|
||||
people.value = await api.putPeople(next);
|
||||
error.value = "";
|
||||
} catch (cause) {
|
||||
error.value = describeError(cause, errors.common.unknown);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const change = (person: Person, edit: Partial<Person>) =>
|
||||
save(people.value.map((p) => (p === person ? { ...p, ...edit } : p)));
|
||||
|
||||
async function add(): Promise<void> {
|
||||
const value = name.value.trim();
|
||||
if (!value) return;
|
||||
await save([...people.value, { id: "", name: value, authority: false, identities: [] }]);
|
||||
if (!error.value) name.value = "";
|
||||
}
|
||||
|
||||
const rename = (person: Person, event: Event) => {
|
||||
const next = (event.target as HTMLInputElement).value.trim();
|
||||
if (next && next !== person.name) void change(person, { name: next });
|
||||
};
|
||||
|
||||
async function addIdentity(person: Person, value: string): Promise<void> {
|
||||
const next = value.trim();
|
||||
if (!next || person.identities.includes(next)) return;
|
||||
await change(person, { identities: [...person.identities, next] });
|
||||
if (!error.value) identity.value[person.id] = "";
|
||||
}
|
||||
|
||||
const removeIdentity = (person: Person, value: string) =>
|
||||
change(person, { identities: person.identities.filter((i) => i !== value) });
|
||||
|
||||
const remove = (person: Person) => save(people.value.filter((p) => p !== person));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="People" />
|
||||
|
||||
<Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>{{ error }}</AlertDescription></Alert>
|
||||
|
||||
<form class="mb-4 flex flex-wrap items-center gap-2" @submit.prevent="add">
|
||||
<Input v-model="name" class="max-w-64" placeholder="Name" aria-label="Name" required />
|
||||
<Button type="submit" size="sm" :disabled="!name.trim() || busy"><Plus data-icon="inline-start" />Add</Button>
|
||||
</form>
|
||||
|
||||
<Section>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead class="w-64">Name</TableHead>
|
||||
<TableHead class="w-28">Authority</TableHead>
|
||||
<TableHead>Identities</TableHead>
|
||||
<TableHead class="w-16 text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="person in people" :key="person.id">
|
||||
<TableCell>
|
||||
<Input :default-value="person.name" :aria-label="`Name of ${person.name}`" :disabled="busy" @change="rename(person, $event)" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Switch
|
||||
:model-value="person.authority"
|
||||
:aria-label="`Authority for ${person.name}`"
|
||||
:disabled="busy"
|
||||
@update:model-value="(on: boolean) => change(person, { authority: on })"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Badge v-for="value in person.identities" :key="value" variant="outline" class="gap-1">
|
||||
{{ label(value) }}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm focus-visible:outline focus-visible:outline-2"
|
||||
:aria-label="`Remove ${label(value)} from ${person.name}`"
|
||||
:disabled="busy"
|
||||
@click="removeIdentity(person, value)"
|
||||
><X class="size-3" /></button>
|
||||
</Badge>
|
||||
<form class="flex items-center gap-1" @submit.prevent="addIdentity(person, identity[person.id] ?? '')">
|
||||
<Input
|
||||
v-model="identity[person.id]"
|
||||
class="h-8 w-44"
|
||||
placeholder="telegram:1001"
|
||||
:aria-label="`Add an identity to ${person.name}`"
|
||||
/>
|
||||
<Button type="submit" size="icon" variant="ghost" :aria-label="`Add identity to ${person.name}`" :disabled="busy || !identity[person.id]?.trim()"><Plus /></Button>
|
||||
</form>
|
||||
<Button
|
||||
v-if="mine() && !person.identities.includes(mine())"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
:disabled="busy"
|
||||
@click="addIdentity(person, mine())"
|
||||
><Link data-icon="inline-start" />Link my account</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell class="text-right">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon" :aria-label="`Remove ${person.name}`" :disabled="busy" @click="remove(person)"><Trash2 /></Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Remove</TooltipContent>
|
||||
</Tooltip>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow v-if="loading">
|
||||
<TableCell colspan="4" class="text-label text-fg-muted" role="status">Loading people…</TableCell>
|
||||
</TableRow>
|
||||
<TableRow v-else-if="!people.length && !error">
|
||||
<TableCell colspan="4">
|
||||
<Empty class="py-6"><EmptyHeader><EmptyTitle>No people yet</EmptyTitle></EmptyHeader></Empty>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -13,7 +13,6 @@ const OrgShell = () => import("@/org/OrgShell.vue");
|
||||
const OrgOverviewPage = () => import("@/org/OrgOverviewPage.vue");
|
||||
const OrgMembersPage = () => import("@/org/OrgMembersPage.vue");
|
||||
const OrgAgentsPage = () => import("@/org/OrgAgentsPage.vue");
|
||||
const OrgPeoplePage = () => import("@/org/OrgPeoplePage.vue");
|
||||
const OrgWorkspacesPage = () => import("@/org/OrgWorkspacesPage.vue");
|
||||
const OrgAccessPage = () => import("@/org/OrgAccessPage.vue");
|
||||
const OrgModelsPage = () => import("@/org/OrgModelsPage.vue");
|
||||
@@ -279,12 +278,6 @@ export const routes: RouteRecordRaw[] = [
|
||||
component: OrgMembersPage,
|
||||
meta: { section: "org_members", label: "Members", navPath: "/org", description: "People in the organisation and their roles." },
|
||||
},
|
||||
{
|
||||
path: "people",
|
||||
name: "org-people",
|
||||
component: OrgPeoplePage,
|
||||
meta: { section: "org_people", label: "People", navPath: "/org", description: "Who answers approvals, and the accounts and channels they answer from." },
|
||||
},
|
||||
{
|
||||
path: "agents",
|
||||
name: "org-agents",
|
||||
|
||||
Reference in new issue
Block a user