Link previews: link cards for GitHub issues, pull requests and repositories, Linear issues and Figma files are read through the services' APIs and show a status pill (Open, Merged, In Progress…) and a line of details. Public items need nothing; a workspace's tokens, set by its admins under Workspace settings → Integrations and checked with each service before being sealed, reach private ones and Linear. GET /link-preview takes the workspace; the link card stores kind, status, state and meta. Slack: each workspace connects its own Slack app, made from a manifest the settings page fills in. Docwell posts chosen page and comment events to a channel (edits at most every 30 minutes per page), previews links to Docwell pages posted in Slack, and answers /docwell with a search as the member whose email matches the Slack user, shown only to them. Only pages every member can open are posted or previewed. Requests from Slack are signature-checked; the webhook dispatcher gained listeners so Slack follows the same events. Confluence: a space's HTML export imports with its page tree (from index.html, else breadcrumbs), links between pages, pictures and attachments. Panels become callouts, code macros code blocks with their language, expand macros toggles, task lists to-dos. New collection workspace_integrations (schema snapshot regenerated), OpenAPI and generated Go, TypeScript and Dart types, strings in all five languages, the user guide, and a rebuilt mobile editor bundle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
412 lines
15 KiB
Go
412 lines
15 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package integrations
|
|
|
|
import (
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/directory"
|
|
"docwell/server/internal/search"
|
|
"docwell/server/internal/store/pocketbase"
|
|
"docwell/server/internal/unfurl"
|
|
"docwell/server/internal/webhooks"
|
|
)
|
|
|
|
const ws = "ws0000000000001"
|
|
|
|
// ---- Fakes -----------------------------------------------------------------------
|
|
|
|
type fakeDir struct {
|
|
roles map[string]string // caller id -> workspace role
|
|
pages map[string]directory.ChatPage
|
|
people map[string]string // email -> caller id
|
|
hits []directory.SearchHit
|
|
asked access.Caller
|
|
}
|
|
|
|
func (d *fakeDir) WorkspaceRole(_ context.Context, c access.Caller, wsID string) (string, error) {
|
|
if r, ok := d.roles[c.ID]; ok && wsID == ws {
|
|
return r, nil
|
|
}
|
|
return "", apperr.NotFound("workspace not found")
|
|
}
|
|
|
|
func (d *fakeDir) OpenToMembers(_ context.Context, wsID, id string) (directory.ChatPage, bool) {
|
|
p, ok := d.pages[id]
|
|
return p, ok && wsID == ws
|
|
}
|
|
|
|
func (d *fakeDir) MemberByEmail(_ context.Context, _ string, email string) (access.Caller, error) {
|
|
if id, ok := d.people[email]; ok {
|
|
return access.Caller{ID: id}, nil
|
|
}
|
|
return access.Caller{}, apperr.NotFound("no such member")
|
|
}
|
|
|
|
func (d *fakeDir) Search(_ context.Context, c access.Caller, _ string, q directory.SearchQuery) (directory.SearchResult, error) {
|
|
d.asked = c
|
|
if q.Text == "nothing" {
|
|
return directory.SearchResult{}, nil
|
|
}
|
|
return directory.SearchResult{Items: d.hits, Total: 9}, nil
|
|
}
|
|
|
|
// fakePB keeps workspace_integrations records in memory.
|
|
func fakePB(t *testing.T) *pocketbase.Client {
|
|
t.Helper()
|
|
var mu sync.Mutex
|
|
recs := map[string]map[string]any{}
|
|
n := 0
|
|
reply := func(w http.ResponseWriter, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) {
|
|
reply(w, map[string]string{"token": "su"})
|
|
})
|
|
mux.HandleFunc("GET /api/collections/workspace_integrations/records", func(w http.ResponseWriter, r *http.Request) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
items := []map[string]any{}
|
|
for _, rec := range recs {
|
|
if r.URL.Query().Get("filter") == "workspace = '"+rec["workspace"].(string)+"'" {
|
|
items = append(items, rec)
|
|
}
|
|
}
|
|
reply(w, map[string]any{"items": items, "totalItems": len(items), "totalPages": 1})
|
|
})
|
|
mux.HandleFunc("POST /api/collections/workspace_integrations/records", func(w http.ResponseWriter, r *http.Request) {
|
|
var body map[string]any
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
mu.Lock()
|
|
n++
|
|
body["id"] = "int" + strconv.Itoa(n)
|
|
recs[body["id"].(string)] = body
|
|
mu.Unlock()
|
|
reply(w, body)
|
|
})
|
|
mux.HandleFunc("PATCH /api/collections/workspace_integrations/records/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
var body map[string]any
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
mu.Lock()
|
|
rec := recs[r.PathValue("id")]
|
|
for k, v := range body {
|
|
rec[k] = v
|
|
}
|
|
mu.Unlock()
|
|
reply(w, rec)
|
|
})
|
|
srv := httptest.NewServer(mux)
|
|
t.Cleanup(srv.Close)
|
|
return pocketbase.New(srv.URL, "su@x.test", "pw")
|
|
}
|
|
|
|
// fakeServices answers as GitHub, Linear, Figma and Slack would.
|
|
type fakeServices struct {
|
|
mu sync.Mutex
|
|
posts []map[string]any // chat.postMessage and chat.unfurl bodies, with "method"
|
|
}
|
|
|
|
func (f *fakeServices) start(t *testing.T) *httptest.Server {
|
|
t.Helper()
|
|
reply := func(w http.ResponseWriter, s string) { _, _ = io.WriteString(w, s) }
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /gh/user", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Authorization") != "Bearer good" {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
reply(w, `{"login":"me"}`)
|
|
})
|
|
mux.HandleFunc("GET /gh/repos/acme/secret/issues/1", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Authorization") != "Bearer good" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
reply(w, `{"title":"Hidden","state":"open","user":{"login":"x"}}`)
|
|
})
|
|
mux.HandleFunc("POST /slack/auth.test", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Authorization") != "Bearer xoxb-good" {
|
|
reply(w, `{"ok":false,"error":"invalid_auth"}`)
|
|
return
|
|
}
|
|
reply(w, `{"ok":true,"team_id":"T1","team":"Acme"}`)
|
|
})
|
|
mux.HandleFunc("GET /slack/conversations.list", func(w http.ResponseWriter, r *http.Request) {
|
|
reply(w, `{"ok":true,"channels":[{"id":"C0RANDOM1","name":"random"},{"id":"C0DOCS001","name":"docs"}]}`)
|
|
})
|
|
mux.HandleFunc("GET /slack/users.info", func(w http.ResponseWriter, r *http.Request) {
|
|
email := map[string]string{"U1": "ann@x.test", "U2": "stranger@x.test"}[r.URL.Query().Get("user")]
|
|
reply(w, `{"ok":true,"user":{"profile":{"email":"`+email+`"}}}`)
|
|
})
|
|
record := func(method string) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var body map[string]any
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
body["method"] = method
|
|
f.mu.Lock()
|
|
f.posts = append(f.posts, body)
|
|
f.mu.Unlock()
|
|
reply(w, `{"ok":true}`)
|
|
}
|
|
}
|
|
mux.HandleFunc("POST /slack/chat.postMessage", record("chat.postMessage"))
|
|
mux.HandleFunc("POST /slack/chat.unfurl", record("chat.unfurl"))
|
|
srv := httptest.NewServer(mux)
|
|
t.Cleanup(srv.Close)
|
|
return srv
|
|
}
|
|
|
|
func (f *fakeServices) sent() []map[string]any {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return append([]map[string]any(nil), f.posts...)
|
|
}
|
|
|
|
// onlyTo keeps link previews off the network.
|
|
type onlyTo struct{ host string }
|
|
|
|
func (o onlyTo) RoundTrip(r *http.Request) (*http.Response, error) {
|
|
if r.URL.Host != o.host {
|
|
return nil, errors.New("blocked in tests")
|
|
}
|
|
return http.DefaultTransport.RoundTrip(r)
|
|
}
|
|
|
|
var (
|
|
admin = access.Caller{ID: "admin00000000001"}
|
|
member = access.Caller{ID: "member0000000001"}
|
|
)
|
|
|
|
func setup(t *testing.T) (*Service, *fakeDir, *fakeServices) {
|
|
t.Helper()
|
|
fs := &fakeServices{}
|
|
srv := fs.start(t)
|
|
host, _ := url.Parse(srv.URL)
|
|
dir := &fakeDir{
|
|
roles: map[string]string{admin.ID: access.WorkspaceAdmin, member.ID: access.WorkspaceMember},
|
|
pages: map[string]directory.ChatPage{
|
|
"page00000000001": {ID: "page00000000001", Workspace: ws, Title: "Roadmap", Icon: "🗺️", SpaceName: "Product",
|
|
URL: "https://docs.test/p/page00000000001", Excerpt: "What we build next"},
|
|
},
|
|
people: map[string]string{"ann@x.test": member.ID},
|
|
hits: []directory.SearchHit{{Hit: search.Hit{ID: "page00000000001", Title: "Roadmap", Snippet: "What we <b>build</b>"}, SpaceName: "Product"}},
|
|
}
|
|
apis := unfurl.APIs{GitHub: srv.URL + "/gh", Linear: srv.URL + "/linear", Figma: srv.URL + "/figma", FigmaWeb: srv.URL + "/figweb"}
|
|
previews := unfurl.NewWithClient(&http.Client{Transport: onlyTo{host: host.Host}})
|
|
s := New(fakePB(t), dir, previews, Options{Secret: "s3cret", WebURL: "https://docs.test", APIs: &apis, SlackAPI: srv.URL + "/slack"})
|
|
return s, dir, fs
|
|
}
|
|
|
|
func ptr[T any](v T) *T { return &v }
|
|
|
|
func isKind(err error, k apperr.Kind) bool {
|
|
e, ok := apperr.As(err)
|
|
return ok && e.Kind == k
|
|
}
|
|
|
|
// ---- Tests -----------------------------------------------------------------------
|
|
|
|
func TestTokensAndPreviews(t *testing.T) {
|
|
s, _, _ := setup(t)
|
|
ctx := context.Background()
|
|
if _, err := s.SetToken(ctx, member, ws, GitHub, "good"); !isKind(err, apperr.KindForbidden) {
|
|
t.Fatalf("a member set a token: %v", err)
|
|
}
|
|
if _, err := s.SetToken(ctx, admin, ws, GitHub, "bad"); err == nil {
|
|
t.Fatal("a bad token was stored")
|
|
}
|
|
v, err := s.SetToken(ctx, admin, ws, GitHub, "good")
|
|
if err != nil || !v.GitHub.Set || v.Linear.Set {
|
|
t.Fatalf("view %+v, %v", v, err)
|
|
}
|
|
// Members' previews use the workspace's token; without a workspace, none.
|
|
p, err := s.Preview(ctx, member, ws, "https://github.com/acme/secret/issues/1")
|
|
if err != nil || p.Kind != unfurl.KindGitHubIssue || p.Title != "Hidden" {
|
|
t.Fatalf("with token: %+v, %v", p, err)
|
|
}
|
|
if p, _ := s.Preview(ctx, member, "", "https://github.com/acme/secret/issues/1"); p.Kind != "" {
|
|
t.Fatalf("without workspace: %+v", p)
|
|
}
|
|
if _, err := s.Preview(ctx, access.Caller{ID: "outsider0000001"}, ws, "https://github.com/acme/secret/issues/1"); err == nil {
|
|
t.Fatal("an outsider used the workspace's tokens")
|
|
}
|
|
if v, _ := s.SetToken(ctx, admin, ws, GitHub, ""); v.GitHub.Set {
|
|
t.Fatal("the token was not removed")
|
|
}
|
|
}
|
|
|
|
func connect(t *testing.T, s *Service) {
|
|
t.Helper()
|
|
ctx := context.Background()
|
|
if _, err := s.SetSlack(ctx, admin, ws, SlackInput{BotToken: ptr("xoxb-bad")}); err == nil {
|
|
t.Fatal("a rejected bot token was stored")
|
|
}
|
|
v, err := s.SetSlack(ctx, admin, ws, SlackInput{BotToken: ptr("xoxb-good"), SigningSecret: ptr("0123456789abcdef0123"), Channel: ptr("#Docs")})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !v.Slack.Connected || v.Slack.Team != "T1" || v.Slack.Channel != "C0DOCS001" || v.Slack.ChannelName != "docs" || !v.Slack.Unfurl || !v.Slack.Search {
|
|
t.Fatalf("slack %+v", v.Slack)
|
|
}
|
|
if !strings.Contains(v.Slack.Manifest, "https://docs.test/api/v1/slack/"+ws+"/commands") || !strings.Contains(v.Slack.Manifest, `"docs.test"`) {
|
|
t.Fatalf("manifest %s", v.Slack.Manifest)
|
|
}
|
|
}
|
|
|
|
func TestSlackPosts(t *testing.T) {
|
|
s, _, fs := setup(t)
|
|
connect(t, s)
|
|
page := map[string]any{"page": map[string]any{"id": "page00000000001"}, "actor": map[string]any{"name": "Ann <a>"}}
|
|
s.Listen(webhooks.Payload{Event: "page.created", Workspace: ws, Data: page})
|
|
// Not open to every member: never posted.
|
|
s.Listen(webhooks.Payload{Event: "page.created", Workspace: ws, Data: map[string]any{"page": map[string]any{"id": "secret000000001"}}})
|
|
// Not among the chosen events (the defaults are created and commented).
|
|
s.Listen(webhooks.Payload{Event: "page.moved", Workspace: ws, Data: page})
|
|
s.Listen(webhooks.Payload{Event: "comment.created", Workspace: ws, Data: map[string]any{
|
|
"page": map[string]any{"id": "page00000000001"}, "actor": map[string]any{"name": "Bo"},
|
|
"comment": map[string]any{"body": `{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Looks good"}]}]}`},
|
|
}})
|
|
posts := fs.sent()
|
|
if len(posts) != 2 {
|
|
t.Fatalf("posts %v", posts)
|
|
}
|
|
if got := posts[0]["text"]; got != "*Ann <a>* created <https://docs.test/p/page00000000001|🗺️ Roadmap> in _Product_" || posts[0]["channel"] != "C0DOCS001" {
|
|
t.Errorf("first post %v", posts[0])
|
|
}
|
|
if got := posts[1]["text"].(string); !strings.HasSuffix(got, "\n>Looks good") || !strings.HasPrefix(got, "*Bo* commented on") {
|
|
t.Errorf("comment post %q", got)
|
|
}
|
|
|
|
// Edits are posted once in a while, not on every save.
|
|
if _, err := s.SetSlack(context.Background(), admin, ws, SlackInput{Events: ptr([]string{"page.updated"})}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s.Listen(webhooks.Payload{Event: "page.updated", Workspace: ws, Data: page})
|
|
s.Listen(webhooks.Payload{Event: "page.updated", Workspace: ws, Data: page})
|
|
if n := len(fs.sent()); n != 3 {
|
|
t.Fatalf("after two edits: %d posts", n)
|
|
}
|
|
}
|
|
|
|
func slackRequest(t *testing.T, path, contentType, body, secret string, at time.Time) *http.Request {
|
|
t.Helper()
|
|
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
|
r.Header.Set("Content-Type", contentType)
|
|
ts := strconv.FormatInt(at.Unix(), 10)
|
|
mac := hmac.New(sha256.New, []byte(secret))
|
|
mac.Write([]byte("v0:" + ts + ":" + body))
|
|
r.Header.Set("X-Slack-Request-Timestamp", ts)
|
|
r.Header.Set("X-Slack-Signature", "v0="+hex.EncodeToString(mac.Sum(nil)))
|
|
return r
|
|
}
|
|
|
|
func TestSlackEvents(t *testing.T) {
|
|
s, _, fs := setup(t)
|
|
connect(t, s)
|
|
const secret = "0123456789abcdef0123"
|
|
|
|
w := httptest.NewRecorder()
|
|
s.Events(w, slackRequest(t, "/", "application/json", `{"type":"url_verification","challenge":"abc"}`, "wrong", time.Now()), ws)
|
|
if w.Code != http.StatusUnauthorized {
|
|
t.Fatalf("bad signature: %d", w.Code)
|
|
}
|
|
w = httptest.NewRecorder()
|
|
s.Events(w, slackRequest(t, "/", "application/json", `{"type":"url_verification","challenge":"abc"}`, secret, time.Now().Add(-10*time.Minute)), ws)
|
|
if w.Code != http.StatusUnauthorized {
|
|
t.Fatalf("old request: %d", w.Code)
|
|
}
|
|
w = httptest.NewRecorder()
|
|
s.Events(w, slackRequest(t, "/", "application/json", `{"type":"url_verification","challenge":"abc"}`, secret, time.Now()), ws)
|
|
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"challenge":"abc"`) {
|
|
t.Fatalf("challenge: %d %s", w.Code, w.Body)
|
|
}
|
|
|
|
event := `{"type":"event_callback","team_id":"T1","event":{"type":"link_shared","channel":"C9","message_ts":"1.2",
|
|
"links":[{"url":"https://docs.test/p/page00000000001"},{"url":"https://docs.test/p/secret000000001"},{"url":"https://other.test/p/page00000000001"}]}}`
|
|
w = httptest.NewRecorder()
|
|
s.Events(w, slackRequest(t, "/", "application/json", event, secret, time.Now()), ws)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("event: %d", w.Code)
|
|
}
|
|
var unfurl map[string]any
|
|
for range 100 {
|
|
for _, p := range fs.sent() {
|
|
if p["method"] == "chat.unfurl" {
|
|
unfurl = p
|
|
}
|
|
}
|
|
if unfurl != nil {
|
|
break
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
if unfurl == nil || unfurl["channel"] != "C9" || unfurl["ts"] != "1.2" {
|
|
t.Fatalf("unfurl %v", unfurl)
|
|
}
|
|
links := unfurl["unfurls"].(map[string]any)
|
|
if len(links) != 1 {
|
|
t.Fatalf("unfurled %v", links)
|
|
}
|
|
card := links["https://docs.test/p/page00000000001"].(map[string]any)
|
|
if card["title"] != "🗺️ Roadmap" || card["text"] != "What we build next" || card["footer"] != "Docwell · Product" {
|
|
t.Errorf("card %v", card)
|
|
}
|
|
}
|
|
|
|
func TestSlackCommands(t *testing.T) {
|
|
s, dir, _ := setup(t)
|
|
connect(t, s)
|
|
const secret = "0123456789abcdef0123"
|
|
run := func(form url.Values) string {
|
|
w := httptest.NewRecorder()
|
|
s.Commands(w, slackRequest(t, "/", "application/x-www-form-urlencoded", form.Encode(), secret, time.Now()), ws)
|
|
var out struct {
|
|
Type string `json:"response_type"`
|
|
Text string `json:"text"`
|
|
}
|
|
_ = json.Unmarshal(w.Body.Bytes(), &out)
|
|
if out.Type != "ephemeral" {
|
|
t.Fatalf("answer %d %s", w.Code, w.Body)
|
|
}
|
|
return out.Text
|
|
}
|
|
got := run(url.Values{"team_id": {"T1"}, "user_id": {"U1"}, "text": {"road map"}})
|
|
want := "Docwell pages for “road map”:\n• <https://docs.test/p/page00000000001|Roadmap> — _Product_\n What we <b>build</b>\n<https://docs.test/search?q=road+map|All 9 results in Docwell>"
|
|
if got != want {
|
|
t.Errorf("search answer:\n%s\nwant\n%s", got, want)
|
|
}
|
|
if dir.asked != member {
|
|
t.Errorf("searched as %+v", dir.asked)
|
|
}
|
|
if got := run(url.Values{"team_id": {"T1"}, "user_id": {"U2"}, "text": {"x"}}); !strings.Contains(got, "not a member") {
|
|
t.Errorf("stranger: %q", got)
|
|
}
|
|
if got := run(url.Values{"team_id": {"T1"}, "user_id": {"U1"}, "text": {"nothing"}}); !strings.HasPrefix(got, "Nothing in Docwell") {
|
|
t.Errorf("no hits: %q", got)
|
|
}
|
|
if _, err := s.SetSlack(context.Background(), admin, ws, SlackInput{Search: ptr(false)}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := run(url.Values{"team_id": {"T1"}, "user_id": {"U1"}, "text": {"x"}}); !strings.Contains(got, "turned off") {
|
|
t.Errorf("search off: %q", got)
|
|
}
|
|
}
|