* fix(notion): keep notion.token out of the Dolt database (#6676) notion.token was missing from YamlOnlyKeys, so `bd config set notion.token` (the command `bd notion status` recommends) wrote the token to the Dolt config table, whose contents `bd dolt push` sends to the remote. The git-tracked-config guard never fired for it either, because checkSecretGitTracked only considers yaml-only keys. - Add notion.token to YamlOnlyKeys, next to github.token, gitlab.token, jira.api_token and ado.pat, so `bd config set` writes it to config.yaml and refuses a git-tracked config.yaml. - Map notion.token to NOTION_TOKEN in secretKeyEnvVarHints so that refusal suggests the variable bd actually reads, not BD_NOTION_TOKEN. - notion.ResolveAuth now reads config.yaml first, then the database, then NOTION_TOKEN. The database read is kept only so a token stored by an older bd keeps authenticating after an upgrade. - resolveNotionAuth's no-store fallback goes through ResolveAuth, so a config.yaml token is found even when no store is open. - The proxied `bd serve` settings integration test used notion.token as its credential-bearing key and read it back with `bd config get`, which now reads config.yaml; it uses notes.api_token instead. - The DB-backed-secret guard test used notion.token as its example of a non-yaml secret key; it uses custom.api_token instead. - Docs list notion.token with the other yaml-only secrets, and the quickstart leads with NOTION_TOKEN because `bd init` in a git repo leaves config.yaml tracked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(config,notion): delete leaked secret rows on unset; name the legacy auth source Maintainer review fixes for #6724 (GH#6676). Finding 1 (major, PR-introduced): moving notion.token into YamlOnlyKeys made `bd config unset notion.token` return before the store, so a workspace that had already leaked the token into the pushed config table lost its only bd-side remover — exactly the population the PR exists to protect. configUnsetCmd now best-effort deletes the database row for yaml-only SECRET keys and reports which copies it removed. It is keyed on IsYamlOnlyKey+IsSecretKey rather than on notion.token, so it closes the gap for the whole class; measured, that is at least ado.pat, github.token, gitlab.token, jira.api_token, linear.api_key, linear.oauth_client_secret and notion.token, plus whatever the prefix rules (`ai.`, `sync.`, `federation.`, ...) admit. Non-secret yaml-only keys are gated out before the store is opened, so an ordinary `bd config unset routing.mode` still costs no database open. It reads before deleting because DeleteConfig reports no miss, so the common never-leaked workspace stays silent instead of announcing a removal that did not happen. Finding 2 (major, pre-existing class): internal/notion/auth.go asserted "It must never be written to the database" as an unqualified invariant while PUT /v0/beads/config/notion.token still writes that row with no refusal. Scoped the comment to the CLI door and named the HTTP/dashboard door as the known remaining hole. Closing that door is deliberately NOT attempted here: it is a cross-tracker change at workapi.ValidateSettingWrite/SetSetting on a pre-existing surface, and belongs where every tracker credential gets the rule at once. Finding 3 (minor): the config.yaml token and the legacy row both reported `config_token`, collapsing the safe case with the leaked one. Added AuthSourceDatabaseLegacy plus a `bd notion status` rotation warning — the only signal that gives the CHANGELOG's rotation advice an addressee. Finding 4 (minor): pinned the end-to-end shape `bd config set` actually writes. The finding cited internal/config/config.go:653 (setNestedKey), which is SaveConfigValue's writer and not on this path — SetYamlConfig routes through updateYamlKey/updateNestedYamlKey — but its conclusion held: the written shape is nested. The new test drives the real writer rather than a second fixture, and both its assertions were proven live by mutation (breaking the config.yaml read trips the round-trip; forcing the flat fallback trips the non-vacuity guard, while the round-trip alone still passed, which is why that guard exists). Finding 5 (nit): both "not configured" errors led with `bd config set notion.token`, which the new git-tracked refusal rejects in the default post-`bd init` layout. They now lead with `export NOTION_TOKEN`, matching the quickstart's ordering. Also corrected the CHANGELOG, which still claimed unset clears config.yaml only. Validation: ./internal/notion and ./internal/config green under `env -u BEADS_DIR`. The cmd/bd notion/config tests are green except TestConfigValidateReadOnlyIsHermetic and TestGetNotionConfigReadsDBPathWhenStoreUnset, which fail identically at the PR head with these fixes stashed (A/B in this same worktree) — ambient, not introduced here. --- Iteration 2 review fixes (one major, three minors, one nit) --- Finding 1 (major, introduced by the iteration-1 fixup above): the cleanup reached the store through openWorkspaceConfig -> ensureDirectMode -> ensureStoreActive, which is open-OR-CREATE. So `bd config unset <yaml-only secret>` in a workspace holding only .beads/config.yaml created a 2.1 MB embedded Dolt database and flipped it out of db-less mode for every later command -- from a command whose contract is "edit a YAML file", silently and with exit 0. It also contradicted configCommandCanRunWithoutStore, which classifies this exact invocation as runnable with no store precisely when beads.FindDatabasePath() is empty. unsetLeakedSecretRow now returns early rather than reach an open-OR-CREATE store in a workspace that has no database to reach. The proxied route is exempt rather than gated -- proxiedWorkspaceConfig reaches an already-connected provider and creates nothing, and a server-mode workspace legitimately has no local database directory for FindDatabasePath to find, so gating it on the local path would silently disable the cleanup exactly where the row is most replicated. Iteration 3 finishes that thought: the same is true of the DIRECT server-mode route, which this gate still skipped. Finding 2 (minor): the remover ran only if the YAML unset succeeded first, which skipped it for the population it exists for -- no config.yaml, or a shape UnsetYamlConfig refuses. Base deleted the row there and the fixup did not, while `bd notion status` names this very command as the remover. The cleanup now runs either way, and a failed YAML unset carries the row's fate in its error instead of telling the user to run `bd init` while a credential sits in the pushed table. Finding 3 (minor): a failed DELETE of a row the read had found was rendered as "Could not check the database ..." under a JSON key asserting unreachability -- the one outcome that is certain, reported as the inconclusive one. removeStoredSecretRow now returns the found bit alongside the error, and the delete-failure case gets its own message and its own JSON keys (database_row_present / database_delete_failed), carrying the rotation warning. Finding 4 (minor): nothing pinned the command -> cleanup wiring; deleting the call left every test green. The yaml-only branch is now runConfigUnsetYamlOnly and four new tests drive configUnsetCmd itself against a recording settings surface: the row is read, deleted and reported; a non-secret yaml-only key touches the config plane zero times; --json carries the new keys; and .beads/ is byte-unchanged (config.yaml aside) after unsetting a secret with no database present. Finding 5 (nit): CHANGELOG and docs/reference/configuration.md described the dual removal unconditionally. Both now say the database half is best effort and name the cases where it is skipped or refused. Every new pin proven by mutation, one at a time, each failing only with its fix removed: dropping the FindDatabasePath gate takes the no-database test into embeddeddolt.OpenSQL (it really does provision); re-gating the cleanup behind the YAML unset leaves the row undeleted and unmentioned; replacing the command's cleanup call with a zero value drops the report and the --json field; returning false for `present` on a failed delete puts database_unreachable back. Complexity ledger flat by construction: worst_changed stays showConfigYAMLOverrides at cyclomatic 17 / cognitive 29, which this PR does not touch and which measures identically at the base blob. The extracted runConfigUnsetYamlOnly is 6/9 and the three report helpers are at most 5/2. Iteration 2 validation: ./internal/notion and ./internal/config green under `env -u BEADS_DIR`; all nine cmd/bd leaked-secret/notion-auth tests green, one -run per invocation (a batched regex shares rootCmd and produces false reds); the CGO_ENABLED=0 gms_pure_go cmd/bd test binary still compiles (the new test file is untagged, so it carries its own tree-snapshot helper rather than the cgo-tagged twin); scripts/check-doc-flags.sh and `go test -tags=gms_pure_go ./test/docsync` pass for the docs edit. --- Iteration 3 review fixes (two minors, both on the gate itself) --- Finding 1 (minor, introduced by the iteration-2 gate above): "not proxied and no local database directory" over-fires. findDatabaseInBeadsDir answers on metadata.json plus embeddeddolt/ and dolt/, and it skips the stat for server mode only when metadata.json is present -- so a metadata-less server workspace, whose host comes from config.yaml or BEADS_DOLT_SERVER_HOST (main.go, GH#3545, the shape gc provisions on every `gc-beads-bd start`), reports "" while its row sits on the shared server, replicated to every remote it pushed to. The skip was not buying anything there either: PersistentPreRun has already CONNECTED that workspace's store, and ensureStoreActive early-returns on an active store without opening or creating anything. For notion.token this was a narrow regression of a base capability -- at base that key was not yaml-only, so `bd config unset notion.token` took the database branch and deleted the row. The seven pre-existing yaml-only secrets never had a remover at base, so for them the skip withheld only new coverage, which is what holds this at minor. The gate is now mayProvisionDatabase, which asks about the store before the disk; each arm that returns false is a route where the database is already open -- proxied, or a store already active and tracked, which is provably non-provisioning because it is ensureStoreActive's own no-op arm. Finding 2 (minor): neither arm of that gate had a behavioral test. Deleting the !usesProxiedServer() clause left all four command-level tests green, and it is the only thing keeping the cleanup alive for proxied workspaces, which have no local database directory by construction -- the clause a later simplification is most likely to read as redundant was the one clause nothing defended. TestConfigUnsetCleansTheRowWithNoLocalDatabaseDirectory now pins both arms as the mirror of TestConfigUnsetDoesNotProvisionADatabase: "no local database directory" is the state all three share, so the route to the database is the only thing that distinguishes them. Both arms mutation-proved, one at a time, each red on exactly one subtest while the four pre-existing command-level tests stayed green under both mutations: deleting the active-store arm reproduces the finding verbatim (GetSetting calls = [], UnsetSetting calls = [] for a connected server workspace, exit 0); deleting the !usesProxiedServer() arm leaves the proxied workspace's row never looked for. That second half -- the pre-existing suite staying green -- is the claim Finding 2 rests on, and only a run under the mutation can state it. The CHANGELOG's "skipped where there is no database to hold a row" and the matching sentence in docs/reference/configuration.md asserted exactly what the gate got wrong; both now say it is skipped only where reaching the row would mean creating a database, and that a server-mode or proxied workspace whose database is simply not on local disk still gets the cleanup. Complexity ledger still flat: worst_changed stays showConfigYAMLOverrides at cyclomatic 17 / cognitive 29 (untouched, identical at the base blob), and extracting the gate took unsetLeakedSecretRow from 6/5 to 5/4 with mayProvisionDatabase at 4/3. Iteration 3 validation: gofmt clean, `go build ./cmd/bd/`, `go vet ./cmd/bd/` and `git diff --check` clean; the six leaked-secret/notion-auth tests and the four command-level tests all green against the real fix, one -run per invocation under a private TMPDIR (a batched regex shares rootCmd and produces false reds; a sibling suite's sweep deletes shared temp roots mid-run); the CGO_ENABLED=0 gms_pure_go cmd/bd test binary still compiles; scripts/check-doc-flags.sh, scripts/check-doc-freshness.sh and `go test -tags=gms_pure_go ./test/docsync` pass for the docs edit (no new links, anchors or headings, so the render check does not apply). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
717 lines
24 KiB
Go
717 lines
24 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/internal/config"
|
|
"github.com/steveyegge/beads/internal/notion"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/tracker"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
type notionConfigOperation struct {
|
|
key string
|
|
value string
|
|
err error
|
|
}
|
|
|
|
type notionConfigCall struct {
|
|
key string
|
|
value string
|
|
}
|
|
|
|
// notionConfigRecorder scripts the config operations a test expects. Writes
|
|
// are recorded independently and never become values that later reads return.
|
|
type notionConfigRecorder struct {
|
|
reads []notionConfigOperation
|
|
sets []notionConfigOperation
|
|
deletes []notionConfigOperation
|
|
|
|
readCalls []notionConfigCall
|
|
setCalls []notionConfigCall
|
|
deleteCalls []notionConfigCall
|
|
}
|
|
|
|
// notionConfigDoltStore is the production-adapter shell for these tests. Its
|
|
// nil embedded store makes any operation outside config read/set/delete panic.
|
|
type notionConfigDoltStore struct {
|
|
storage.DoltStorage
|
|
recorder *notionConfigRecorder
|
|
}
|
|
|
|
func (s *notionConfigDoltStore) GetConfig(ctx context.Context, key string) (string, error) {
|
|
return s.recorder.GetConfig(ctx, key)
|
|
}
|
|
|
|
func (s *notionConfigDoltStore) SetConfig(ctx context.Context, key, value string) error {
|
|
return s.recorder.SetConfig(ctx, key, value)
|
|
}
|
|
|
|
func (s *notionConfigDoltStore) DeleteConfig(ctx context.Context, key string) error {
|
|
return s.recorder.DeleteConfig(ctx, key)
|
|
}
|
|
|
|
func (r *notionConfigRecorder) GetConfig(_ context.Context, key string) (string, error) {
|
|
r.readCalls = append(r.readCalls, notionConfigCall{key: key})
|
|
if len(r.reads) == 0 {
|
|
return "", errors.New("unexpected config read")
|
|
}
|
|
op := r.reads[0]
|
|
r.reads = r.reads[1:]
|
|
if op.key != key {
|
|
return "", errors.New("unexpected config read key")
|
|
}
|
|
return op.value, op.err
|
|
}
|
|
|
|
func (r *notionConfigRecorder) SetConfig(_ context.Context, key, value string) error {
|
|
r.setCalls = append(r.setCalls, notionConfigCall{key: key, value: value})
|
|
if len(r.sets) == 0 {
|
|
return errors.New("unexpected config set")
|
|
}
|
|
op := r.sets[0]
|
|
r.sets = r.sets[1:]
|
|
if op.key != key || op.value != value {
|
|
return errors.New("unexpected config set values")
|
|
}
|
|
return op.err
|
|
}
|
|
|
|
func (r *notionConfigRecorder) DeleteConfig(_ context.Context, key string) error {
|
|
r.deleteCalls = append(r.deleteCalls, notionConfigCall{key: key})
|
|
if len(r.deletes) == 0 {
|
|
return errors.New("unexpected config delete")
|
|
}
|
|
op := r.deletes[0]
|
|
r.deletes = r.deletes[1:]
|
|
if op.key != key {
|
|
return errors.New("unexpected config delete key")
|
|
}
|
|
return op.err
|
|
}
|
|
|
|
func (r *notionConfigRecorder) assertConsumed(t *testing.T) {
|
|
t.Helper()
|
|
if len(r.reads) != 0 || len(r.sets) != 0 || len(r.deletes) != 0 {
|
|
t.Fatalf("unconsumed config script: reads=%+v sets=%+v deletes=%+v", r.reads, r.sets, r.deletes)
|
|
}
|
|
}
|
|
|
|
func installNotionRecorderStore(t *testing.T, recorder *notionConfigRecorder, decorated bool) *notionConfigDoltStore {
|
|
t.Helper()
|
|
saveAndRestoreGlobals(t)
|
|
raw := ¬ionConfigDoltStore{recorder: recorder}
|
|
if decorated {
|
|
store = storage.NewHookFiringStore(raw, nil)
|
|
} else {
|
|
store = raw
|
|
}
|
|
setStoreActive(true)
|
|
return raw
|
|
}
|
|
|
|
func assertNotionConfigCalls(t *testing.T, recorder *notionConfigRecorder, reads, sets, deletes []notionConfigCall) {
|
|
t.Helper()
|
|
if !reflect.DeepEqual(recorder.readCalls, reads) || !reflect.DeepEqual(recorder.setCalls, sets) || !reflect.DeepEqual(recorder.deleteCalls, deletes) {
|
|
t.Fatalf("calls = reads:%+v sets:%+v deletes:%+v, want reads:%+v sets:%+v deletes:%+v", recorder.readCalls, recorder.setCalls, recorder.deleteCalls, reads, sets, deletes)
|
|
}
|
|
recorder.assertConsumed(t)
|
|
}
|
|
|
|
func TestNotionCommandsRegistered(t *testing.T) {
|
|
// Not parallel: Find mutates Cobra flag state on the global command tree.
|
|
|
|
for _, name := range []string{"init", "connect", "status", "sync"} {
|
|
if _, _, err := notionCmd.Find([]string{name}); err != nil {
|
|
t.Fatalf("missing subcommand %q: %v", name, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestGetNotionConfigPrefersStoreOverEnv(t *testing.T) {
|
|
recorder := ¬ionConfigRecorder{reads: []notionConfigOperation{
|
|
{key: "notion.data_source_id", value: "store-ds"},
|
|
{key: "notion.view_url", value: "https://store/view"},
|
|
}}
|
|
installNotionRecorderStore(t, recorder, false)
|
|
|
|
t.Setenv("NOTION_TOKEN", "env-token")
|
|
t.Setenv("NOTION_DATA_SOURCE_ID", "env-ds")
|
|
t.Setenv("NOTION_VIEW_URL", "https://env/view")
|
|
|
|
cfg := getNotionConfig()
|
|
if cfg.DataSourceID != "store-ds" || cfg.ViewURL != "https://store/view" {
|
|
t.Fatalf("config = %+v", cfg)
|
|
}
|
|
assertNotionConfigCalls(t, recorder,
|
|
[]notionConfigCall{{key: "notion.data_source_id"}, {key: "notion.view_url"}}, nil, nil)
|
|
}
|
|
|
|
func TestRunNotionStatusJSONWithMissingConfig(t *testing.T) {
|
|
saveAndRestoreGlobals(t)
|
|
pinJSONOutput(t, true)
|
|
store = nil
|
|
dbPath = ""
|
|
t.Setenv("NOTION_TOKEN", "")
|
|
t.Setenv("NOTION_DATA_SOURCE_ID", "")
|
|
t.Setenv("NOTION_VIEW_URL", "")
|
|
|
|
cmd := &cobra.Command{}
|
|
var stdout bytes.Buffer
|
|
cmd.SetOut(&stdout)
|
|
cmd.SetContext(context.Background())
|
|
|
|
if err := runNotionStatus(cmd, nil); err != nil {
|
|
t.Fatalf("runNotionStatus returned error: %v", err)
|
|
}
|
|
|
|
var resp notion.StatusResponse
|
|
if err := json.Unmarshal(stdout.Bytes(), &resp); err != nil {
|
|
t.Fatalf("unmarshal status json: %v\n%s", err, stdout.String())
|
|
}
|
|
if resp.Configured {
|
|
t.Fatal("expected configured=false")
|
|
}
|
|
if !strings.Contains(resp.Error, "bd config set notion.token") {
|
|
t.Fatalf("error = %q", resp.Error)
|
|
}
|
|
}
|
|
|
|
func TestRunNotionInitPersistsTargetConfig(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
viewURL string
|
|
decorated bool
|
|
sets []notionConfigOperation
|
|
deletes []notionConfigOperation
|
|
wantSets []notionConfigCall
|
|
wantDelete []notionConfigCall
|
|
}{
|
|
{
|
|
name: "saves returned target",
|
|
viewURL: "https://www.notion.so/db123",
|
|
sets: []notionConfigOperation{
|
|
{key: "notion.data_source_id", value: "ds_123"},
|
|
{key: "notion.view_url", value: "https://www.notion.so/db123"},
|
|
},
|
|
wantSets: []notionConfigCall{{key: "notion.data_source_id", value: "ds_123"}, {key: "notion.view_url", value: "https://www.notion.so/db123"}},
|
|
},
|
|
{
|
|
name: "clears blank view through unwrapped decorated store",
|
|
decorated: true,
|
|
sets: []notionConfigOperation{{key: "notion.data_source_id", value: "ds_123"}},
|
|
deletes: []notionConfigOperation{{key: "notion.view_url"}},
|
|
wantSets: []notionConfigCall{{key: "notion.data_source_id", value: "ds_123"}},
|
|
wantDelete: []notionConfigCall{{key: "notion.view_url"}},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
recorder := ¬ionConfigRecorder{
|
|
reads: []notionConfigOperation{{key: "notion.token"}},
|
|
sets: tt.sets,
|
|
deletes: tt.deletes,
|
|
}
|
|
rawStore := installNotionRecorderStore(t, recorder, tt.decorated)
|
|
if tt.decorated && notionConfigDeleteTarget() != rawStore {
|
|
t.Fatal("notionConfigDeleteTarget did not unwrap the decorated store")
|
|
}
|
|
|
|
oldFactory := newNotionSetupClient
|
|
oldParent, oldTitle, oldJSON := notionInitParent, notionInitTitle, jsonOutput
|
|
t.Cleanup(func() {
|
|
newNotionSetupClient = oldFactory
|
|
notionInitParent, notionInitTitle, jsonOutput = oldParent, oldTitle, oldJSON
|
|
})
|
|
notionInitParent = "329e5bf9-7fae-8080-bb4a-d94e1387655d"
|
|
notionInitTitle = "Beads Issues"
|
|
jsonOutput = false
|
|
t.Setenv("NOTION_TOKEN", "env-token")
|
|
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/databases" {
|
|
t.Fatalf("unexpected path %q", r.URL.Path)
|
|
}
|
|
body, _ := io.ReadAll(r.Body)
|
|
for _, want := range []string{
|
|
`"page_id":"329e5bf9-7fae-8080-bb4a-d94e1387655d"`,
|
|
`"initial_data_source"`,
|
|
`"Beads ID"`,
|
|
`"Status"`,
|
|
} {
|
|
if !strings.Contains(string(body), want) {
|
|
t.Fatalf("request body missing %q\n%s", want, body)
|
|
}
|
|
}
|
|
_, _ = fmt.Fprintf(w, `{"id":"db_123","url":%q,"data_sources":[{"id":"ds_123","name":"Beads Issues"}]}`, tt.viewURL)
|
|
}))
|
|
defer server.Close()
|
|
newNotionSetupClient = func(token string) *notion.Client {
|
|
return notion.NewClient(token).WithBaseURL(server.URL)
|
|
}
|
|
|
|
cmd := &cobra.Command{}
|
|
var stdout bytes.Buffer
|
|
cmd.SetOut(&stdout)
|
|
cmd.SetContext(context.Background())
|
|
if err := runNotionInit(cmd, nil); err != nil {
|
|
t.Fatalf("runNotionInit returned error: %v", err)
|
|
}
|
|
if !strings.Contains(stdout.String(), "Saved data source: ds_123") {
|
|
t.Fatalf("stdout = %q", stdout.String())
|
|
}
|
|
if tt.viewURL == "" && strings.Contains(stdout.String(), "Launch URL:") {
|
|
t.Fatalf("stdout unexpectedly contains launch URL: %q", stdout.String())
|
|
}
|
|
assertNotionConfigCalls(t, recorder,
|
|
[]notionConfigCall{{key: "notion.token"}}, tt.wantSets, tt.wantDelete)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRunNotionConnectResolvesDataSourceURL(t *testing.T) {
|
|
url := "https://www.notion.so/workspace/329e5bf97fae8080bb4ad94e1387655d"
|
|
recorder := ¬ionConfigRecorder{
|
|
reads: []notionConfigOperation{{key: "notion.token"}},
|
|
sets: []notionConfigOperation{
|
|
{key: "notion.data_source_id", value: "329e5bf9-7fae-8080-bb4a-d94e1387655d"},
|
|
{key: "notion.view_url", value: url},
|
|
},
|
|
}
|
|
installNotionRecorderStore(t, recorder, false)
|
|
oldFactory := newNotionSetupClient
|
|
oldURL, oldJSON := notionConnectURL, jsonOutput
|
|
t.Cleanup(func() {
|
|
newNotionSetupClient = oldFactory
|
|
notionConnectURL, jsonOutput = oldURL, oldJSON
|
|
})
|
|
notionConnectURL = url
|
|
jsonOutput = false
|
|
t.Setenv("NOTION_TOKEN", "env-token")
|
|
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/data_sources/329e5bf9-7fae-8080-bb4a-d94e1387655d":
|
|
_, _ = io.WriteString(w, `{"id":"329e5bf9-7fae-8080-bb4a-d94e1387655d","properties":{"Name":{"type":"title"},"Beads ID":{"type":"rich_text"},"Status":{"type":"select"},"Priority":{"type":"select"},"Type":{"type":"select"},"Description":{"type":"rich_text"},"Assignee":{"type":"rich_text"},"Labels":{"type":"multi_select"}}}`)
|
|
default:
|
|
t.Fatalf("unexpected path %q", r.URL.Path)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
newNotionSetupClient = func(token string) *notion.Client {
|
|
return notion.NewClient(token).WithBaseURL(server.URL)
|
|
}
|
|
cmd := &cobra.Command{}
|
|
var stdout bytes.Buffer
|
|
cmd.SetOut(&stdout)
|
|
cmd.SetContext(context.Background())
|
|
if err := runNotionConnect(cmd, nil); err != nil {
|
|
t.Fatalf("runNotionConnect returned error: %v", err)
|
|
}
|
|
if !strings.Contains(stdout.String(), "Connected Notion data source 329e5bf9-7fae-8080-bb4a-d94e1387655d") {
|
|
t.Fatalf("stdout = %q", stdout.String())
|
|
}
|
|
assertNotionConfigCalls(t, recorder,
|
|
[]notionConfigCall{{key: "notion.token"}},
|
|
[]notionConfigCall{{key: "notion.data_source_id", value: "329e5bf9-7fae-8080-bb4a-d94e1387655d"}, {key: "notion.view_url", value: url}}, nil)
|
|
}
|
|
|
|
func TestRunNotionConnectResolvesDatabaseURL(t *testing.T) {
|
|
ctx := context.Background()
|
|
url := "https://www.notion.so/workspace/429e5bf97fae8080bb4ad94e1387655d"
|
|
recorder := ¬ionConfigRecorder{sets: []notionConfigOperation{
|
|
{key: "notion.data_source_id", value: "529e5bf9-7fae-8080-bb4a-d94e1387655d"},
|
|
{key: "notion.view_url", value: url},
|
|
}}
|
|
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/data_sources/429e5bf9-7fae-8080-bb4a-d94e1387655d":
|
|
w.WriteHeader(http.StatusNotFound)
|
|
_, _ = io.WriteString(w, `{"code":"object_not_found","message":"not found"}`)
|
|
case "/databases/429e5bf9-7fae-8080-bb4a-d94e1387655d":
|
|
_, _ = io.WriteString(w, `{"id":"429e5bf9-7fae-8080-bb4a-d94e1387655d","data_sources":[{"id":"529e5bf9-7fae-8080-bb4a-d94e1387655d","name":"Beads Issues"}]}`)
|
|
case "/data_sources/529e5bf9-7fae-8080-bb4a-d94e1387655d":
|
|
_, _ = io.WriteString(w, `{"id":"529e5bf9-7fae-8080-bb4a-d94e1387655d","properties":{"Name":{"type":"title"},"Beads ID":{"type":"rich_text"},"Status":{"type":"select"},"Priority":{"type":"select"},"Type":{"type":"select"},"Description":{"type":"rich_text"},"Assignee":{"type":"rich_text"},"Labels":{"type":"multi_select"}}}`)
|
|
default:
|
|
t.Fatalf("unexpected path %q", r.URL.Path)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
result, err := runNotionConnectAfterValidation(ctx, notion.NewClient("env-token").WithBaseURL(server.URL), url, recorder, recorder)
|
|
if err != nil {
|
|
t.Fatalf("runNotionConnectAfterValidation returned error: %v", err)
|
|
}
|
|
if result.DataSourceID != "529e5bf9-7fae-8080-bb4a-d94e1387655d" || result.DatabaseID != "429e5bf9-7fae-8080-bb4a-d94e1387655d" {
|
|
t.Fatalf("result = %+v", result)
|
|
}
|
|
recorder.assertConsumed(t)
|
|
}
|
|
|
|
func TestRunNotionStatusUsesHTTPClient(t *testing.T) {
|
|
saveAndRestoreGlobals(t)
|
|
originalFactory := newNotionStatusClient
|
|
t.Cleanup(func() { newNotionStatusClient = originalFactory })
|
|
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/users/me":
|
|
if got := r.Header.Get("Authorization"); got != "Bearer env-token" {
|
|
t.Fatalf("authorization = %q", got)
|
|
}
|
|
_, _ = io.WriteString(w, `{"id":"user-1","name":"Osamu","type":"person","person":{"email":"osamu@example.com"}}`)
|
|
case "/data_sources/ds_123":
|
|
_, _ = io.WriteString(w, `{"id":"ds_123","url":"https://www.notion.so/source","title":[{"plain_text":"Tasks"}],"properties":{"Name":{"type":"title"},"Beads ID":{"type":"rich_text"},"Status":{"type":"select"},"Priority":{"type":"select"},"Type":{"type":"select"},"Description":{"type":"rich_text"},"Assignee":{"type":"rich_text"},"Labels":{"type":"multi_select"}}}`)
|
|
default:
|
|
t.Fatalf("unexpected path %q", r.URL.Path)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
|
|
newNotionStatusClient = func(token string) *notion.Client {
|
|
return notion.NewClient(token).WithBaseURL(server.URL)
|
|
}
|
|
pinJSONOutput(t, true)
|
|
store = nil
|
|
dbPath = ""
|
|
t.Setenv("NOTION_TOKEN", "env-token")
|
|
t.Setenv("NOTION_DATA_SOURCE_ID", "ds_123")
|
|
t.Setenv("NOTION_VIEW_URL", "https://www.notion.so/view")
|
|
|
|
cmd := &cobra.Command{}
|
|
var stdout bytes.Buffer
|
|
cmd.SetOut(&stdout)
|
|
cmd.SetContext(context.Background())
|
|
|
|
if err := runNotionStatus(cmd, nil); err != nil {
|
|
t.Fatalf("runNotionStatus returned error: %v", err)
|
|
}
|
|
|
|
var resp notion.StatusResponse
|
|
if err := json.Unmarshal(stdout.Bytes(), &resp); err != nil {
|
|
t.Fatalf("unmarshal status json: %v\n%s", err, stdout.String())
|
|
}
|
|
if !resp.Ready {
|
|
t.Fatalf("expected ready response, got %+v", resp)
|
|
}
|
|
if resp.Database == nil || resp.Database.Title != "Tasks" {
|
|
t.Fatalf("database = %+v", resp.Database)
|
|
}
|
|
if resp.Auth == nil || !resp.Auth.OK || resp.Auth.User == nil || resp.Auth.User.Email != "osamu@example.com" {
|
|
t.Fatalf("auth = %+v", resp.Auth)
|
|
}
|
|
if resp.Auth.Source != "env" {
|
|
t.Fatalf("auth source = %q", resp.Auth.Source)
|
|
}
|
|
}
|
|
|
|
// TestResolveNotionAuthPrefersStoredTokenOverEnv pins the PRECEDENCE, which is
|
|
// unchanged: a token in the database still outranks NOTION_TOKEN, so a
|
|
// workspace configured before GH#6676 keeps authenticating after the upgrade.
|
|
//
|
|
// The reported SOURCE did change. Only an older bd can have put this row here,
|
|
// so it resolves as AuthSourceDatabaseLegacy rather than AuthSourceConfigToken
|
|
// — that is the signal `bd notion status` uses to tell this workspace its token
|
|
// was pushed to its remotes and needs rotating.
|
|
func TestResolveNotionAuthPrefersStoredTokenOverEnv(t *testing.T) {
|
|
recorder := ¬ionConfigRecorder{reads: []notionConfigOperation{{key: "notion.token", value: "config-token"}}}
|
|
installNotionRecorderStore(t, recorder, false)
|
|
t.Setenv("NOTION_TOKEN", "env-token")
|
|
|
|
auth, err := resolveNotionAuth(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("resolveNotionAuth returned error: %v", err)
|
|
}
|
|
if auth == nil || auth.Token != "config-token" || auth.Source != notion.AuthSourceDatabaseLegacy {
|
|
t.Fatalf("auth = %+v", auth)
|
|
}
|
|
assertNotionConfigCalls(t, recorder, []notionConfigCall{{key: "notion.token"}}, nil, nil)
|
|
}
|
|
|
|
// TestResolveNotionAuthPrefersConfigYamlOverStore pins GH#6676: notion.token
|
|
// lives in config.yaml, so a yaml token is used without consulting the
|
|
// database, where only a token written by an older bd can be found.
|
|
func TestResolveNotionAuthPrefersConfigYamlOverStore(t *testing.T) {
|
|
recorder := ¬ionConfigRecorder{}
|
|
installNotionRecorderStore(t, recorder, false)
|
|
initConfigForTest(t)
|
|
config.Set("notion.token", "yaml-token")
|
|
t.Setenv("NOTION_TOKEN", "env-token")
|
|
|
|
auth, err := resolveNotionAuth(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("resolveNotionAuth returned error: %v", err)
|
|
}
|
|
if auth == nil || auth.Token != "yaml-token" || auth.Source != notion.AuthSourceConfigToken {
|
|
t.Fatalf("auth = %+v", auth)
|
|
}
|
|
assertNotionConfigCalls(t, recorder, nil, nil, nil)
|
|
}
|
|
|
|
// TestResolveNotionAuthReadsConfigYamlWithoutStore verifies the yaml token is
|
|
// found even when no store is open and no database path is known.
|
|
func TestResolveNotionAuthReadsConfigYamlWithoutStore(t *testing.T) {
|
|
saveAndRestoreGlobals(t)
|
|
initConfigForTest(t)
|
|
store = nil
|
|
dbPath = ""
|
|
config.Set("notion.token", "yaml-token")
|
|
t.Setenv("NOTION_TOKEN", "env-token")
|
|
|
|
auth, err := resolveNotionAuth(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("resolveNotionAuth returned error: %v", err)
|
|
}
|
|
if auth == nil || auth.Token != "yaml-token" || auth.Source != notion.AuthSourceConfigToken {
|
|
t.Fatalf("auth = %+v", auth)
|
|
}
|
|
}
|
|
|
|
func TestRenderNotionSyncResultUsesPhaseStats(t *testing.T) {
|
|
saveAndRestoreGlobals(t)
|
|
notionSyncDryRun = true
|
|
t.Cleanup(func() { notionSyncDryRun = false })
|
|
|
|
cmd := &cobra.Command{}
|
|
var stdout bytes.Buffer
|
|
cmd.SetOut(&stdout)
|
|
|
|
renderNotionSyncResult(cmd, &tracker.SyncResult{
|
|
Stats: tracker.SyncStats{Pulled: 2, Pushed: 3, Conflicts: 1},
|
|
Warnings: []string{
|
|
"Skipped unsupported Notion issue types: event=2",
|
|
"Skipped bd-1: Notion external_ref points outside the current target; clear external_ref to recreate it in this data source",
|
|
"Skipped bd-2: Notion external_ref points outside the current target; clear external_ref to recreate it in this data source",
|
|
},
|
|
PullStats: tracker.PullStats{
|
|
Queried: 12,
|
|
Candidates: 2,
|
|
Created: 1,
|
|
Updated: 1,
|
|
},
|
|
PushStats: tracker.PushStats{
|
|
Created: 2,
|
|
Updated: 1,
|
|
},
|
|
})
|
|
out := stdout.String()
|
|
for _, want := range []string{
|
|
"Dry run mode",
|
|
"Queried 12 pages from Notion (2 pull candidates)",
|
|
"Pulled 2 issues (1 created, 1 updated)",
|
|
"Pushed 3 issues (2 created, 1 updated)",
|
|
"Resolved 1 conflicts",
|
|
"Skipped 2 linked issues that still point at a different Notion target. Clear external_ref to recreate them in this data source.",
|
|
} {
|
|
if !strings.Contains(out, want) {
|
|
t.Fatalf("stdout missing %q\n%s", want, out)
|
|
}
|
|
}
|
|
for _, unwanted := range []string{
|
|
"event=2",
|
|
"bd-1",
|
|
"bd-2",
|
|
} {
|
|
if strings.Contains(out, unwanted) {
|
|
t.Fatalf("stdout unexpectedly contained %q\n%s", unwanted, out)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRenderNotionSyncResultOmitsMutationSummaryForSameMinuteNoopDryRun(t *testing.T) {
|
|
saveAndRestoreGlobals(t)
|
|
notionSyncDryRun = true
|
|
t.Cleanup(func() { notionSyncDryRun = false })
|
|
|
|
cmd := &cobra.Command{}
|
|
var stdout bytes.Buffer
|
|
cmd.SetOut(&stdout)
|
|
|
|
renderNotionSyncResult(cmd, &tracker.SyncResult{
|
|
PullStats: tracker.PullStats{
|
|
Queried: 49,
|
|
Candidates: 3,
|
|
},
|
|
})
|
|
out := stdout.String()
|
|
for _, want := range []string{
|
|
"Dry run mode",
|
|
"Queried 49 pages from Notion (3 pull candidates)",
|
|
"Run without --dry-run to apply changes",
|
|
} {
|
|
if !strings.Contains(out, want) {
|
|
t.Fatalf("stdout missing %q\n%s", want, out)
|
|
}
|
|
}
|
|
for _, unwanted := range []string{
|
|
"Pulled ",
|
|
"Pushed ",
|
|
"Resolved ",
|
|
} {
|
|
if strings.Contains(out, unwanted) {
|
|
t.Fatalf("stdout unexpectedly contained %q\n%s", unwanted, out)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestValidateNotionConfigMessages(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
err := validateNotionConfig(notionConfig{}, nil)
|
|
if err == nil || !strings.Contains(err.Error(), "bd config set notion.token") {
|
|
t.Fatalf("err = %v", err)
|
|
}
|
|
err = validateNotionConfig(notionConfig{}, ¬ion.ResolvedAuth{Token: "token", Source: notion.AuthSourceConfigToken})
|
|
if err == nil || !strings.Contains(err.Error(), "bd notion init") {
|
|
t.Fatalf("err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestSaveNotionTargetConfig(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
deleteErr := errors.New("delete failed")
|
|
setErr := errors.New("set failed")
|
|
tests := []struct {
|
|
name string
|
|
recorder *notionConfigRecorder
|
|
viewURL string
|
|
wantErr error
|
|
wantText string
|
|
setCalls []notionConfigCall
|
|
delCalls []notionConfigCall
|
|
}{
|
|
{
|
|
name: "data source set failure short circuits",
|
|
recorder: ¬ionConfigRecorder{sets: []notionConfigOperation{{key: "notion.data_source_id", value: "ds_123", err: setErr}}},
|
|
viewURL: "https://www.notion.so/view",
|
|
wantErr: setErr,
|
|
wantText: "save notion.data_source_id",
|
|
setCalls: []notionConfigCall{{key: "notion.data_source_id", value: "ds_123"}},
|
|
},
|
|
{
|
|
name: "view delete failure preserves context",
|
|
recorder: ¬ionConfigRecorder{sets: []notionConfigOperation{{key: "notion.data_source_id", value: "ds_123"}}, deletes: []notionConfigOperation{{key: "notion.view_url", err: deleteErr}}},
|
|
wantErr: deleteErr,
|
|
wantText: "clear notion.view_url",
|
|
setCalls: []notionConfigCall{{key: "notion.data_source_id", value: "ds_123"}},
|
|
delCalls: []notionConfigCall{{key: "notion.view_url"}},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
err := saveNotionTargetConfigWithWriter(context.Background(), tt.recorder, tt.recorder, " ds_123 ", tt.viewURL)
|
|
if !errors.Is(err, tt.wantErr) {
|
|
t.Fatalf("saveNotionTargetConfigWithWriter() error = %v, want %v", err, tt.wantErr)
|
|
}
|
|
if tt.wantText != "" && !strings.Contains(err.Error(), tt.wantText) {
|
|
t.Fatalf("saveNotionTargetConfigWithWriter() error = %q, want context %q", err, tt.wantText)
|
|
}
|
|
if !reflect.DeepEqual(tt.recorder.setCalls, tt.setCalls) || !reflect.DeepEqual(tt.recorder.deleteCalls, tt.delCalls) {
|
|
t.Fatalf("calls = sets:%+v deletes:%+v, want sets:%+v deletes:%+v", tt.recorder.setCalls, tt.recorder.deleteCalls, tt.setCalls, tt.delCalls)
|
|
}
|
|
tt.recorder.assertConsumed(t)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestShouldPushNotionIssue(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
tests := []struct {
|
|
name string
|
|
issue *types.Issue
|
|
pushPrefix string
|
|
pushLabel string
|
|
want bool
|
|
}{
|
|
{
|
|
name: "existing notion ref is allowed",
|
|
issue: func() *types.Issue {
|
|
extRef := "https://www.notion.so/Test-0123456789abcdef0123456789abcdef"
|
|
return &types.Issue{ID: "beads-1", ExternalRef: &extRef}
|
|
}(),
|
|
want: true,
|
|
},
|
|
{
|
|
name: "other tracker ref is rejected",
|
|
issue: func() *types.Issue {
|
|
extRef := "https://github.com/example/repo/issues/1"
|
|
return &types.Issue{ID: "beads-1", ExternalRef: &extRef}
|
|
}(),
|
|
want: false,
|
|
},
|
|
{
|
|
name: "unlinked issue is allowed when no gate is configured",
|
|
issue: &types.Issue{ID: "beads-1"},
|
|
want: true,
|
|
},
|
|
{
|
|
name: "prefix alone narrows issue set when no label gate is configured",
|
|
issue: &types.Issue{ID: "beads-1"},
|
|
pushPrefix: "beads",
|
|
want: true,
|
|
},
|
|
{
|
|
name: "prefix mismatch still rejects issue without label gate",
|
|
issue: &types.Issue{ID: "beads-1"},
|
|
pushPrefix: "proj",
|
|
want: false,
|
|
},
|
|
{
|
|
name: "configured label opts issue in",
|
|
issue: &types.Issue{ID: "beads-1", Labels: []string{"notion-sync"}},
|
|
pushLabel: "notion-sync",
|
|
want: true,
|
|
},
|
|
{
|
|
name: "configured label still gates unlinked issue",
|
|
issue: &types.Issue{ID: "beads-1"},
|
|
pushLabel: "notion-sync",
|
|
want: false,
|
|
},
|
|
{
|
|
name: "configured label is case insensitive",
|
|
issue: &types.Issue{ID: "beads-1", Labels: []string{"Notion-Sync"}},
|
|
pushLabel: "notion-sync",
|
|
want: true,
|
|
},
|
|
{
|
|
name: "label plus matching prefix allows issue",
|
|
issue: &types.Issue{ID: "beads-1", Labels: []string{"notion-sync"}},
|
|
pushPrefix: "beads",
|
|
pushLabel: "notion-sync",
|
|
want: true,
|
|
},
|
|
{
|
|
name: "label plus wrong prefix rejects issue",
|
|
issue: &types.Issue{ID: "beads-1", Labels: []string{"notion-sync"}},
|
|
pushPrefix: "proj",
|
|
pushLabel: "notion-sync",
|
|
want: false,
|
|
},
|
|
}
|
|
|
|
tr := ¬ion.Tracker{}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := shouldPushNotionIssue(tt.issue, tr, tt.pushPrefix, tt.pushLabel); got != tt.want {
|
|
t.Fatalf("shouldPushNotionIssue() = %v, want %v", got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|