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, op func(id, method, path, summary string, status int) huma.Operation) { httpapi.Register(api, httpapi.Authorized(ActionRead, KindAccount), op("list-channel-links", http.MethodGet, "/api/account/channels", "List the channels you can link and your linked accounts", 0), m.listChannels) httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindAccount), op("begin-channel-link", http.MethodPost, "/api/account/channels/{connector}/link", "Start linking a channel account", 0), m.beginChannelLink) httpapi.Register(api, httpapi.Authorized(ActionUpdate, KindAccount), op("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 }