Files
base/apis/private_test.go
zeekay cc7a65b5cb base: route convention /api/* -> /v1/*
One path: /v1/*. We do not use /api/ — that's Casdoor's path. The
BASE_API_PREFIX env knob is gone; the prefix is hard-coded in
apis/base.go and apis/serve.go banner.

Server-side mounts:
- apis: bindHealthApi, bindCollectionApi, bindRecordCrudApi, etc. all
  attach under r.Group("/v1") (was r.Group(BASE_API_PREFIX, default /api))
- platform plugin: /api/platform/* -> /v1/platform/* (including auth and
  org sub-groups)
- kms plugin: /api/kms/* -> /v1/kms/*
- functions plugin: /api/functions/* -> /v1/functions/*
- cloudsql plugin: /api/cloud-sql/*, /api/meta/* -> /v1/*
- superuser OIDC: /_/api/oidc/config -> /_/v1/oidc/config
- core settings: default RateLimitRule labels /api/batch, /api/ ->
  /v1/batch, /v1/
- apis/batch.go: ValidBatchActions regexes match /v1/collections/*;
  internal rewrite targets /v1/collections/* (was /v1/base/collections/*,
  a stale artifact)

Clients:
- sdk/base-js (BaseClient.collections, files, realtime, CRDT WS,
  signIn/refresh/health) targets /v1/*
- sdk/base-react (use-crdt WS path) targets /v1/crdt
- ui-react admin (lib/api.ts, settings.application copy) targets /v1/*
- cmd/cli (NewClient.APIPrefix) defaults to /v1; client_test.go and
  cmd/cli_test.go stubServer use /v1/*
- cmd/typegen calls /v1/collections

Upstream paths untouched: Casdoor IAM (/api/login, /api/userinfo,
/api/signup, /api/send-verification-code, /api/get-user), KMS Infisical
(/api/v1/auth/universal-auth/login, /api/v2/workspace/environments),
Kubernetes tasks (/api/v1/namespaces/...), IPFS (/api/v0/...), Gitea/
GitLab/Discord/Strava/Patreon/Box/Wakatime upstream APIs. Those are
their contracts, not ours.

Tests: all 437 prior /api/ test URLs across apis/*_test.go and
plugins/platform/auth_proxy_test.go updated to /v1/. Build + go vet
clean. ./apis ./core ./plugins/platform ./plugins/jsvm ./forms all
green. Pre-existing red probes (network/TestRedProbe_*,
migratecmd/TestAutomigrateCollection*) unchanged.
2026-05-15 14:41:26 -07:00

175 lines
5.5 KiB
Go

package apis_test
import (
"bytes"
"net/http"
"testing"
"github.com/hanzoai/base/core"
"github.com/hanzoai/base/tests"
"github.com/hanzoai/dbx"
)
// Reuse the auth tokens baked into tests/data — same user the rest of the
// suite authenticates as.
const (
privateUserAToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb2xsZWN0aW9uSWQiOiJfdXNlcnNfYXV0aF8iLCJleHAiOjI1MjQ2MDQ0NjEsImlkIjoiNHExeGxjbG1mbG9rdTMzIiwicmVmcmVzaGFibGUiOnRydWUsInR5cGUiOiJhdXRoIn0.AuFTIzCsdLEy-5adFzpjZzbqAdTP6Iu9B1wPBAxLBgo"
privateTestUserID = "4q1xlclmfloku33"
)
// seedPrivateRow inserts a ciphertext row for the test user. Creates the
// table first since the endpoint does so lazily on first use.
func seedPrivateRow(app *tests.TestApp, tag string, ct []byte) error {
_, err := app.DB().NewQuery(`
CREATE TABLE IF NOT EXISTS _private (
user_id TEXT NOT NULL,
tag TEXT NOT NULL,
ct BLOB NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (user_id, tag)
) WITHOUT ROWID
`).Execute()
if err != nil {
return err
}
_, err = app.DB().NewQuery(`
INSERT INTO _private (user_id, tag, ct, updated_at)
VALUES ({:u}, {:t}, {:c}, {:n})
`).Bind(dbx.Params{"u": privateTestUserID, "t": tag, "c": ct, "n": int64(1700000000000)}).Execute()
return err
}
func TestPrivateAPI(t *testing.T) {
t.Parallel()
ciphertext := []byte{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe}
scenarios := []tests.ApiScenario{
// --- Auth gating ---
{
Name: "PUT private tag as guest → 401",
Method: http.MethodPut,
URL: "/v1/private/watchlist",
Body: bytes.NewReader(ciphertext),
ExpectedStatus: 401,
ExpectedContent: []string{`"status":401`},
},
{
Name: "GET private tag as guest → 401",
Method: http.MethodGet,
URL: "/v1/private/watchlist",
ExpectedStatus: 401,
ExpectedContent: []string{`"status":401`},
},
{
Name: "LIST private tags as guest → 401",
Method: http.MethodGet,
URL: "/v1/private",
ExpectedStatus: 401,
ExpectedContent: []string{`"status":401`},
},
// --- Tag validation ---
{
Name: "PUT with dotdot tag → 400",
Method: http.MethodPut,
URL: "/v1/private/..bad",
Body: bytes.NewReader(ciphertext),
Headers: map[string]string{"Authorization": privateUserAToken},
ExpectedStatus: 400,
ExpectedContent: []string{`"status":400`, "Invalid tag"},
},
// --- Happy path writes ---
{
Name: "PUT ciphertext returns size + timestamp",
Method: http.MethodPut,
URL: "/v1/private/watchlist",
Body: bytes.NewReader(ciphertext),
Headers: map[string]string{"Authorization": privateUserAToken},
ExpectedStatus: 200,
ExpectedContent: []string{
`"tag":"watchlist"`,
`"size":8`,
},
},
{
Name: "PUT empty body → 400 (must DELETE)",
Method: http.MethodPut,
URL: "/v1/private/empty",
Body: bytes.NewReader([]byte{}),
Headers: map[string]string{"Authorization": privateUserAToken},
ExpectedStatus: 400,
ExpectedContent: []string{`"status":400`, "Empty ciphertext"},
},
// --- Reads (seed pre-row via BeforeTestFunc) ---
{
Name: "LIST returns seeded tag",
Method: http.MethodGet,
URL: "/v1/private",
Headers: map[string]string{"Authorization": privateUserAToken},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := seedPrivateRow(app, "watchlist", ciphertext); err != nil {
t.Fatalf("seed failed: %v", err)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"tag":"watchlist"`,
`"size":8`,
`"updated_at":1700000000000`,
},
},
{
Name: "GET returns seeded ciphertext bytes",
Method: http.MethodGet,
URL: "/v1/private/watchlist",
Headers: map[string]string{"Authorization": privateUserAToken},
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := seedPrivateRow(app, "watchlist", ciphertext); err != nil {
t.Fatalf("seed failed: %v", err)
}
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
if ct := res.Header.Get("Content-Type"); ct != "application/octet-stream" {
t.Errorf("expected octet-stream, got %q", ct)
}
if ua := res.Header.Get("X-Private-Updated-At"); ua != "1700000000000" {
t.Errorf("expected updated_at header, got %q", ua)
}
},
ExpectedStatus: 200,
// The body is raw binary — bypass the content string check by
// asserting that the response doesn't contain the JSON envelope.
NotExpectedContent: []string{`"status"`, `"data"`},
},
{
Name: "GET non-existent tag → 404",
Method: http.MethodGet,
URL: "/v1/private/nope",
Headers: map[string]string{"Authorization": privateUserAToken},
ExpectedStatus: 404,
ExpectedContent: []string{`"status":404`},
},
// --- Delete ---
{
Name: "DELETE seeded tag → 204",
Method: http.MethodDelete,
URL: "/v1/private/watchlist",
Headers: map[string]string{"Authorization": privateUserAToken},
ExpectedStatus: 204,
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
if err := seedPrivateRow(app, "watchlist", ciphertext); err != nil {
t.Fatalf("seed failed: %v", err)
}
},
},
}
for _, s := range scenarios {
s.Test(t)
}
}