diff --git a/cfg/dev.yaml b/cfg/dev.yaml index 7146d0284..7536f10ce 100644 --- a/cfg/dev.yaml +++ b/cfg/dev.yaml @@ -64,6 +64,7 @@ probod: slack: sender-interval: 60 + signing-secret: "this-is-not-a-secret-for-slack-signing" openai: api-key: "thisisnotasecret" @@ -90,4 +91,6 @@ probod: auth-url: "https://slack.com/oauth/v2/authorize" token-url: "https://slack.com/api/oauth.v2.access" scopes: + - "chat:write" + - "channels:join" - "incoming-webhook" diff --git a/pkg/coredata/entity_type_reg.go b/pkg/coredata/entity_type_reg.go index 8c402b035..6794eeb1c 100644 --- a/pkg/coredata/entity_type_reg.go +++ b/pkg/coredata/entity_type_reg.go @@ -62,4 +62,5 @@ const ( InvitationEntityType MembershipEntityType SlackMessageEntityType + SlackMessageUpdateEntityType ) diff --git a/pkg/coredata/migrations/20251020T163914Z.sql b/pkg/coredata/migrations/20251020T163914Z.sql new file mode 100644 index 000000000..6a7bda16c --- /dev/null +++ b/pkg/coredata/migrations/20251020T163914Z.sql @@ -0,0 +1,21 @@ +CREATE TYPE slack_message_type AS ENUM ('TRUST_CENTER_ACCESS_REQUEST', 'WELCOME'); + +ALTER TABLE slack_messages ALTER COLUMN body TYPE JSONB USING body::jsonb; +ALTER TABLE slack_messages ADD COLUMN message_ts TEXT; +ALTER TABLE slack_messages ADD COLUMN channel_id TEXT; +ALTER TABLE slack_messages ADD COLUMN requester_email TEXT; +ALTER TABLE slack_messages ADD COLUMN type slack_message_type NOT NULL; + +ALTER TABLE slack_messages ADD CONSTRAINT unique_slack_message_org_ts_channel UNIQUE (organization_id, message_ts, channel_id); + +CREATE TABLE slack_message_updates ( + id TEXT PRIMARY KEY, + tenant_id TEXT NOT NULL, + slack_message_id TEXT NOT NULL, + body JSONB NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL, + sent_at TIMESTAMP WITH TIME ZONE, + error TEXT, + CONSTRAINT fk_slack_message_updates_slack_message_id FOREIGN KEY (slack_message_id) REFERENCES slack_messages(id) ON UPDATE CASCADE ON DELETE CASCADE +); diff --git a/pkg/coredata/slack_message.go b/pkg/coredata/slack_message.go index 5b03ee59c..6f2025c1b 100644 --- a/pkg/coredata/slack_message.go +++ b/pkg/coredata/slack_message.go @@ -18,6 +18,7 @@ import ( "context" "errors" "fmt" + "maps" "time" "github.com/getprobo/probo/pkg/gid" @@ -27,13 +28,17 @@ import ( type ( SlackMessage struct { - ID gid.GID `db:"id"` - OrganizationID gid.GID `db:"organization_id"` - Body string `db:"body"` - CreatedAt time.Time `db:"created_at"` - UpdatedAt time.Time `db:"updated_at"` - SentAt *time.Time `db:"sent_at"` - Error *string `db:"error"` + ID gid.GID `db:"id"` + OrganizationID gid.GID `db:"organization_id"` + Type SlackMessageType `db:"type"` + Body map[string]any `db:"body"` + MessageTS *string `db:"message_ts"` + ChannelID *string `db:"channel_id"` + RequesterEmail *string `db:"requester_email"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` + SentAt *time.Time `db:"sent_at"` + Error *string `db:"error"` } ErrNoUnsentSlackMessage struct{} @@ -46,13 +51,17 @@ func (e ErrNoUnsentSlackMessage) Error() string { func NewSlackMessage( scope Scoper, organizationID gid.GID, - body string, + messageType SlackMessageType, + body map[string]any, + requesterEmail *string, ) *SlackMessage { now := time.Now() return &SlackMessage{ ID: gid.New(scope.GetTenantID(), SlackMessageEntityType), OrganizationID: organizationID, + Type: messageType, Body: body, + RequesterEmail: requesterEmail, CreatedAt: now, UpdatedAt: now, } @@ -64,15 +73,17 @@ func (s *SlackMessage) Insert( scope Scoper, ) error { q := ` -INSERT INTO slack_messages (id, tenant_id, organization_id, body, created_at, updated_at) -VALUES (@id, @tenant_id, @organization_id, @body, @created_at, @updated_at) +INSERT INTO slack_messages (id, tenant_id, organization_id, type, body, requester_email, created_at, updated_at) +VALUES (@id, @tenant_id, @organization_id, @type, @body, @requester_email, @created_at, @updated_at) ` args := pgx.StrictNamedArgs{ "id": s.ID, "tenant_id": scope.GetTenantID(), "organization_id": s.OrganizationID, + "type": s.Type, "body": s.Body, + "requester_email": s.RequesterEmail, "created_at": s.CreatedAt, "updated_at": s.UpdatedAt, } @@ -90,7 +101,7 @@ func (s *SlackMessage) LoadNextUnsentForUpdate( conn pg.Conn, ) error { q := ` -SELECT id, organization_id, body, created_at, updated_at, sent_at, error +SELECT id, organization_id, type, body, message_ts, channel_id, requester_email, created_at, updated_at, sent_at, error FROM slack_messages WHERE sent_at IS NULL AND error IS NULL ORDER BY created_at ASC @@ -117,21 +128,61 @@ FOR UPDATE return nil } +// This is used for Slack webhook verification where we don't know the tenant yet +func (s *SlackMessage) LoadByChannelAndTSUnscoped( + ctx context.Context, + conn pg.Conn, + channelID string, + messageTS string, +) error { + q := ` +SELECT id, organization_id, type, body, message_ts, channel_id, requester_email, created_at, updated_at, sent_at, error +FROM slack_messages +WHERE message_ts = @message_ts AND channel_id = @channel_id +LIMIT 1 + ` + + args := pgx.StrictNamedArgs{ + "message_ts": messageTS, + "channel_id": channelID, + } + + rows, err := conn.Query(ctx, q, args) + if err != nil { + return fmt.Errorf("cannot query slack message: %w", err) + } + + message, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[SlackMessage]) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("slack message not found") + } + return fmt.Errorf("cannot collect slack message: %w", err) + } + + *s = message + + return nil +} + func (s *SlackMessage) Update( ctx context.Context, conn pg.Conn, ) error { q := ` UPDATE slack_messages -SET sent_at = @sent_at, updated_at = @updated_at, error = @error +SET body = @body, sent_at = @sent_at, updated_at = @updated_at, error = @error, message_ts = @message_ts, channel_id = @channel_id WHERE id = @id ` args := pgx.StrictNamedArgs{ "id": s.ID, + "body": s.Body, "sent_at": s.SentAt, "updated_at": s.UpdatedAt, "error": s.Error, + "message_ts": s.MessageTS, + "channel_id": s.ChannelID, } _, err := conn.Exec(ctx, q, args) @@ -141,3 +192,86 @@ WHERE id = @id return nil } + +func (s *SlackMessage) LoadById( + ctx context.Context, + conn pg.Conn, + scope Scoper, + slackMessageID gid.GID, +) error { + q := ` +SELECT id, organization_id, type, body, message_ts, channel_id, requester_email, created_at, updated_at, sent_at, error +FROM slack_messages +WHERE id = @id +AND %s +LIMIT 1 + ` + + args := pgx.StrictNamedArgs{ + "id": slackMessageID, + } + maps.Copy(args, scope.SQLArguments()) + + rows, err := conn.Query(ctx, q, args) + if err != nil { + return fmt.Errorf("cannot query slack message: %w", err) + } + + message, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[SlackMessage]) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("slack message not found") + } + return fmt.Errorf("cannot collect slack message: %w", err) + } + + *s = message + + return nil +} + +func (s *SlackMessage) LoadLatestByRequesterEmailAndType( + ctx context.Context, + conn pg.Conn, + scope Scoper, + organizationID gid.GID, + requesterEmail string, + messageType SlackMessageType, + since time.Time, +) error { + q := ` +SELECT id, organization_id, type, body, message_ts, channel_id, requester_email, created_at, updated_at, sent_at, error +FROM slack_messages +WHERE %s + AND organization_id = @organization_id + AND requester_email = @requester_email + AND type = @type + AND created_at >= @since +ORDER BY created_at DESC +LIMIT 1 + ` + + q = fmt.Sprintf(q, scope.SQLFragment()) + + args := pgx.StrictNamedArgs{ + "organization_id": organizationID, + "requester_email": requesterEmail, + "type": messageType, + "since": since, + } + maps.Copy(args, scope.SQLArguments()) + + rows, err := conn.Query(ctx, q, args) + if err != nil { + return fmt.Errorf("cannot query slack message: %w", err) + } + + message, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[SlackMessage]) + if err != nil { + return err + } + + *s = message + + return nil +} diff --git a/pkg/coredata/slack_message_type.go b/pkg/coredata/slack_message_type.go new file mode 100644 index 000000000..20d94cceb --- /dev/null +++ b/pkg/coredata/slack_message_type.go @@ -0,0 +1,57 @@ +// Copyright (c) 2025 Probo Inc . +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +// PERFORMANCE OF THIS SOFTWARE. + +package coredata + +import ( + "database/sql/driver" + "fmt" +) + +type SlackMessageType string + +const ( + SlackMessageTypeTrustCenterAccessRequest SlackMessageType = "TRUST_CENTER_ACCESS_REQUEST" + SlackMessageTypeWelcome SlackMessageType = "WELCOME" +) + +func (smt SlackMessageType) String() string { + return string(smt) +} + +func (smt *SlackMessageType) Scan(value any) error { + var s string + switch v := value.(type) { + case string: + s = v + case []byte: + s = string(v) + default: + return fmt.Errorf("unsupported type for SlackMessageType: %T", value) + } + + switch s { + case "TRUST_CENTER_ACCESS_REQUEST": + *smt = SlackMessageTypeTrustCenterAccessRequest + case "WELCOME": + *smt = SlackMessageTypeWelcome + default: + return fmt.Errorf("invalid SlackMessageType value: %q", s) + } + return nil +} + +func (smt SlackMessageType) Value() (driver.Value, error) { + return smt.String(), nil +} diff --git a/pkg/coredata/slack_message_update.go b/pkg/coredata/slack_message_update.go new file mode 100644 index 000000000..ff1b75936 --- /dev/null +++ b/pkg/coredata/slack_message_update.go @@ -0,0 +1,182 @@ +// Copyright (c) 2025 Probo Inc . +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +// PERFORMANCE OF THIS SOFTWARE. + +package coredata + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/getprobo/probo/pkg/gid" + "github.com/jackc/pgx/v5" + "go.gearno.de/kit/pg" +) + +type ( + SlackMessageUpdate struct { + ID gid.GID `db:"id"` + SlackMessageID gid.GID `db:"slack_message_id"` + Body map[string]any `db:"body"` + CreatedAt time.Time `db:"created_at"` + UpdatedAt time.Time `db:"updated_at"` + SentAt *time.Time `db:"sent_at"` + Error *string `db:"error"` + } + + ErrNoUnsentSlackMessageUpdate struct{} +) + +func (e ErrNoUnsentSlackMessageUpdate) Error() string { + return "no unsent slack message update found" +} + +func NewSlackMessageUpdate( + scope Scoper, + slackMessageID gid.GID, + body map[string]any, +) *SlackMessageUpdate { + now := time.Now() + return &SlackMessageUpdate{ + ID: gid.New(scope.GetTenantID(), SlackMessageUpdateEntityType), + SlackMessageID: slackMessageID, + Body: body, + CreatedAt: now, + UpdatedAt: now, + } +} + +func (s *SlackMessageUpdate) Insert( + ctx context.Context, + conn pg.Conn, + scope Scoper, +) error { + q := ` +INSERT INTO slack_message_updates (id, tenant_id, slack_message_id, body, created_at, updated_at, sent_at, error) +VALUES (@id, @tenant_id, @slack_message_id, @body, @created_at, @updated_at, @sent_at, @error) + ` + + args := pgx.StrictNamedArgs{ + "id": s.ID, + "tenant_id": scope.GetTenantID(), + "slack_message_id": s.SlackMessageID, + "body": s.Body, + "created_at": s.CreatedAt, + "updated_at": s.UpdatedAt, + "sent_at": s.SentAt, + "error": s.Error, + } + + _, err := conn.Exec(ctx, q, args) + if err != nil { + return fmt.Errorf("cannot insert slack message update: %w", err) + } + + return nil +} + +func (s *SlackMessageUpdate) LoadLatestBySlackMessageID( + ctx context.Context, + conn pg.Conn, + slackMessageID gid.GID, +) error { + q := ` +SELECT id, slack_message_id, body, created_at, updated_at, sent_at, error +FROM slack_message_updates +WHERE slack_message_id = @slack_message_id +ORDER BY created_at DESC +LIMIT 1 + ` + + args := pgx.StrictNamedArgs{ + "slack_message_id": slackMessageID, + } + + rows, err := conn.Query(ctx, q, args) + if err != nil { + return fmt.Errorf("cannot query slack message updates: %w", err) + } + + update, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[SlackMessageUpdate]) + if err != nil { + return err + } + + *s = update + + return nil +} + +func (s *SlackMessageUpdate) LoadNextUnsentForUpdate( + ctx context.Context, + conn pg.Conn, +) error { + q := ` +SELECT smu.id, smu.slack_message_id, smu.body, smu.created_at, smu.updated_at, smu.sent_at, smu.error +FROM slack_message_updates smu +INNER JOIN slack_messages sm ON smu.slack_message_id = sm.id +WHERE smu.sent_at IS NULL + AND smu.error IS NULL + AND sm.sent_at IS NOT NULL + AND sm.error IS NULL +ORDER BY smu.created_at ASC +LIMIT 1 +FOR UPDATE OF smu + ` + + rows, err := conn.Query(ctx, q) + if err != nil { + return fmt.Errorf("cannot query slack message updates: %w", err) + } + + update, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[SlackMessageUpdate]) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return ErrNoUnsentSlackMessageUpdate{} + } + + return fmt.Errorf("cannot collect slack message update: %w", err) + } + + *s = update + + return nil +} + +func (s *SlackMessageUpdate) Update( + ctx context.Context, + conn pg.Conn, +) error { + q := ` +UPDATE slack_message_updates +SET body = @body, updated_at = @updated_at, sent_at = @sent_at, error = @error +WHERE id = @id + ` + + args := pgx.StrictNamedArgs{ + "id": s.ID, + "body": s.Body, + "updated_at": s.UpdatedAt, + "sent_at": s.SentAt, + "error": s.Error, + } + + _, err := conn.Exec(ctx, q, args) + if err != nil { + return fmt.Errorf("cannot update slack message update: %w", err) + } + + return nil +} diff --git a/pkg/probo/connector_service.go b/pkg/probo/connector_service.go index 9c7013849..18018ae9c 100644 --- a/pkg/probo/connector_service.go +++ b/pkg/probo/connector_service.go @@ -17,6 +17,7 @@ package probo import ( "bytes" "context" + "encoding/json" "fmt" "text/template" "time" @@ -29,7 +30,16 @@ import ( ) var ( - welcomeTemplate = template.Must(template.ParseFS(Templates, "templates/welcome.txt.tmpl")) + welcomeTemplate = template.Must( + template.New("welcome.json.tmpl"). + Funcs(template.FuncMap{ + "jsonEscape": func(s string) string { + b, _ := json.Marshal(s) + return string(b[1 : len(b)-1]) + }, + }). + ParseFS(Templates, "templates/welcome.json.tmpl"), + ) ) type ( @@ -135,7 +145,12 @@ func (s *ConnectorService) Create( return fmt.Errorf("failed to execute template: %w", err) } - slackMessage := coredata.NewSlackMessage(s.svc.scope, req.OrganizationID, buf.String()) + var body map[string]any + if err := json.NewDecoder(&buf).Decode(&body); err != nil { + return fmt.Errorf("failed to parse template JSON: %w", err) + } + + slackMessage := coredata.NewSlackMessage(s.svc.scope, req.OrganizationID, coredata.SlackMessageTypeWelcome, body, nil) if err := slackMessage.Insert(ctx, conn, s.svc.scope); err != nil { return fmt.Errorf("cannot insert slack message: %w", err) } diff --git a/pkg/probo/templates/welcome.json.tmpl b/pkg/probo/templates/welcome.json.tmpl new file mode 100644 index 000000000..190cc5258 --- /dev/null +++ b/pkg/probo/templates/welcome.json.tmpl @@ -0,0 +1,32 @@ +{ + "text": "Welcome to Probo app!", + "blocks": [ + { + "type": "header", + "text": { + "type": "plain_text", + "text": "👋 Welcome to Probo!" + } + }, + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "This channel is now connected to your Probo platform.\n\nYou'll receive notifications here for new trust center access requests." + } + }, + { + "type": "context", + "elements": [ + { + "type": "mrkdwn", + "text": "🏢 *Organization:* {{jsonEscape .OrganizationName}}" + }, + { + "type": "mrkdwn", + "text": "💬 *Channel:* {{jsonEscape .ChannelName}}" + } + ] + } + ] +} diff --git a/pkg/probo/templates/welcome.txt.tmpl b/pkg/probo/templates/welcome.txt.tmpl deleted file mode 100644 index e2ff0dd96..000000000 --- a/pkg/probo/templates/welcome.txt.tmpl +++ /dev/null @@ -1,8 +0,0 @@ -*Welcome to Probo app!* - -This channel is now connected to your Probo platform. You'll receive notifications here for: -• New trust center access requests - -*Organization:* {{.OrganizationName}} -*Channel:* {{.ChannelName}} - diff --git a/pkg/probod/probod.go b/pkg/probod/probod.go index 45dcf9d44..ee43c941b 100644 --- a/pkg/probod/probod.go +++ b/pkg/probod/probod.go @@ -209,7 +209,6 @@ func (impl *Implm) Run( return fmt.Errorf("cannot get trust auth token secret bytes: %w", err) } - awsConfig := awsconfig.NewConfig( l, httpclient.DefaultPooledClient( @@ -347,9 +346,16 @@ func (impl *Implm) Run( impl.cfg.Hostname, impl.cfg.EncryptionKey, impl.cfg.TrustAuth.TokenSecret, + impl.cfg.Slack.SigningSecret, authService, html2pdfConverter, fileManagerService, + l, + trust.TrustConfig{ + TokenSecret: impl.cfg.TrustAuth.TokenSecret, + TokenDuration: time.Duration(impl.cfg.TrustAuth.TokenDuration) * time.Hour, + TokenType: impl.cfg.TrustAuth.TokenType, + }, ) serverHandler, err := server.NewServer( diff --git a/pkg/probod/slack_config.go b/pkg/probod/slack_config.go index 2739371bd..26fd9d527 100644 --- a/pkg/probod/slack_config.go +++ b/pkg/probod/slack_config.go @@ -16,6 +16,7 @@ package probod type ( slackConfig struct { - SenderInterval int `json:"sender-interval"` + SenderInterval int `json:"sender-interval"` + SigningSecret string `json:"signing-secret"` } ) diff --git a/pkg/server/api/trust/v1/resolver.go b/pkg/server/api/trust/v1/resolver.go index 82e8581a6..43cef7ce3 100644 --- a/pkg/server/api/trust/v1/resolver.go +++ b/pkg/server/api/trust/v1/resolver.go @@ -110,6 +110,8 @@ func NewMux( r.Post("/auth/authenticate", authTokenHandler(trustSvc, trustAuthCfg)) r.Delete("/auth/logout", trustCenterLogoutHandler(authCfg, trustAuthCfg)) + r.Post("/slack", slackHandler(trustSvc, trustSvc.GetSlackSigningSecret(), logger)) + return r } diff --git a/pkg/server/api/trust/v1/slack_handler.go b/pkg/server/api/trust/v1/slack_handler.go new file mode 100644 index 000000000..a12bc35a9 --- /dev/null +++ b/pkg/server/api/trust/v1/slack_handler.go @@ -0,0 +1,238 @@ +// Copyright (c) 2025 Probo Inc . +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +// PERFORMANCE OF THIS SOFTWARE. + +package trust_v1 + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/getprobo/probo/pkg/gid" + "github.com/getprobo/probo/pkg/slack" + "github.com/getprobo/probo/pkg/trust" + "go.gearno.de/kit/httpserver" + "go.gearno.de/kit/log" +) + +type ( + SlackInteractivePayload struct { + ResponseURL string `json:"response_url"` + Actions []struct { + ActionID string `json:"action_id"` + Value string `json:"value"` + } `json:"actions"` + Container struct { + MessageTS string `json:"message_ts"` + ChannelID string `json:"channel_id"` + } `json:"container"` + } + + SlackInteractiveResponse struct { + Success bool `json:"success"` + Message string `json:"message,omitempty"` + } +) + +func slackHandler(trustSvc *trust.Service, slackSigningSecret string, logger *log.Logger) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + bodyBytes, err := io.ReadAll(r.Body) + if err != nil { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "cannot read request body"}) + return + } + + r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) + + timestamp := r.Header.Get("X-Slack-Request-Timestamp") + signature := r.Header.Get("X-Slack-Signature") + if timestamp == "" || signature == "" { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "missing Slack signature headers"}) + return + } + + if err := slack.VerifySignature(slackSigningSecret, timestamp, signature, bodyBytes); err != nil { + logger.ErrorCtx(ctx, "invalid Slack signature", log.Error(err)) + httpserver.RenderJSON(w, http.StatusUnauthorized, SlackInteractiveResponse{Success: false, Message: "invalid Slack signature"}) + return + } + + var slackPayload SlackInteractivePayload + if ct := r.Header.Get("Content-Type"); ct != "application/x-www-form-urlencoded" { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "unsupported content type"}) + return + } + + if err := r.ParseForm(); err != nil { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "cannot parse form"}) + return + } + + raw := r.FormValue("payload") + if raw == "" { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "empty payload field"}) + return + } + + if err := json.NewDecoder(strings.NewReader(raw)).Decode(&slackPayload); err != nil { + logger.ErrorCtx(ctx, "cannot parse Slack payload", log.Error(err)) + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "cannot parse Slack payload"}) + return + } + + // Slack sends empty action for url button clicks + if len(slackPayload.Actions) == 0 { + httpserver.RenderJSON(w, http.StatusOK, SlackInteractiveResponse{Success: true, Message: "no action required"}) + return + } + action := slackPayload.Actions[0] + if action.Value == "" { + httpserver.RenderJSON(w, http.StatusOK, SlackInteractiveResponse{Success: true, Message: "no action required"}) + return + } + + if slackPayload.Container.MessageTS == "" { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "missing message_ts"}) + return + } + + if slackPayload.Container.ChannelID == "" { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "missing channel_id"}) + return + } + + if slackPayload.ResponseURL == "" { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "missing response_url"}) + return + } + + var documentIDs []gid.GID + var reportIDs []gid.GID + + switch action.ActionID { + case "accept_all": + var acceptAllData struct { + DocumentIDs []string `json:"document_ids"` + ReportIDs []string `json:"report_ids"` + } + if err := json.NewDecoder(strings.NewReader(action.Value)).Decode(&acceptAllData); err != nil { + logger.ErrorCtx(ctx, "failed to parse accept_all value", log.Error(err)) + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "invalid accept_all value"}) + return + } + + for _, idStr := range acceptAllData.DocumentIDs { + docID, err := gid.ParseGID(idStr) + if err != nil { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "invalid document ID"}) + return + } + documentIDs = append(documentIDs, docID) + } + + for _, idStr := range acceptAllData.ReportIDs { + repID, err := gid.ParseGID(idStr) + if err != nil { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "invalid report ID"}) + return + } + reportIDs = append(reportIDs, repID) + } + + case "accept_document": + docID, err := gid.ParseGID(action.Value) + if err != nil { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "invalid document ID"}) + return + } + documentIDs = []gid.GID{docID} + + case "accept_report": + repID, err := gid.ParseGID(action.Value) + if err != nil { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "invalid report ID"}) + return + } + reportIDs = []gid.GID{repID} + + default: + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: fmt.Sprintf("unknown action: %s", action.ActionID)}) + return + } + + // Load the slack message without tenant scope + slackMessage, err := trustSvc.WithTenant(gid.TenantID{}).SlackMessages.LoadSlackMessageUnscoped( + ctx, + slackPayload.Container.ChannelID, + slackPayload.Container.MessageTS, + ) + if err != nil { + logger.ErrorCtx(ctx, "cannot load slack message", log.Error(err)) + httpserver.RenderJSON(w, http.StatusInternalServerError, SlackInteractiveResponse{Success: false, Message: "internal server error"}) + return + } + + fourteenDaysAgo := time.Now().Add(-14 * 24 * time.Hour) + if slackMessage.CreatedAt.Before(fourteenDaysAgo) { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "this message is too old to be updated (older than 14 days)"}) + return + } + + if slackMessage.RequesterEmail == nil || *slackMessage.RequesterEmail == "" { + httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "missing requester_email"}) + return + } + requesterEmail := *slackMessage.RequesterEmail + + tenantSvc := trustSvc.WithTenant(slackMessage.OrganizationID.TenantID()) + trustCenter, err := tenantSvc.TrustCenters.GetByOrganizationID(ctx, slackMessage.OrganizationID) + if err != nil { + logger.ErrorCtx(ctx, "cannot load trust center", log.Error(err)) + httpserver.RenderJSON(w, http.StatusInternalServerError, SlackInteractiveResponse{Success: false, Message: "internal server error"}) + return + } + + if err := tenantSvc.TrustCenterAccesses.AcceptByIDs( + ctx, + trustCenter.ID, + requesterEmail, + documentIDs, + reportIDs, + ); err != nil { + logger.ErrorCtx(ctx, "failed to grant access", log.Error(err)) + httpserver.RenderJSON(w, http.StatusInternalServerError, SlackInteractiveResponse{Success: false, Message: "internal server error"}) + return + } + + if err := tenantSvc.SlackMessages.UpdateSlackAccessMessage( + ctx, + slackMessage.ID, + action.ActionID, + action.Value, + slackPayload.ResponseURL, + ); err != nil { + logger.ErrorCtx(ctx, "failed to update Slack message", log.Error(err)) + httpserver.RenderJSON(w, http.StatusInternalServerError, SlackInteractiveResponse{Success: false, Message: "internal server error"}) + return + } + + httpserver.RenderJSON(w, http.StatusOK, SlackInteractiveResponse{Success: true, Message: "Access granted"}) + } +} diff --git a/pkg/server/api/trust/v1/v1_resolver.go b/pkg/server/api/trust/v1/v1_resolver.go index 7ac668eb0..7d5b2956b 100644 --- a/pkg/server/api/trust/v1/v1_resolver.go +++ b/pkg/server/api/trust/v1/v1_resolver.go @@ -140,7 +140,7 @@ func (r *mutationResolver) RequestAllAccesses(ctx context.Context, input types.R return nil, fmt.Errorf("email is required for unauthenticated users") } - access, err := publicTrustService.TrustCenterAccesses.Request(ctx, &trust.RequestTrustCenterAccessRequest{ + access, err := publicTrustService.TrustCenterAccesses.Request(ctx, &trust.TrustCenterAccessRequest{ TrustCenterID: input.TrustCenterID, Email: *email, Name: input.Name, @@ -370,7 +370,7 @@ func (r *mutationResolver) RequestDocumentAccess(ctx context.Context, input type return nil, fmt.Errorf("email is required for unauthenticated users") } - access, err := publicTrustService.TrustCenterAccesses.Request(ctx, &trust.RequestTrustCenterAccessRequest{ + access, err := publicTrustService.TrustCenterAccesses.Request(ctx, &trust.TrustCenterAccessRequest{ TrustCenterID: input.TrustCenterID, Email: *email, Name: input.Name, @@ -423,7 +423,7 @@ func (r *mutationResolver) RequestReportAccess(ctx context.Context, input types. return nil, fmt.Errorf("email is required for unauthenticated users") } - access, err := publicTrustService.TrustCenterAccesses.Request(ctx, &trust.RequestTrustCenterAccessRequest{ + access, err := publicTrustService.TrustCenterAccesses.Request(ctx, &trust.TrustCenterAccessRequest{ TrustCenterID: input.TrustCenterID, Email: *email, Name: input.Name, diff --git a/pkg/slack/client.go b/pkg/slack/client.go index a597078a3..4ea1714b6 100644 --- a/pkg/slack/client.go +++ b/pkg/slack/client.go @@ -21,63 +21,161 @@ import ( "fmt" "io" "net/http" + + "go.gearno.de/kit/httpclient" + "go.gearno.de/kit/log" +) + +const ( + slackAPIPostMessage = "https://slack.com/api/chat.postMessage" + slackAPIUpdateMessage = "https://slack.com/api/chat.update" + slackAPIConversationJoin = "https://slack.com/api/conversations.join" ) type ( Client struct { - webhookURL string httpClient *http.Client } - webhookMessage struct { - Text string `json:"text,omitempty"` - Blocks []block `json:"blocks,omitempty"` - } - - block struct { - Type string `json:"type"` - Text *textItem `json:"text,omitempty"` - } - - textItem struct { - Type string `json:"type"` - Text string `json:"text"` + SlackResponse struct { + OK bool `json:"ok,omitempty"` + TS string `json:"ts,omitempty"` + Channel string `json:"channel,omitempty"` + Error string `json:"error,omitempty"` } ) -func NewClient(webhookURL string, httpClient *http.Client) *Client { +func NewClient(logger *log.Logger) *Client { + httpClientOpts := []httpclient.Option{ + httpclient.WithLogger(logger), + } + return &Client{ - webhookURL: webhookURL, - httpClient: httpClient, + httpClient: httpclient.DefaultPooledClient(httpClientOpts...), } } -func (c *Client) PostMessage(ctx context.Context, text string) error { - msg := webhookMessage{ - Text: text, - Blocks: []block{ - { - Type: "section", - Text: &textItem{ - Type: "mrkdwn", - Text: text, - }, - }, - }, +func (c *Client) CreateMessage(ctx context.Context, accessToken string, channelID string, body map[string]any) (*SlackResponse, error) { + payload := map[string]any{ + "channel": channelID, + "text": body["text"], + "blocks": body["blocks"], } var buf bytes.Buffer - if err := json.NewEncoder(&buf).Encode(msg); err != nil { + if err := json.NewEncoder(&buf).Encode(payload); err != nil { + return nil, fmt.Errorf("cannot marshal message: %w", err) + } + + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, slackAPIPostMessage, &buf) + if err != nil { + return nil, fmt.Errorf("cannot create request: %w", err) + } + + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Authorization", "Bearer "+accessToken) + + resp, err := c.httpClient.Do(httpReq) + if err != nil { + return nil, fmt.Errorf("cannot send request: %w", err) + } + defer resp.Body.Close() + + responseBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(responseBody)) + } + + var slackResponse SlackResponse + + if err := json.NewDecoder(bytes.NewReader(responseBody)).Decode(&slackResponse); err != nil { + return nil, fmt.Errorf("failed to parse Slack response: %w (body: %s)", err, string(responseBody)) + } + + if !slackResponse.OK { + return nil, fmt.Errorf("Slack API error: %s (channel: %s, response: %s)", slackResponse.Error, channelID, string(responseBody)) + } + + return &slackResponse, nil +} + +func (c *Client) UpdateInteractiveMessage(ctx context.Context, responseURL string, body map[string]any) error { + updatePayload := map[string]any{ + "replace_original": true, + "text": body["text"], + "blocks": body["blocks"], + } + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(updatePayload); err != nil { + return fmt.Errorf("cannot marshal interactive message update: %w", err) + } + + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, responseURL, &buf) + if err != nil { + return fmt.Errorf("cannot create interactive message update request: %w", err) + } + + httpReq.Header.Set("Content-Type", "application/json") + + resp, err := c.httpClient.Do(httpReq) + if err != nil { + return fmt.Errorf("cannot send interactive message update request: %w", err) + } + defer resp.Body.Close() + + responseBody, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("failed to read response body: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(responseBody)) + } + + // Slack can return either plain text "ok" or JSON {"ok":true} + bodyStr := string(responseBody) + if bodyStr == "ok" || bodyStr == "" { + return nil + } + + var slackResponse SlackResponse + if err := json.NewDecoder(bytes.NewReader(responseBody)).Decode(&slackResponse); err == nil { + if slackResponse.OK { + return nil + } + if slackResponse.Error != "" { + return fmt.Errorf("Slack error: %s", slackResponse.Error) + } + } + + return fmt.Errorf("unexpected Slack response: %s", bodyStr) +} + +func (c *Client) UpdateMessage(ctx context.Context, accessToken string, channelID string, messageTS string, body map[string]any) error { + payload := map[string]any{ + "channel": channelID, + "ts": messageTS, + "text": body["text"], + "blocks": body["blocks"], + } + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(payload); err != nil { return fmt.Errorf("cannot marshal message: %w", err) } - body := buf.Bytes() - httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.webhookURL, bytes.NewReader(body)) + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, slackAPIUpdateMessage, &buf) if err != nil { return fmt.Errorf("cannot create request: %w", err) } httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Authorization", "Bearer "+accessToken) resp, err := c.httpClient.Do(httpReq) if err != nil { @@ -85,20 +183,76 @@ func (c *Client) PostMessage(ctx context.Context, text string) error { } defer resp.Body.Close() + responseBody, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("failed to read response body: %w", err) + } + if resp.StatusCode != http.StatusOK { - body, err := io.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("unexpected status code: %d, failed to read response body: %w", resp.StatusCode, err) - } + return fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(responseBody)) + } - var errorResponse map[string]any - var buf bytes.Buffer - buf.Write(body) - if err := json.NewDecoder(&buf).Decode(&errorResponse); err != nil { - return fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(body)) - } + var slackResponse SlackResponse + if err := json.NewDecoder(bytes.NewReader(responseBody)).Decode(&slackResponse); err != nil { + return fmt.Errorf("failed to parse Slack response: %w (body: %s)", err, string(responseBody)) + } - return fmt.Errorf("unexpected status code: %d, response: %+v", resp.StatusCode, errorResponse) + if !slackResponse.OK { + return fmt.Errorf("Slack API error: %s", slackResponse.Error) + } + + return nil +} + +func (c *Client) JoinChannel(ctx context.Context, accessToken string, channelID string) error { + payload := map[string]any{ + "channel": channelID, + } + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(payload); err != nil { + return fmt.Errorf("cannot marshal request: %w", err) + } + + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, slackAPIConversationJoin, &buf) + if err != nil { + return fmt.Errorf("cannot create request: %w", err) + } + + httpReq.Header.Set("Content-Type", "application/json") + httpReq.Header.Set("Authorization", "Bearer "+accessToken) + + resp, err := c.httpClient.Do(httpReq) + if err != nil { + return fmt.Errorf("cannot send request: %w", err) + } + defer resp.Body.Close() + + responseBody, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("failed to read response body: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(responseBody)) + } + + var slackResponse SlackResponse + + if err := json.NewDecoder(bytes.NewReader(responseBody)).Decode(&slackResponse); err != nil { + return fmt.Errorf("failed to parse Slack response: %w (body: %s)", err, string(responseBody)) + } + + if !slackResponse.OK { + if slackResponse.Error == "already_in_channel" { + return nil + } + + if slackResponse.Error == "channel_not_found" || slackResponse.Error == "is_private" { + return fmt.Errorf("cannot join private channel - bot must be invited manually") + } + + return fmt.Errorf("Slack API error: %s", slackResponse.Error) } return nil diff --git a/pkg/slack/sender.go b/pkg/slack/sender.go index 34a40e930..24cb3fef8 100644 --- a/pkg/slack/sender.go +++ b/pkg/slack/sender.go @@ -18,13 +18,11 @@ import ( "context" "errors" "fmt" - "net/http" "time" "github.com/getprobo/probo/pkg/connector" "github.com/getprobo/probo/pkg/coredata" "github.com/getprobo/probo/pkg/crypto/cipher" - "go.gearno.de/kit/httpclient" "go.gearno.de/kit/log" "go.gearno.de/kit/pg" ) @@ -35,7 +33,6 @@ type ( logger *log.Logger encryptionKey cipher.EncryptionKey interval time.Duration - httpClient *http.Client } Config struct { @@ -44,18 +41,11 @@ type ( ) func NewSender(pg *pg.Client, logger *log.Logger, encryptionKey cipher.EncryptionKey, cfg Config) *Sender { - httpClientOpts := []httpclient.Option{ - httpclient.WithLogger(logger), - } - - httpClient := httpclient.DefaultPooledClient(httpClientOpts...) - return &Sender{ pg: pg, logger: logger, encryptionKey: encryptionKey, interval: cfg.Interval, - httpClient: httpClient, } } @@ -70,6 +60,10 @@ LOOP: s.logger.ErrorCtx(ctx, "cannot send slack message", log.Error(err)) } + if err := s.batchUpdateMessages(ctx); err != nil { + s.logger.ErrorCtx(ctx, "cannot update slack message", log.Error(err)) + } + goto LOOP } } @@ -101,7 +95,14 @@ func (s *Sender) batchSendMessages(ctx context.Context) error { return err } - if sendErr := s.sendMessage(ctx, tx, message); sendErr != nil { + channelID, messageTS, sendErr := s.sendMessage(ctx, tx, message) + message.ChannelID = channelID + message.MessageTS = messageTS + + now := time.Now() + message.UpdatedAt = now + + if sendErr != nil { errorMsg := sendErr.Error() message.Error = &errorMsg message.UpdatedAt = time.Now() @@ -114,9 +115,7 @@ func (s *Sender) batchSendMessages(ctx context.Context) error { return nil } - now := time.Now() message.SentAt = &now - message.UpdatedAt = now if err := message.Update(ctx, tx); err != nil { return fmt.Errorf("cannot update slack message: %w", err) @@ -136,7 +135,137 @@ func (s *Sender) batchSendMessages(ctx context.Context) error { } } -func (s *Sender) sendMessage(ctx context.Context, tx pg.Conn, message *coredata.SlackMessage) error { +func (s *Sender) sendMessage(ctx context.Context, tx pg.Conn, message *coredata.SlackMessage) (*string, *string, error) { + tenantID := message.ID.TenantID() + scope := coredata.NewScope(tenantID) + + var connectors coredata.Connectors + if err := connectors.LoadAllByOrganizationIDProtocolAndProvider( + ctx, + tx, + scope, + message.OrganizationID, + coredata.ConnectorProtocolOAuth2, + coredata.ConnectorProviderSlack, + s.encryptionKey, + ); err != nil { + return nil, nil, fmt.Errorf("cannot load slack connectors: %w", err) + } + + if len(connectors) == 0 { + return nil, nil, fmt.Errorf("no slack connectors configured for organization") + } + + c := connectors[0] + if c.Connection == nil { + return nil, nil, fmt.Errorf("slack connector has nil connection") + } + + slackConn, ok := c.Connection.(*connector.SlackConnection) + if !ok { + return nil, nil, fmt.Errorf("slack connector must have SlackConnection type, got %T", c.Connection) + } + + if slackConn.Settings.ChannelID == "" { + return nil, nil, fmt.Errorf("slack connector %s has no channel ID", c.ID) + } + + if slackConn.AccessToken == "" { + return nil, nil, fmt.Errorf("slack connector %s has no access token", c.ID) + } + + client := NewClient(s.logger) + + if message.Type == coredata.SlackMessageTypeWelcome { + if err := client.JoinChannel(ctx, slackConn.AccessToken, slackConn.Settings.ChannelID); err != nil { + s.logger.ErrorCtx(ctx, "failed to join Slack channel", log.Error(err)) + } + } + + slackResp, err := client.CreateMessage(ctx, slackConn.AccessToken, slackConn.Settings.ChannelID, message.Body) + if err != nil { + s.logger.ErrorCtx(ctx, "failed to post message to Slack", log.Error(err)) + return nil, nil, fmt.Errorf("failed to post message to Slack: %w", err) + } + + return &slackResp.Channel, &slackResp.TS, nil +} + +func (s *Sender) batchUpdateMessages(ctx context.Context) error { + for { + err := s.pg.WithTx( + ctx, + func(tx pg.Conn) (err error) { + update := &coredata.SlackMessageUpdate{} + + defer func() { + if r := recover(); r != nil { + panicErr := fmt.Sprintf("panic recovered: %v", r) + update.Error = &panicErr + update.UpdatedAt = time.Now() + + if updateErr := update.Update(ctx, tx); updateErr != nil { + s.logger.ErrorCtx(ctx, "cannot update slack message update after panic", log.Error(updateErr)) + } + + s.logger.ErrorCtx(ctx, "panic while updating slack message", log.String("error", panicErr), log.String("update_id", update.ID.String())) + err = fmt.Errorf("panic recovered: %v", r) + } + }() + + err = update.LoadNextUnsentForUpdate(ctx, tx) + if err != nil { + return err + } + + message := &coredata.SlackMessage{} + if err := message.LoadById(ctx, tx, coredata.NewScope(update.SlackMessageID.TenantID()), update.SlackMessageID); err != nil { + return fmt.Errorf("cannot load slack message: %w", err) + } + + updateErr := s.updateMessage(ctx, tx, message, update) + + now := time.Now() + update.UpdatedAt = now + + if updateErr != nil { + errorMsg := updateErr.Error() + update.Error = &errorMsg + update.UpdatedAt = time.Now() + + if err := update.Update(ctx, tx); err != nil { + return fmt.Errorf("cannot update slack message update with error: %w", err) + } + + s.logger.ErrorCtx(ctx, "error updating slack message", log.Error(updateErr), log.String("update_id", update.ID.String())) + return nil + } + + update.SentAt = &now + + if err := update.Update(ctx, tx); err != nil { + return fmt.Errorf("cannot update slack message update: %w", err) + } + + return nil + }, + ) + + if errors.Is(err, coredata.ErrNoUnsentSlackMessageUpdate{}) { + return nil + } + + if err != nil { + return err + } + } +} + +func (s *Sender) updateMessage(ctx context.Context, tx pg.Conn, message *coredata.SlackMessage, update *coredata.SlackMessageUpdate) error { + if message.ChannelID == nil || message.MessageTS == nil { + return fmt.Errorf("slack message has no channel ID or message TS") + } + tenantID := message.ID.TenantID() scope := coredata.NewScope(tenantID) @@ -157,20 +286,25 @@ func (s *Sender) sendMessage(ctx context.Context, tx pg.Conn, message *coredata. return fmt.Errorf("no slack connectors configured for organization") } - for _, c := range connectors { - slackConn, ok := c.Connection.(*connector.SlackConnection) - if !ok { - return fmt.Errorf("slack connector must have SlackConnection type") - } + c := connectors[0] + if c.Connection == nil { + return fmt.Errorf("slack connector has nil connection") + } - if slackConn.Settings.WebhookURL == "" { - return fmt.Errorf("slack connector %s has no webhook URL", c.ID) - } + slackConn, ok := c.Connection.(*connector.SlackConnection) + if !ok { + return fmt.Errorf("slack connector must have SlackConnection type, got %T", c.Connection) + } - client := NewClient(slackConn.Settings.WebhookURL, s.httpClient) - if err := client.PostMessage(ctx, message.Body); err != nil { - return fmt.Errorf("failed to post message to Slack: %w", err) - } + if slackConn.AccessToken == "" { + return fmt.Errorf("slack connector %s has no access token", c.ID) + } + + client := NewClient(s.logger) + + if err := client.UpdateMessage(ctx, slackConn.AccessToken, *message.ChannelID, *message.MessageTS, update.Body); err != nil { + s.logger.ErrorCtx(ctx, "failed to update message on Slack", log.Error(err)) + return fmt.Errorf("failed to update message on Slack: %w", err) } return nil diff --git a/pkg/slack/signature.go b/pkg/slack/signature.go new file mode 100644 index 000000000..27b2830e2 --- /dev/null +++ b/pkg/slack/signature.go @@ -0,0 +1,56 @@ +// Copyright (c) 2025 Probo Inc . +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +// PERFORMANCE OF THIS SOFTWARE. + +package slack + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + "strconv" + "time" +) + +// VerifySignature implements the verification algorithm described in https://api.slack.com/authentication/verifying-requests-from-slack +func VerifySignature(signingSecret, timestamp, signature string, body []byte) error { + // Check timestamp to prevent replay attacks + ts, err := strconv.ParseInt(timestamp, 10, 64) + if err != nil { + return fmt.Errorf("invalid timestamp: %w", err) + } + + now := time.Now().Unix() + if abs(now-ts) > 60*5 { // 5 minutes + return fmt.Errorf("request timestamp too old") + } + + baseString := fmt.Sprintf("v0:%s:%s", timestamp, body) + h := hmac.New(sha256.New, []byte(signingSecret)) + h.Write([]byte(baseString)) + expected := "v0=" + hex.EncodeToString(h.Sum(nil)) + + if !hmac.Equal([]byte(expected), []byte(signature)) { + return fmt.Errorf("signature mismatch") + } + + return nil +} + +func abs(n int64) int64 { + if n < 0 { + return -n + } + return n +} diff --git a/pkg/trust/organization_service.go b/pkg/trust/organization_service.go index 5cb37cb7a..3ce3f25b4 100644 --- a/pkg/trust/organization_service.go +++ b/pkg/trust/organization_service.go @@ -61,6 +61,40 @@ func (s OrganizationService) Get( return organization, nil } +func (s OrganizationService) GetOrganizationCustomDomain( + ctx context.Context, + organizationID gid.GID, +) (*coredata.CustomDomain, error) { + var domain *coredata.CustomDomain + + err := s.svc.pg.WithConn( + ctx, + func(conn pg.Conn) error { + var org coredata.Organization + if err := org.LoadByID(ctx, conn, s.svc.scope, organizationID); err != nil { + return fmt.Errorf("cannot load organization: %w", err) + } + + if org.CustomDomainID == nil { + return nil + } + + domain = &coredata.CustomDomain{} + if err := domain.LoadByID(ctx, conn, s.svc.scope, s.svc.encryptionKey, *org.CustomDomainID); err != nil { + return fmt.Errorf("cannot load custom domain: %w", err) + } + + return nil + }, + ) + + if err != nil { + return nil, err + } + + return domain, nil +} + func (s OrganizationService) GenerateLogoURL( ctx context.Context, organizationID gid.GID, diff --git a/pkg/trust/service.go b/pkg/trust/service.go index 159496ea6..841e7f802 100644 --- a/pkg/trust/service.go +++ b/pkg/trust/service.go @@ -15,6 +15,8 @@ package trust import ( + "time" + "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/getprobo/probo/pkg/auth" "github.com/getprobo/probo/pkg/coredata" @@ -23,21 +25,32 @@ import ( "github.com/getprobo/probo/pkg/gid" "github.com/getprobo/probo/pkg/html2pdf" "github.com/getprobo/probo/pkg/probo" + "github.com/getprobo/probo/pkg/slack" + "go.gearno.de/kit/log" "go.gearno.de/kit/pg" ) type ( + TrustConfig struct { + TokenSecret string + TokenDuration time.Duration + TokenType string + } + Service struct { - pg *pg.Client - s3 *s3.Client - bucket string - proboSvc *probo.Service - encryptionKey cipher.EncryptionKey - tokenSecret string - hostname string - auth *auth.Service - html2pdfConverter *html2pdf.Converter - fileManager *filemanager.Service + pg *pg.Client + s3 *s3.Client + bucket string + proboSvc *probo.Service + encryptionKey cipher.EncryptionKey + tokenSecret string + slackSigningSecret string + hostname string + auth *auth.Service + html2pdfConverter *html2pdf.Converter + fileManager *filemanager.Service + logger *log.Logger + trustConfig TrustConfig } TenantService struct { @@ -52,6 +65,8 @@ type ( auth *auth.Service html2pdfConverter *html2pdf.Converter fileManager *filemanager.Service + logger *log.Logger + trustConfig TrustConfig TrustCenters *TrustCenterService Documents *DocumentService Audits *AuditService @@ -61,6 +76,7 @@ type ( TrustCenterReferences *TrustCenterReferenceService Reports *ReportService Organizations *OrganizationService + SlackMessages *SlackMessageService } ) @@ -71,20 +87,26 @@ func NewService( hostname string, encryptionKey cipher.EncryptionKey, tokenSecret string, + slackSigningSecret string, auth *auth.Service, html2pdfConverter *html2pdf.Converter, fileManagerService *filemanager.Service, + logger *log.Logger, + trustConfig TrustConfig, ) *Service { return &Service{ - pg: pgClient, - s3: s3Client, - bucket: bucket, - encryptionKey: encryptionKey, - tokenSecret: tokenSecret, - hostname: hostname, - auth: auth, - html2pdfConverter: html2pdfConverter, - fileManager: fileManagerService, + pg: pgClient, + s3: s3Client, + bucket: bucket, + encryptionKey: encryptionKey, + tokenSecret: tokenSecret, + slackSigningSecret: slackSigningSecret, + hostname: hostname, + auth: auth, + html2pdfConverter: html2pdfConverter, + fileManager: fileManagerService, + logger: logger, + trustConfig: trustConfig, } } @@ -101,17 +123,22 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService { auth: s.auth, html2pdfConverter: s.html2pdfConverter, fileManager: s.fileManager, + logger: s.logger, + trustConfig: s.trustConfig, } + slackClient := slack.NewClient(s.logger) + tenantService.TrustCenters = &TrustCenterService{svc: tenantService} tenantService.Documents = &DocumentService{svc: tenantService, html2pdfConverter: s.html2pdfConverter} tenantService.Audits = &AuditService{svc: tenantService} tenantService.Vendors = &VendorService{svc: tenantService} tenantService.Frameworks = &FrameworkService{svc: tenantService} - tenantService.TrustCenterAccesses = &TrustCenterAccessService{svc: tenantService, auth: s.auth} + tenantService.TrustCenterAccesses = &TrustCenterAccessService{svc: tenantService, auth: s.auth, logger: s.logger} tenantService.TrustCenterReferences = &TrustCenterReferenceService{svc: tenantService} tenantService.Reports = &ReportService{svc: tenantService} tenantService.Organizations = &OrganizationService{svc: tenantService} + tenantService.SlackMessages = &SlackMessageService{svc: tenantService, slackClient: slackClient} return tenantService } @@ -119,3 +146,7 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService { func (s *Service) GetTokenSecret() string { return s.tokenSecret } + +func (s *Service) GetSlackSigningSecret() string { + return s.slackSigningSecret +} diff --git a/pkg/trust/slack_message_service.go b/pkg/trust/slack_message_service.go new file mode 100644 index 000000000..de672d5c7 --- /dev/null +++ b/pkg/trust/slack_message_service.go @@ -0,0 +1,337 @@ +// Copyright (c) 2025 Probo Inc . +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +// PERFORMANCE OF THIS SOFTWARE. + +package trust + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "maps" + "time" + + "github.com/getprobo/probo/pkg/coredata" + "github.com/getprobo/probo/pkg/gid" + "github.com/getprobo/probo/pkg/slack" + "go.gearno.de/kit/pg" +) + +const ( + slackMessageDeduplicationWindow = 7 * 24 * time.Hour + trustCenterAccessURLFormat = "https://%s/organizations/%s/trust-center/access" +) + +type SlackMessageService struct { + svc *TenantService + slackClient *slack.Client +} + +func (s *SlackMessageService) LoadSlackMessageUnscoped( + ctx context.Context, + channelID string, + messageTS string, +) (*coredata.SlackMessage, error) { + var slackMessage coredata.SlackMessage + + err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error { + if err := slackMessage.LoadByChannelAndTSUnscoped(ctx, conn, channelID, messageTS); err != nil { + return fmt.Errorf("cannot load slack message: %w", err) + } + + return nil + }) + + if err != nil { + return nil, err + } + + return &slackMessage, nil +} + +func (s *SlackMessageService) UpdateSlackAccessMessage( + ctx context.Context, + slackMessageID gid.GID, + actionID string, + value string, + responseURL string, +) error { + return s.svc.pg.WithTx(ctx, func(tx pg.Conn) error { + var slackMessage coredata.SlackMessage + if err := slackMessage.LoadById(ctx, tx, s.svc.scope, slackMessageID); err != nil { + return fmt.Errorf("cannot load slack message: %w", err) + } + + baseBody := slackMessage.Body + var latestUpdate coredata.SlackMessageUpdate + if err := latestUpdate.LoadLatestBySlackMessageID(ctx, tx, slackMessage.ID); err == nil { + baseBody = latestUpdate.Body + } + + accessTabURL := fmt.Sprintf(trustCenterAccessURLFormat, s.svc.hostname, slackMessage.OrganizationID) + updatedBody := s.changeButton(baseBody, actionID, value, accessTabURL) + + slackMessageUpdate := coredata.NewSlackMessageUpdate(s.svc.scope, slackMessage.ID, updatedBody) + now := time.Now() + slackMessageUpdate.SentAt = &now + if err := slackMessageUpdate.Insert(ctx, tx, s.svc.scope); err != nil { + return fmt.Errorf("cannot insert slack message update: %w", err) + } + + if err := s.slackClient.UpdateInteractiveMessage(ctx, responseURL, updatedBody); err != nil { + return fmt.Errorf("failed to update Slack message: %w", err) + } + + return nil + }) +} + +func (s *SlackMessageService) QueueSlackNotification( + ctx context.Context, + requesterEmail string, + trustCenterID gid.GID, +) error { + return s.svc.pg.WithTx(ctx, func(tx pg.Conn) error { + var trustCenterAccess coredata.TrustCenterAccess + if err := trustCenterAccess.LoadByTrustCenterIDAndEmail(ctx, tx, s.svc.scope, trustCenterID, requesterEmail); err != nil { + return fmt.Errorf("cannot load trust center access: %w", err) + } + + var trustCenter coredata.TrustCenter + if err := trustCenter.LoadByID(ctx, tx, s.svc.scope, trustCenterID); err != nil { + return fmt.Errorf("cannot load trust center: %w", err) + } + + var accesses coredata.TrustCenterDocumentAccesses + if err := accesses.LoadAllByTrustCenterAccessID(ctx, tx, s.svc.scope, trustCenterAccess.ID); err != nil { + return fmt.Errorf("cannot load trust center document accesses: %w", err) + } + + var documentIDs []string + var reportIDs []string + var documents []struct { + ID string + Title string + Granted bool + } + var reports []struct { + ID string + Title string + AuditID string + Granted bool + } + + for _, access := range accesses { + if access.DocumentID != nil { + doc := &coredata.Document{} + if err := doc.LoadByID(ctx, tx, s.svc.scope, *access.DocumentID); err != nil { + return fmt.Errorf("cannot load document: %w", err) + } + documentIDs = append(documentIDs, access.DocumentID.String()) + documents = append(documents, struct { + ID string + Title string + Granted bool + }{ + ID: access.DocumentID.String(), + Title: doc.Title, + Granted: access.Active, + }) + } + + if access.ReportID != nil { + rep := &coredata.Report{} + if err := rep.LoadByID(ctx, tx, s.svc.scope, *access.ReportID); err != nil { + return fmt.Errorf("cannot load report: %w", err) + } + + audit := &coredata.Audit{} + if err := audit.LoadByReportID(ctx, tx, s.svc.scope, *access.ReportID); err != nil { + return fmt.Errorf("cannot load audit: %w", err) + } + + framework := &coredata.Framework{} + if err := framework.LoadByID(ctx, tx, s.svc.scope, audit.FrameworkID); err != nil { + return fmt.Errorf("cannot load framework: %w", err) + } + + label := framework.Name + if audit.Name != nil && *audit.Name != "" { + label = label + " - " + *audit.Name + } + reportIDs = append(reportIDs, access.ReportID.String()) + reports = append(reports, struct { + ID string + Title string + AuditID string + Granted bool + }{ + ID: access.ReportID.String(), + Title: label, + AuditID: audit.ID.String(), + Granted: access.Active, + }) + } + } + + templateData := struct { + RequesterName string + RequesterEmail string + OrganizationID string + Domain string + DocumentIDs []string + ReportIDs []string + Documents []struct { + ID string + Title string + Granted bool + } + Reports []struct { + ID string + Title string + AuditID string + Granted bool + } + }{ + RequesterName: trustCenterAccess.Name, + RequesterEmail: requesterEmail, + OrganizationID: trustCenter.OrganizationID.String(), + Domain: s.svc.hostname, + DocumentIDs: documentIDs, + ReportIDs: reportIDs, + Documents: documents, + Reports: reports, + } + + var buf bytes.Buffer + if err := accessRequestTemplate.Execute(&buf, templateData); err != nil { + return fmt.Errorf("failed to execute template: %w", err) + } + + var body map[string]any + if err := json.NewDecoder(&buf).Decode(&body); err != nil { + return fmt.Errorf("failed to parse template JSON: %w", err) + } + + sevenDaysAgo := time.Now().Add(-slackMessageDeduplicationWindow) + var existingMessage coredata.SlackMessage + err := existingMessage.LoadLatestByRequesterEmailAndType( + ctx, + tx, + s.svc.scope, + trustCenter.OrganizationID, + requesterEmail, + coredata.SlackMessageTypeTrustCenterAccessRequest, + sevenDaysAgo, + ) + + if err == nil && existingMessage.MessageTS != nil && existingMessage.ChannelID != nil { + slackMessageUpdate := coredata.NewSlackMessageUpdate(s.svc.scope, existingMessage.ID, body) + if err := slackMessageUpdate.Insert(ctx, tx, s.svc.scope); err != nil { + return fmt.Errorf("cannot insert slack message update: %w", err) + } + + return nil + } + + slackMessage := coredata.NewSlackMessage(s.svc.scope, trustCenter.OrganizationID, coredata.SlackMessageTypeTrustCenterAccessRequest, body, &requesterEmail) + if err := slackMessage.Insert(ctx, tx, s.svc.scope); err != nil { + return fmt.Errorf("cannot insert slack message: %w", err) + } + + return nil + }) +} + +func (s *SlackMessageService) changeButton(body map[string]any, actionID string, value string, accessTabURL string) map[string]any { + blocks, ok := body["blocks"].([]any) + if !ok { + return body + } + + isAcceptAll := actionID == "accept_all" + + updatedBlocks := make([]any, len(blocks)) + for i, blockAny := range blocks { + block, ok := blockAny.(map[string]any) + if !ok { + updatedBlocks[i] = blockAny + continue + } + + blockCopy := make(map[string]any) + maps.Copy(blockCopy, block) + + if blockType, ok := block["type"].(string); ok && blockType == "section" { + if acc, ok := block["accessory"].(map[string]any); ok { + if s.shouldChangeButton(acc, actionID, value, isAcceptAll) { + blockCopy["accessory"] = s.makeStaticButton(accessTabURL) + } + } + } + + if blockType, ok := block["type"].(string); ok && blockType == "actions" { + if elements, ok := block["elements"].([]any); ok { + updatedElements := make([]any, len(elements)) + for j, elemAny := range elements { + elem, ok := elemAny.(map[string]any) + if !ok { + updatedElements[j] = elemAny + continue + } + + if s.shouldChangeButton(elem, actionID, value, isAcceptAll) { + updatedElements[j] = s.makeStaticButton(accessTabURL) + } else { + updatedElements[j] = elem + } + } + blockCopy["elements"] = updatedElements + } + } + + updatedBlocks[i] = blockCopy + } + + updatedBody := make(map[string]any) + maps.Copy(updatedBody, body) + updatedBody["blocks"] = updatedBlocks + + return updatedBody +} + +func (s *SlackMessageService) shouldChangeButton(button map[string]any, actionID string, value string, isAcceptAll bool) bool { + if button["type"] != "button" { + return false + } + + btnActionID, _ := button["action_id"].(string) + btnValue, _ := button["value"].(string) + + isExactMatch := btnActionID == actionID && btnValue == value + isAcceptAllMatch := isAcceptAll && (btnActionID == "accept_document" || btnActionID == "accept_report") + + return isExactMatch || isAcceptAllMatch +} + +func (s *SlackMessageService) makeStaticButton(accessTabURL string) map[string]any { + return map[string]any{ + "type": "button", + "text": map[string]any{ + "type": "plain_text", + "text": "✓ Granted", + }, + "url": accessTabURL, + } +} diff --git a/pkg/trust/templates/access-request.json.tmpl b/pkg/trust/templates/access-request.json.tmpl new file mode 100644 index 000000000..824fc644e --- /dev/null +++ b/pkg/trust/templates/access-request.json.tmpl @@ -0,0 +1,121 @@ +{ + "text": "New Trust Center Access Request", + "blocks": [ + { + "type": "header", + "text": { + "type": "plain_text", + "text": "🔒 New Trust Center Access Request" + } + }, + { + "type": "context", + "elements": [ + { + "type": "mrkdwn", + "text": "👤 Requested by *{{jsonEscape .RequesterName}}* <{{jsonEscape .RequesterEmail}}>" + } + ] + }, + { + "type": "actions", + "elements": [ + { + "type": "button", + "text": { + "type": "plain_text", + "text": "✅ Accept All" + }, + "action_id": "accept_all", + "value": "{{buildAcceptAllValue .DocumentIDs .ReportIDs}}", + "style": "primary" + }, + { + "type": "button", + "text": { + "type": "plain_text", + "text": "👁️ View Requests" + }, + "url": "https://{{.Domain}}/organizations/{{.OrganizationID}}/trust-center/access" + } + ] + }{{if .Documents}}, + { + "type": "divider" + }, + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "*📄 Requested Documents*" + } + }{{range .Documents}}, + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "" + }, + "accessory": {{if .Granted}}{ + "type": "button", + "text": { + "type": "plain_text", + "text": "✓ Granted" + }, + "url": "https://{{$.Domain}}/organizations/{{$.OrganizationID}}/trust-center/access" + }{{else}}{ + "type": "button", + "text": { + "type": "plain_text", + "text": "Accept" + }, + "action_id": "accept_document", + "value": "{{.ID}}", + "style": "primary" + }{{end}} + }{{end}}{{end}}{{if .Reports}}, + { + "type": "divider" + }, + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "*📊 Requested Audit Reports*" + } + }{{range .Reports}}, + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "" + }, + "accessory": {{if .Granted}}{ + "type": "button", + "text": { + "type": "plain_text", + "text": "✓ Granted" + }, + "url": "https://{{$.Domain}}/organizations/{{$.OrganizationID}}/trust-center/access" + }{{else}}{ + "type": "button", + "text": { + "type": "plain_text", + "text": "Accept" + }, + "action_id": "accept_report", + "value": "{{.ID}}", + "style": "primary" + }{{end}} + }{{end}}{{end}}, + { + "type": "context", + "elements": [ + { + "type": "mrkdwn", + "text": "⚠️ _Updates from this message will only work for 14 days_" + } + ] + } + ] +} diff --git a/pkg/trust/templates/access-request.txt.tmpl b/pkg/trust/templates/access-request.txt.tmpl deleted file mode 100644 index 4aad10a8f..000000000 --- a/pkg/trust/templates/access-request.txt.tmpl +++ /dev/null @@ -1,7 +0,0 @@ -*New Trust Center Access Request* - -*Organization:* {{.OrganizationName}} -*Requested by:* {{.RequesterName}} -*Email:* {{.RequesterEmail}} - -<{{.ConsoleUrl}}|View Access Requests> diff --git a/pkg/trust/trust_center_access_service.go b/pkg/trust/trust_center_access_service.go index f705faf5b..b24e28add 100644 --- a/pkg/trust/trust_center_access_service.go +++ b/pkg/trust/trust_center_access_service.go @@ -15,32 +15,58 @@ package trust import ( - "bytes" "context" "encoding/json" "errors" "fmt" "net/mail" + "net/url" + "strings" "text/template" "time" + "github.com/getprobo/probo/packages/emails" "github.com/getprobo/probo/pkg/auth" "github.com/getprobo/probo/pkg/coredata" "github.com/getprobo/probo/pkg/gid" + "github.com/getprobo/probo/pkg/probo" + "github.com/getprobo/probo/pkg/statelesstoken" + "go.gearno.de/kit/log" "go.gearno.de/kit/pg" ) var ( - accessRequestTemplate = template.Must(template.ParseFS(Templates, "templates/access-request.txt.tmpl")) + accessRequestTemplate = template.Must( + template.New("access-request.json.tmpl"). + Funcs(template.FuncMap{ + "jsonEscape": func(s string) string { + b, _ := json.Marshal(s) + return string(b[1 : len(b)-1]) + }, + "buildAcceptAllValue": func(docIDs, repIDs []string) string { + value := map[string][]string{ + "document_ids": docIDs, + "report_ids": repIDs, + } + b, _ := json.Marshal(value) + s := string(b) + s = strings.ReplaceAll(s, `\`, `\\`) + s = strings.ReplaceAll(s, `"`, `\"`) + return s + }, + }). + ParseFS(Templates, "templates/access-request.json.tmpl"), + ) ) type ( TrustCenterAccessService struct { - svc *TenantService - auth *auth.Service + svc *TenantService + auth *auth.Service + logger *log.Logger } - RequestTrustCenterAccessRequest struct { + TrustCenterAccessRequest struct { TrustCenterID gid.GID Email string Name *string @@ -50,7 +76,6 @@ type ( ) const ( - TokenTypeTrustCenterAccess = "trust_center_access" TrustCenterAccessURLFormat = "https://%s/organizations/%s/trust-center/access" ) @@ -76,7 +101,7 @@ func (s TrustCenterAccessService) ValidateToken( func (s TrustCenterAccessService) Request( ctx context.Context, - req *RequestTrustCenterAccessRequest, + req *TrustCenterAccessRequest, ) (*coredata.TrustCenterAccess, error) { now := time.Now() @@ -175,10 +200,6 @@ func (s TrustCenterAccessService) Request( return fmt.Errorf("cannot bulk insert trust center report accesses: %w", err) } - if err := s.queueSlackNotification(ctx, tx, organizationID, access.Name, access.Email); err != nil { - return fmt.Errorf("cannot queue slack notification: %w", err) - } - return nil }) @@ -186,6 +207,10 @@ func (s TrustCenterAccessService) Request( return nil, err } + if err := s.svc.SlackMessages.QueueSlackNotification(ctx, access.Email, req.TrustCenterID); err != nil { + s.logger.ErrorCtx(ctx, "cannot queue slack notification") + } + return access, nil } @@ -310,6 +335,136 @@ func (s TrustCenterAccessService) LoadReportAccess( return reportAccess, nil } +func (s *TrustCenterAccessService) AcceptByIDs( + ctx context.Context, + trustCenterID gid.GID, + email string, + documentIDs []gid.GID, + reportIDs []gid.GID, +) error { + return s.svc.pg.WithTx(ctx, func(tx pg.Conn) error { + access := &coredata.TrustCenterAccess{} + if err := access.LoadByTrustCenterIDAndEmail(ctx, tx, s.svc.scope, trustCenterID, email); err != nil { + return fmt.Errorf("cannot load trust center access: %w", err) + } + + wasInactive := !access.Active + now := time.Now() + + if len(documentIDs) > 0 { + if err := coredata.ActivateByDocumentIDs(ctx, tx, s.svc.scope, access.ID, documentIDs, now); err != nil { + return fmt.Errorf("cannot activate document accesses: %w", err) + } + } + if len(reportIDs) > 0 { + if err := coredata.ActivateByReportIDs(ctx, tx, s.svc.scope, access.ID, reportIDs, now); err != nil { + return fmt.Errorf("cannot activate report accesses: %w", err) + } + } + + if wasInactive { + access.Active = true + access.UpdatedAt = now + if err := access.Update(ctx, tx, s.svc.scope); err != nil { + return fmt.Errorf("cannot update trust center access: %w", err) + } + + if err := s.sendAccessEmail(ctx, tx, access); err != nil { + return fmt.Errorf("failed to send access email: %w", err) + } + } + + return nil + }) +} + +func (s *TrustCenterAccessService) sendAccessEmail(ctx context.Context, tx pg.Conn, access *coredata.TrustCenterAccess) error { + accessToken, err := statelesstoken.NewToken( + s.svc.trustConfig.TokenSecret, + s.svc.trustConfig.TokenType, + s.svc.trustConfig.TokenDuration, + probo.TrustCenterAccessData{ + TrustCenterID: access.TrustCenterID, + Email: access.Email, + }, + ) + if err != nil { + return fmt.Errorf("cannot generate access token: %w", err) + } + + trustCenter := &coredata.TrustCenter{} + err = trustCenter.LoadByID(ctx, tx, s.svc.scope, access.TrustCenterID) + if err != nil { + return fmt.Errorf("cannot load trust center: %w", err) + } + + organization := &coredata.Organization{} + err = organization.LoadByID(ctx, tx, s.svc.scope, trustCenter.OrganizationID) + if err != nil { + return fmt.Errorf("cannot load organization: %w", err) + } + + hostname := s.svc.hostname + path := "/trust/" + trustCenter.Slug + "/access" + + if organization.CustomDomainID != nil { + customDomain, err := s.svc.Organizations.GetOrganizationCustomDomain(ctx, organization.ID) + if err != nil { + return fmt.Errorf("cannot load custom domain: %w", err) + } + + if customDomain == nil || customDomain.SSLStatus != coredata.CustomDomainSSLStatusActive { + return fmt.Errorf("custom domain is not active") + } + + hostname = customDomain.Domain + path = "/access" + } + + accessURL := url.URL{ + Scheme: "https", + Host: hostname, + Path: path, + RawQuery: url.Values{ + "token": []string{accessToken}, + }.Encode(), + } + + return s.sendTrustCenterAccessEmail(ctx, tx, access.Name, access.Email, organization.Name, accessURL.String()) +} + +func (s *TrustCenterAccessService) sendTrustCenterAccessEmail( + ctx context.Context, + tx pg.Conn, + name string, + email string, + companyName string, + accessURL string, +) error { + subject, textBody, htmlBody, err := emails.RenderTrustCenterAccess( + s.svc.hostname, + name, + companyName, + accessURL, + ) + if err != nil { + return fmt.Errorf("cannot render trust center access email: %w", err) + } + + accessEmail := coredata.NewEmail( + name, + email, + subject, + textBody, + htmlBody, + ) + + if err := accessEmail.Insert(ctx, tx); err != nil { + return fmt.Errorf("cannot insert access email: %w", err) + } + return nil +} + func extractExistingIDs(accesses coredata.TrustCenterDocumentAccesses) ([]gid.GID, []gid.GID) { var documentIDs []gid.GID var reportIDs []gid.GID @@ -341,42 +496,3 @@ func filterExistingIDs(allIDs []gid.GID, existingIDs []gid.GID) []gid.GID { return newIDs } - -func (s TrustCenterAccessService) queueSlackNotification( - ctx context.Context, - tx pg.Conn, - organizationID gid.GID, - requesterName string, - requesterEmail string, -) error { - var organization coredata.Organization - if err := organization.LoadByID(ctx, tx, s.svc.scope, organizationID); err != nil { - return fmt.Errorf("cannot load organization: %w", err) - } - - consoleURL := fmt.Sprintf(TrustCenterAccessURLFormat, s.svc.hostname, organizationID) - - data := struct { - OrganizationName string - RequesterName string - RequesterEmail string - ConsoleUrl string - }{ - OrganizationName: organization.Name, - RequesterName: requesterName, - RequesterEmail: requesterEmail, - ConsoleUrl: consoleURL, - } - - var buf bytes.Buffer - if err := accessRequestTemplate.Execute(&buf, data); err != nil { - return fmt.Errorf("failed to execute template: %w", err) - } - - slackMessage := coredata.NewSlackMessage(s.svc.scope, organizationID, buf.String()) - if err := slackMessage.Insert(ctx, tx, s.svc.scope); err != nil { - return fmt.Errorf("cannot insert slack message: %w", err) - } - - return nil -}