package mapatest import ( "context" "io" "log/slog" "net/http" "net/url" "path/filepath" "strings" "testing" "amadan.net/rastrillo/rastrillo/db" "amadan.net/oficina/mapa/internal/mapa" "amadan.net/oficina/notion.git/notion" "amadan.net/oficina/notion.git/notiontest" ) // The Notion import from the outside: real requests to the real router, // with the module's fake as Notion. Nothing here dials anything else. // fakeNotion is mapa.NotionAccess over a notiontest server. type fakeNotion struct{ server *notiontest.Server } func (fake fakeNotion) Verify(ctx context.Context, token string) (notion.Workspace, error) { client, err := fake.Client(token) if err != nil { return notion.Workspace{}, err } return client.Me(ctx) } func (fake fakeNotion) Client(token string) (*notion.Client, error) { return notiontest.Client(token, fake.server.URL) } func (fake fakeNotion) Files() *notion.Files { return notiontest.Files(fake.server) } // newImportRig is a rig where Ana may import, connected to a fake // serving ws. func newImportRig(t *testing.T, ws *notiontest.Workspace) (*rig, *notiontest.Server) { t.Helper() return newImportRigWith(t, ws, nil) } // newImportRigWith is newImportRig with change applied to its config // first, when there is one. func newImportRigWith(t *testing.T, ws *notiontest.Workspace, change func(*mapa.Config, string)) (*rig, *notiontest.Server) { t.Helper() dir := t.TempDir() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) database, err := db.Open(filepath.Join(dir, "mapa.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { database.Close() }) env := testEnv(Ana + "," + Bo) env["MAPA_IMPORTERS"] = Ana config, err := mapa.LoadConfig(func(key string) string { return env[key] }) if err != nil { t.Fatal(err) } if change != nil { change(&config, dir) } built, err := mapa.AppForTest(database, config, logger, Ana) if err != nil { t.Fatal(err) } server := notiontest.Start(ws, notion.APIVersion) t.Cleanup(server.Close) built.UseNotion(fakeNotion{server: server}) t.Cleanup(built.WaitImports) return &rig{built: built, db: database, dir: dir}, server } // importToken is the secret every rig connects with; I11 looks for it. const importToken = "secret_I11canaryTOKENxyz0123456789" // importAll connects as Ana, starts, and waits for the run. func (rig *rig) importAll(t *testing.T) { t.Helper() for _, action := range []struct { path string form url.Values }{{"/import/notion/connect", url.Values{"token": {importToken}}}, {"/import/notion/start", nil}} { response := rig.post(t, Ana, action.path, action.form) if response.Code != http.StatusSeeOther { t.Fatalf("%s: %d\n%s", action.path, response.Code, response.Body) } } rig.built.WaitImports() } // importRoutes are the import's routes, as the guard must answer them. var importRoutes = []string{"GET /import/notion", "POST /import/notion/connect", "POST /import/notion/start", "POST /import/notion/startover", "POST /import/notion/resume", "POST /import/notion/stop", "GET /import/notion/disconnect", "POST /import/notion/disconnect", "GET /import/notion/finish", "POST /import/notion/finish", "GET /import/notion/forget", "POST /import/notion/forget"} // I13, who sees Import (spec §7). With MAPA_IMPORTERS unset every import // route 404s for everyone; with it set, a member not named gets 404 on // every route, GET and POST, and the File menu offers it only to // importers. The account menu never does: File is its one place // (level-up build note 87). // // Mutations (make mutate, first red 2026-11-17): importerOnly lets every // member through; File offers Import to every member (2026-11-22). func TestI13OnlyImportersSeeImport(t *testing.T) { plain := newRig(t) imports, _ := newImportRig(t, notiontest.NewWorkspace("empty")) for _, route := range importRoutes { method, path, _ := strings.Cut(route, " ") for _, check := range []struct { rig *rig who string want int }{{plain, Ana, 404}, {plain, Bo, 404}, {imports, Bo, 404}} { response := check.rig.send(check.who, method, path, nil) if response.StatusCode != check.want { t.Errorf("%s as %s: %d, want %d", route, check.who, response.StatusCode, check.want) } } } for _, at := range []string{"/", "/pages", "/deleted"} { page := imports.page(t, Ana, at) if !strings.Contains(fileMenuOf(page), importPathHref+`>Import from Notion…<`) { t.Errorf("%s: an importer's File menu does not offer Import", at) } if strings.Contains(between(page, "
"), importPathHref) { t.Errorf("%s: the account menu offers Import too", at) } for _, rig := range []*rig{plain, imports} { if strings.Contains(rig.page(t, Bo, at), importPathHref) { t.Errorf("%s: a member who may not import is offered it", at) } } } } // fileMenuOf is the File menu's markup on page. func fileMenuOf(page string) string { return between(page, `id="mapa-menu-file"`, "
") } const importPathHref = `href="/import/notion"` // canaryWorkspace is a workspace whose every title, text, file name and // name is a canary, with the canaries' ids beside it. func canaryWorkspace() (*notiontest.Workspace, []string) { ws := notiontest.NewWorkspace("canaries") ws.Me["bot"].(map[string]any)["workspace_name"] = "Workspacecanary" root := ws.Page("", notiontest.Text("Zebracanary")) child := ws.Page(root, notiontest.Text("Okapicanary")) ws.Add(root, notiontest.Para(notiontest.Text("quokkacanary words "), notiontest.PageMention(child, "Okapicanary")), notiontest.Image(ws.Host("filecanary.png", []byte("x")))) ws.Add(child, notiontest.Rich("toggle", notiontest.Text("nilgaicanary"))) canaries := []string{"Zebracanary", "Okapicanary", "quokkacanary", "nilgaicanary", "filecanary", "Workspacecanary", importToken} for _, id := range []string{root, child} { canaries = append(canaries, id, strings.ReplaceAll(id, "-", "")) } return ws, canaries } // I9, plaintext (spec §15). The new tables' columns are §15's (the // schema half is TestPlaintextColumnsAreExactlySection4). The file half: // a full import over canary titles, bodies, a canary token and canary // Notion ids, run twice, then every byte on disk read, WAL included. // // Mutation (make mutate, first red 2026-11-17): the staged tree written // unsealed. func TestI9NoNotionPlaintextReachesTheDisk(t *testing.T) { ws, canaries := canaryWorkspace() rig, _ := newImportRig(t, ws) rig.importAll(t) if response := rig.post(t, Ana, "/import/notion/start", nil); response.Code != http.StatusSeeOther { t.Fatalf("second run: %d", response.Code) } rig.built.WaitImports() if rig.count(t, "pages") != 2 { t.Fatalf("%d pages imported", rig.count(t, "pages")) } if err := rig.db.Close(); err != nil { t.Fatal(err) } for _, hit := range scan(t, rig.dir, canaries) { t.Errorf("plaintext on disk: %s", hit) } } // I11, the token is never rendered (memoria N14): no 8-character run of // it in any response, after connecting, running, a refused token and // every confirm page. // // Mutation (make mutate, first red 2026-11-17): the connection form // shows the token's last four characters as a mask. func TestI11TheTokenIsNeverRendered(t *testing.T) { ws, _ := canaryWorkspace() rig, server := newImportRig(t, ws) rig.importAll(t) var bodies []string for _, path := range []string{"/import/notion", "/import/notion/finish", "/import/notion/disconnect", "/import/notion/forget", "/"} { bodies = append(bodies, rig.page(t, Ana, path)) } server.Lock() server.Workspace.Me["id"] = "" server.Unlock() refused := rig.post(t, Ana, "/import/notion/connect", url.Values{"token": {importToken}}) bodies = append(bodies, refused.Body.String()) for _, body := range bodies { for start := 0; start+8 <= len(importToken); start++ { if strings.Contains(body, importToken[start:start+8]) { t.Fatalf("a response holds %q of the token", importToken[start:start+8]) } } } if !strings.Contains(bodies[0], "Connected to") { t.Error("the import page does not say it is connected") } }