Compare commits

...

4 Commits

Author SHA1 Message Date
codex-bot 34c461a61c feat(auth): renew sessions with 30-day idle and 90-day absolute limits
Foundry Go checks / check (push) Successful in 2m53s
Foundry Go checks / check (pull_request) Successful in 3m9s
2026-11-06 12:32:04 +08:00
Zayden-Jung 022086beb8 Merge pull request '支持 Canvas 框选区、成员归属与名称显示模式' (#9) from codex/canvas-frames into main
Foundry Go checks / check (push) Successful in 3m28s
Deploy Foundry Core / deploy (push) Successful in 3m4s
Reviewed-on: #9
2026-11-06 03:21:48 +00:00
codex-bot 6f504ebe15 Support canvas frame nodes and explicit membership snapshots
Foundry Go checks / check (push) Successful in 3m13s
Foundry Go checks / check (pull_request) Successful in 4m24s
2026-11-06 11:20:05 +08:00
Zayden-Jung 57aab71d45 Merge pull request 'Canvas 快照持久化与 workspace/board SEO slug' (#7) from codex/canvas-persistence into main
Foundry Go checks / check (push) Successful in 2m38s
Deploy Foundry Core / deploy (push) Successful in 3m45s
Foundry Go checks / check (pull_request) Successful in 3m20s
Reviewed-on: #7
2026-11-05 18:57:43 +00:00
11 changed files with 355 additions and 29 deletions
+33
View File
@@ -104,3 +104,36 @@ at least 5 MiB; load the server snapshot, offer migration of old local drafts,
serialize autosaves and handle 412 explicitly. Restore node style dimensions
from width/height and render edges as Bézier curves. These frontend changes are
outside this Core delivery; local drafts alone are not database persistence.
Canvas schema 1 also supports frames: `type: "frame"` with `data.kind: "frame"`.
Frame names use `data.title`; optional `data.labelMode` is `hidden`, `fixed`, or
`scaled` (frontend default: `fixed`). Frames cannot rotate, connect to edges,
or belong to other frames. Any non-frame node can specify `data.frameId`, which
must reference a frame in the same snapshot; forward references are supported.
Membership is explicit and independent of geometry: moving a frame over existing
content does not add members. The frontend assigns membership on content drop
and implements label zoom behavior. Core preserves the supplied membership and
label mode without inferring them from positions. Renderer-only `zIndex` is
ignored alongside transient state; restore frame layering in the frontend.
This extends existing JSONB snapshots and requires no additional migration.
### Browser session lifetime
Sessions use random, revocable bearer tokens rather than JWTs. New email and OAuth
logins have a 30-day idle lifetime; authenticated requests atomically renew that
idle deadline, capped at 90 days from issuance. Idle-expired, absolute-expired,
revoked and wrong-project tokens are never revived. Logout removes the session.
Apply `db/004-session-lifetime.sql` before running this version. Existing sessions
keep their prior idle expiry, so expired logins remain expired. For legacy rows,
the absolute 90-day cap starts at migration time because issuance was not recorded;
an unexpired legacy session gains the new idle lifetime on its next authenticated
request. New rows record their actual creation time and absolute deadline.
Login and exchange responses return `expires_in: 2592000`. Protected platform
responses and `/auth/me` include `X-Foundry-Session-Expires-In` with the remaining
seconds after renewal, shortened near the absolute deadline. The frontend proxy
must renew its HttpOnly cookie using that value, with a maximum of 30 days. It must
not extend a cookie beyond the backend-provided remaining lifetime, or expose the
session token to client JavaScript. CORS exposes the lifetime header alongside
ETag where applicable. The absolute deadline stays server-authoritative.
+9
View File
@@ -0,0 +1,9 @@
BEGIN;
-- Existing sessions keep their current idle deadline: expired sessions stay expired.
-- Their original issuance time was not recorded, so the new absolute cap starts here.
ALTER TABLE project_sessions
ADD COLUMN created_at timestamptz NOT NULL DEFAULT now(),
ADD COLUMN absolute_expires_at timestamptz NOT NULL DEFAULT (now() + interval '90 days');
COMMIT;
+8 -1
View File
@@ -17,7 +17,8 @@ psql <<'SQL'
INSERT INTO project_accounts(project,id,google_subject,email)
VALUES ('fixture','00000000-0000-0000-0000-000000000001','existing-google','existing@example.invalid');
INSERT INTO project_sessions VALUES
('existing-session','fixture','00000000-0000-0000-0000-000000000001',now()+interval '1 hour');
('existing-session','fixture','00000000-0000-0000-0000-000000000001',now()+interval '1 hour'),
('expired-session','fixture','00000000-0000-0000-0000-000000000001',now()-interval '1 hour');
SQL
psql <<'SQLROLE'
CREATE ROLE foundry_fixture LOGIN;
@@ -33,6 +34,12 @@ BEGIN
JOIN account_identities i ON (i.project,i.account_id)=(a.project,a.id)
WHERE s.token_hash='existing-session' AND i.provider='google' AND i.subject='existing-google'
) THEN RAISE EXCEPTION 'Existing Google login was lost'; END IF;
IF EXISTS (SELECT 1 FROM project_sessions WHERE token_hash='expired-session' AND expires_at>now()) THEN
RAISE EXCEPTION 'Migration revived expired session';
END IF;
IF NOT EXISTS (SELECT 1 FROM project_sessions WHERE token_hash='existing-session' AND absolute_expires_at>now()+interval '89 days') THEN
RAISE EXCEPTION 'Missing absolute session deadline';
END IF;
END $$;
BEGIN;
INSERT INTO project_accounts(project,id,email) VALUES
+14 -11
View File
@@ -129,6 +129,7 @@ func (s *service) project(w http.ResponseWriter, r *http.Request) error {
return reject(w, 403, "origin_denied")
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", SessionExpiryHeader)
}
switch {
case r.Method == http.MethodOptions:
@@ -289,8 +290,8 @@ func (s *service) exchange(w http.ResponseWriter, r *http.Request, project strin
WHERE token_hash = $1 AND project = $2 AND frontend_challenge = $3 AND expires_at > now()
RETURNING account_id
)
INSERT INTO project_sessions
SELECT $4, $2, account_id, now() + interval '8 hours' FROM redeemed_grant
INSERT INTO project_sessions(token_hash,project,account_id,expires_at)
SELECT $4, $2, account_id, now() + interval '30 days' FROM redeemed_grant
`, digest(code), project, digest(verifier), digest(session))
if err != nil {
return err
@@ -302,7 +303,7 @@ func (s *service) exchange(w http.ResponseWriter, r *http.Request, project strin
if count == 0 {
return reject(w, 401, "invalid_grant")
}
reply(w, 200, payload{"access_token": session, "token_type": "Bearer", "expires_in": 28800})
reply(w, 200, payload{"access_token": session, "token_type": "Bearer", "expires_in": SessionIdleSeconds})
return nil
}
@@ -319,19 +320,21 @@ func (s *service) account(w http.ResponseWriter, r *http.Request, project string
reply(w, 204, nil)
return nil
}
var id string
var email *string
err := s.db.QueryRowContext(r.Context(), `
SELECT a.id::text, a.email FROM project_sessions s
JOIN project_accounts a ON a.project = s.project AND a.id = s.account_id
WHERE s.token_hash = $1 AND s.project = $2 AND s.expires_at > now()
`, digest(token), project).Scan(&id, &email)
if errors.Is(err, sql.ErrNoRows) {
session, err := AuthenticateSession(r.Context(), s.db, project, r.Header.Get("Authorization"))
if errors.Is(err, ErrInvalidSession) {
return reject(w, 401, "invalid_session")
}
if err != nil {
return err
}
var email *string
err = s.db.QueryRowContext(r.Context(), "SELECT email FROM project_accounts WHERE project=$1 AND id=$2", project, session.AccountID).Scan(&email)
if err != nil {
return err
}
WriteSessionHeaders(w, session)
id := session.AccountID
reply(w, 200, payload{"project": project, "id": id, "email": email})
return nil
}
+4 -4
View File
@@ -94,11 +94,11 @@ func (s *service) emailAction(w http.ResponseWriter, r *http.Request, project, a
return reject(w, 401, "invalid_credentials")
}
session := token()
_, err = s.db.ExecContext(r.Context(), "INSERT INTO project_sessions VALUES($1,$2,$3,now()+interval '8 hours')", digest(session), project, account)
_, err = s.db.ExecContext(r.Context(), "INSERT INTO project_sessions(token_hash,project,account_id,expires_at) VALUES($1,$2,$3,now()+interval '30 days')", digest(session), project, account)
if err != nil {
return err
}
reply(w, 200, payload{"access_token": session, "token_type": "Bearer", "expires_in": 28800})
reply(w, 200, payload{"access_token": session, "token_type": "Bearer", "expires_in": SessionIdleSeconds})
return nil
}
@@ -205,13 +205,13 @@ SELECT $1,id,$2,
return err
}
session := token()
_, err = tx.ExecContext(r.Context(), "INSERT INTO project_sessions VALUES($1,$2,$3,now()+interval '8 hours')", digest(session), project, account)
_, err = tx.ExecContext(r.Context(), "INSERT INTO project_sessions(token_hash,project,account_id,expires_at) VALUES($1,$2,$3,now()+interval '30 days')", digest(session), project, account)
if err != nil {
return err
}
if err = tx.Commit(); err != nil {
return err
}
reply(w, 201, payload{"access_token": session, "token_type": "Bearer", "expires_in": 28800})
reply(w, 201, payload{"access_token": session, "token_type": "Bearer", "expires_in": SessionIdleSeconds})
return nil
}
+32 -9
View File
@@ -4,24 +4,47 @@ import (
"context"
"database/sql"
"errors"
"net/http"
"strconv"
"strings"
)
const SessionIdleSeconds = 30 * 24 * 60 * 60
const SessionExpiryHeader = "X-Foundry-Session-Expires-In"
var ErrInvalidSession = errors.New("invalid session")
// Authenticate resolves only an unexpired session belonging to this project.
func Authenticate(ctx context.Context, db *sql.DB, project, authorization string) (string, error) {
type Session struct {
AccountID string
ExpiresIn int64
}
// AuthenticateSession atomically validates and renews a live session, bounded by
// its absolute deadline. Expired, revoked and wrong-project tokens never renew.
func AuthenticateSession(ctx context.Context, db *sql.DB, project, authorization string) (Session, error) {
value, ok := strings.CutPrefix(authorization, "Bearer ")
if !ok || !tokenPattern.MatchString(value) {
return "", ErrInvalidSession
return Session{}, ErrInvalidSession
}
var id string
var session Session
err := db.QueryRowContext(ctx, `
SELECT account_id::text FROM project_sessions
WHERE project=$1 AND token_hash=$2 AND expires_at>now()
`, project, digest(value)).Scan(&id)
UPDATE project_sessions
SET expires_at=LEAST(now()+interval '30 days',absolute_expires_at)
WHERE project=$1 AND token_hash=$2 AND expires_at>now() AND absolute_expires_at>now()
RETURNING account_id::text,GREATEST(0,FLOOR(EXTRACT(EPOCH FROM (expires_at-now()))))::bigint
`, project, digest(value)).Scan(&session.AccountID, &session.ExpiresIn)
if errors.Is(err, sql.ErrNoRows) {
return "", ErrInvalidSession
return Session{}, ErrInvalidSession
}
return id, err
return session, err
}
func WriteSessionHeaders(w http.ResponseWriter, session Session) {
w.Header().Set(SessionExpiryHeader, strconv.FormatInt(session.ExpiresIn, 10))
}
// Authenticate preserves the existing API for clients that only need an account ID.
func Authenticate(ctx context.Context, db *sql.DB, project, authorization string) (string, error) {
session, err := AuthenticateSession(ctx, db, project, authorization)
return session.AccountID, err
}
+151
View File
@@ -0,0 +1,151 @@
package auth
import (
"context"
"database/sql"
"encoding/json"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
func sessionFixture(t *testing.T) (*sql.DB, string, string) {
t.Helper()
dsn := os.Getenv("PLATFORM_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires isolated integration database")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
project := "session-" + token()[:12]
var account string
if err = db.QueryRow("INSERT INTO project_accounts(project,id) VALUES($1,gen_random_uuid()) RETURNING id::text", project).Scan(&account); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = db.Exec("DELETE FROM project_accounts WHERE project=$1", project); db.Close() })
return db, project, account
}
func TestSessionIdleAndAbsoluteExpiry(t *testing.T) {
db, project, account := sessionFixture(t)
for _, test := range []struct {
name, idle, absolute string
valid bool
}{
{"active", "1 hour", "90 days", true},
{"idle-expired", "-1 second", "90 days", false},
{"absolute-cap", "1 hour", "2 days", true},
{"absolute-expired", "1 hour", "-1 second", false},
} {
t.Run(test.name, func(t *testing.T) {
value := token()
_, err := db.Exec("INSERT INTO project_sessions(token_hash,project,account_id,expires_at,absolute_expires_at) VALUES($1,$2,$3,now()+$4::interval,now()+$5::interval)", digest(value), project, account, test.idle, test.absolute)
if err != nil {
t.Fatal(err)
}
var before time.Time
if err := db.QueryRow("SELECT expires_at FROM project_sessions WHERE token_hash=$1", digest(value)).Scan(&before); err != nil {
t.Fatal(err)
}
session, err := AuthenticateSession(context.Background(), db, project, "Bearer "+value)
if !test.valid {
if err != ErrInvalidSession {
t.Fatalf("expired session accepted: %v", err)
}
var after time.Time
if err := db.QueryRow("SELECT expires_at FROM project_sessions WHERE token_hash=$1", digest(value)).Scan(&after); err != nil {
t.Fatal(err)
}
if !after.Equal(before) {
t.Fatal("expired session revived")
}
return
}
if err != nil || session.AccountID != account || session.ExpiresIn <= 0 || session.ExpiresIn > SessionIdleSeconds {
t.Fatalf("invalid renewal result: %+v %v", session, err)
}
var expiry, cap time.Time
if err := db.QueryRow("SELECT expires_at,absolute_expires_at FROM project_sessions WHERE token_hash=$1", digest(value)).Scan(&expiry, &cap); err != nil {
t.Fatal(err)
}
if expiry.After(cap) || (test.name == "absolute-cap" && !expiry.Equal(cap)) {
t.Fatal("absolute cap not enforced")
}
if test.name == "active" && session.ExpiresIn < SessionIdleSeconds-2 {
t.Fatal("active session did not receive 30 idle days")
}
})
}
}
func TestSessionIsolationRevocationAndConcurrentRenewal(t *testing.T) {
db, project, account := sessionFixture(t)
value := token()
if _, err := db.Exec("INSERT INTO project_sessions(token_hash,project,account_id,expires_at,absolute_expires_at) VALUES($1,$2,$3,now()+interval '1 hour',now()+interval '2 days')", digest(value), project, account); err != nil {
t.Fatal(err)
}
for _, input := range []struct{ project, authorization string }{{"other", "Bearer " + value}, {project, "Bearer bad-token"}, {project, ""}} {
if _, err := AuthenticateSession(context.Background(), db, input.project, input.authorization); err != ErrInvalidSession {
t.Fatalf("invalid or cross-project token accepted: %v", err)
}
}
var group sync.WaitGroup
for range 4 {
group.Add(1)
go func() {
defer group.Done()
session, err := AuthenticateSession(context.Background(), db, project, "Bearer "+value)
if err != nil || session.ExpiresIn > 2*86400 {
t.Errorf("concurrent renewal escaped cap: %+v %v", session, err)
}
}()
}
group.Wait()
if _, err := db.Exec("DELETE FROM project_sessions WHERE token_hash=$1", digest(value)); err != nil {
t.Fatal(err)
}
if _, err := AuthenticateSession(context.Background(), db, project, "Bearer "+value); err != ErrInvalidSession {
t.Fatal("revoked session renewed")
}
}
func TestOAuthExchangeIssuesLongLivedSessionAndMeReturnsRemainingLifetime(t *testing.T) {
db, project, account := sessionFixture(t)
code, verifier := token(), token()
_, err := db.Exec("INSERT INTO login_grants(token_hash,project,account_id,frontend_challenge,expires_at) VALUES($1,$2,$3,$4,now()+interval '1 minute')", digest(code), project, account, digest(verifier))
if err != nil {
t.Fatal(err)
}
s := &service{db: db}
r := httptest.NewRequest("POST", "/exchange", nil)
r.Header.Set("X-Foundry-Code", code)
r.Header.Set("X-Foundry-Verifier", verifier)
out := httptest.NewRecorder()
if err = s.exchange(out, r, project); err != nil || out.Code != 200 {
t.Fatalf("exchange: %d %v", out.Code, err)
}
var result struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
if err = json.Unmarshal(out.Body.Bytes(), &result); err != nil || result.ExpiresIn != SessionIdleSeconds {
t.Fatal("incorrect login lifetime")
}
var idle, absolute float64
if err = db.QueryRow("SELECT EXTRACT(EPOCH FROM(expires_at-created_at)),EXTRACT(EPOCH FROM(absolute_expires_at-created_at)) FROM project_sessions WHERE token_hash=$1", digest(result.AccessToken)).Scan(&idle, &absolute); err != nil || idle < SessionIdleSeconds-2 || absolute != 90*86400 {
t.Fatalf("wrong session deadlines: %f %f %v", idle, absolute, err)
}
r = httptest.NewRequest("GET", "/me", strings.NewReader(""))
r.Header.Set("Authorization", "Bearer "+result.AccessToken)
out = httptest.NewRecorder()
if err = s.account(out, r, project, false); err != nil || out.Header().Get(SessionExpiryHeader) == "" {
t.Fatal("missing renewal header")
}
}
+26 -2
View File
@@ -105,7 +105,7 @@ func normalizeCanvas(raw json.RawMessage) (json.RawMessage, bool) {
}
}
}
for _, key := range []string{"selected", "dragging", "measured", "style"} {
for _, key := range []string{"selected", "dragging", "measured", "style", "zIndex"} {
delete(n, key)
}
if !canvasFields(n, "id", "type", "position", "width", "height", "data") {
@@ -125,7 +125,7 @@ func normalizeCanvas(raw json.RawMessage) (json.RawMessage, bool) {
return nil, false
}
d, ok := n["data"].(map[string]any)
if !ok || !canvasFields(d, "kind", "title", "text", "src", "icon", "rotation", "fontSize", "textStyle") {
if !ok || !canvasFields(d, "kind", "title", "text", "src", "icon", "rotation", "fontSize", "textStyle", "frameId", "labelMode") {
return nil, false
}
kind, ok := d["kind"].(string)
@@ -137,12 +137,28 @@ func normalizeCanvas(raw json.RawMessage) (json.RawMessage, bool) {
typ = "plainText"
} else if kind == "icon" {
typ = "icon"
} else if kind == "frame" {
typ = "frame"
} else if !canvasChoice(kind, "text", "image", "script") {
return nil, false
}
if n["type"] != typ || !canvasString(d["title"], 300) || !canvasString(d["text"], 100000) {
return nil, false
}
if frameID, exists := d["frameId"]; exists {
value, ok := frameID.(string)
if kind == "frame" || !ok || !canvasID.MatchString(value) {
return nil, false
}
}
if mode, exists := d["labelMode"]; exists && (kind != "frame" || !canvasChoice(mode, "hidden", "fixed", "scaled")) {
return nil, false
}
if kind == "frame" {
if rotation, exists := d["rotation"]; exists && rotation != float64(0) {
return nil, false
}
}
kinds[id] = kind
if r, exists := d["rotation"]; exists && (!canvasNumber(r, 0, 360) || r == float64(360)) {
return nil, false
@@ -191,6 +207,14 @@ func normalizeCanvas(raw json.RawMessage) (json.RawMessage, bool) {
}
}
}
// Resolve memberships after all nodes so forward references are valid.
// Geometry never creates membership: only explicit frameId is persisted.
for _, value := range nodes {
data := value.(map[string]any)["data"].(map[string]any)
if id, exists := data["frameId"]; exists && kinds[id.(string)] != "frame" {
return nil, false
}
}
seen := map[string]bool{}
for _, v := range edges {
e, ok := v.(map[string]any)
+49
View File
@@ -39,3 +39,52 @@ func TestSlugValidation(t *testing.T) {
}
}
}
// Frame nodes follow the frontend contract: membership is data, not containment.
const frameFixture = `{"schema_version":1,"nodes":[{"id":"text","type":"material","position":{"x":100,"y":100},"data":{"kind":"text","title":"成员","text":"正文","frameId":"frame"}},{"id":"plain","type":"plainText","position":{"x":0,"y":0},"data":{"kind":"plain-text","title":"纯文本","text":"文字","frameId":"frame"}},{"id":"icon","type":"icon","position":{"x":10,"y":10},"data":{"kind":"icon","title":"图标","text":"","icon":"Star","frameId":"frame"}},{"id":"frame","type":"frame","position":{"x":0,"y":0},"width":600,"height":400,"zIndex":-1,"style":{"width":600,"height":400,"pointerEvents":"none"},"data":{"kind":"frame","title":"框选区","text":"","rotation":0,"labelMode":"fixed"}},{"id":"outside","type":"material","position":{"x":100,"y":100},"data":{"kind":"script","title":"重叠但未加入","text":""}}],"edges":[],"viewport":{"x":0,"y":0,"zoom":1}}`
func TestCanvasFrames(t *testing.T) {
for _, mode := range []string{"hidden", "fixed", "scaled"} {
t.Run(mode, func(t *testing.T) {
out, ok := normalizeCanvas(json.RawMessage(strings.Replace(frameFixture, `"labelMode":"fixed"`, `"labelMode":"`+mode+`"`, 1)))
if !ok {
t.Fatal("valid frame rejected")
}
var doc map[string]any
json.Unmarshal(out, &doc)
nodes := doc["nodes"].([]any)
if nodes[0].(map[string]any)["data"].(map[string]any)["frameId"] != "frame" || nodes[3].(map[string]any)["data"].(map[string]any)["labelMode"] != mode {
t.Fatal("frame data lost")
}
if _, exists := nodes[4].(map[string]any)["data"].(map[string]any)["frameId"]; exists {
t.Fatal("position inferred membership")
}
if _, exists := nodes[3].(map[string]any)["zIndex"]; exists {
t.Fatal("rendering state persisted")
}
})
}
cases := [][2]string{
{`"labelMode":"fixed"`, `"labelMode":"invalid"`},
{`"labelMode":"fixed"`, `"labelMode":null`},
{`"rotation":0`, `"rotation":1`},
{`"frameId":"frame"`, `"frameId":"missing"`},
{`"frameId":"frame"`, `"frameId":"text"`},
{`"frameId":"frame"`, `"frameId":null`},
{`"frameId":"frame"`, `"frameId":""`},
{`"labelMode":"fixed"`, `"labelMode":"fixed","frameId":"frame"`},
{`"type":"frame"`, `"type":"material"`},
{`"edges":[]`, `"edges":[{"id":"e","source":"text","target":"frame"}]`},
}
for _, c := range cases {
t.Run(c[1], func(t *testing.T) {
if _, ok := normalizeCanvas(json.RawMessage(strings.Replace(frameFixture, c[0], c[1], 1))); ok {
t.Fatal("invalid frame accepted")
}
})
}
withoutMode := strings.Replace(frameFixture, `,"labelMode":"fixed"`, "", 1)
if _, ok := normalizeCanvas(json.RawMessage(withoutMode)); !ok {
t.Fatal("optional labelMode rejected")
}
}
+6 -2
View File
@@ -69,7 +69,7 @@ func (s *service) protected(callbacks map[string]string, handle endpoint) http.H
return
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", "ETag")
w.Header().Set("Access-Control-Expose-Headers", "ETag, "+auth.SessionExpiryHeader)
}
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
@@ -77,11 +77,15 @@ func (s *service) protected(callbacks map[string]string, handle endpoint) http.H
reply(w, 204, nil)
return
}
account, err := auth.Authenticate(r.Context(), s.db, project, r.Header.Get("Authorization"))
session, err := auth.AuthenticateSession(r.Context(), s.db, project, r.Header.Get("Authorization"))
if errors.Is(err, auth.ErrInvalidSession) {
reject(w, 401, "invalid_session")
return
}
account := session.AccountID
if err == nil {
auth.WriteSessionHeaders(w, session)
}
if err == nil && r.PathValue("workspace") != "" {
var id string
err = s.db.QueryRowContext(r.Context(), "SELECT id::text FROM workspaces WHERE project=$1 AND (id::text=$2 OR slug=$2)", project, r.PathValue("workspace")).Scan(&id)
+23
View File
@@ -14,6 +14,7 @@ import (
"net/http/httptest"
"os"
"regexp"
"strconv"
"strings"
"testing"
@@ -234,6 +235,28 @@ func TestOnboardingAndSharing(t *testing.T) {
if call("GET", workspacePath, tokens[0], nil, 200)["slug"] != "research-team" {
t.Fatal("rename changed slug")
}
// Frames round-trip through PostgreSQL with all label modes and explicit memberships.
for index, mode := range []string{"hidden", "fixed", "scaled"} {
version := strconv.Itoa(4 + index)
raw := strings.Replace(frameFixture, `"labelMode":"fixed"`, `"labelMode":"`+mode+`"`, 1)
call("PATCH", canvasPath, tokens[0], response{"document": json.RawMessage(raw)}, 200, `"`+version+`"`)
persisted := call("GET", canvasPath, tokens[0], nil, 200)
normalized, _ := normalizeCanvas(json.RawMessage(raw))
want, _ := json.Marshal(json.RawMessage(normalized))
got, _ := json.Marshal(persisted["document"])
if !bytes.Equal(want, got) {
t.Fatal("frame snapshot not preserved")
}
}
invalidFrame := strings.Replace(frameFixture, `"frameId":"frame"`, `"frameId":"missing"`, 1)
rejected := call("PATCH", canvasPath, tokens[0], response{"document": json.RawMessage(invalidFrame)}, 400, `"7"`)
if rejected["error"] != "invalid_canvas" {
t.Fatal("unexpected frame error")
}
if call("GET", canvasPath, tokens[0], nil, 200)["version"] != float64(7) {
t.Fatal("invalid frame changed saved version")
}
layout := call("POST", boardPath+"/layouts", tokens[0], response{"material_id": articleID, "x": 1, "y": 2, "width": 320, "height": 200, "z_index": 1}, 201, `"2"`)
call("GET", boardPath+"/layouts", tokens[1], nil, 200)
call("POST", boardPath+"/grants", tokens[0], response{"account_id": accounts[2], "role": "viewer"}, 204)