Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
940a9137b4 | ||
|
|
0ba1dcfef0 | ||
|
|
96065d1e89 | ||
|
|
2cbaa9342d | ||
|
|
38b0fe2a94 | ||
|
|
667776e43f | ||
|
|
02edb51b8a | ||
|
|
b61fbc38a4 | ||
|
|
02fb77f72b | ||
|
|
09afb438c9 | ||
|
|
2d6ceac0d7 | ||
|
|
bd80ff6a0c | ||
|
|
b90aef79d0 | ||
|
|
84d52390f9 | ||
|
|
4049acf76e | ||
|
|
43a2d8c5a1 |
No files matched your search
@@ -35,8 +35,8 @@ jobs:
|
|||||||
[worker.oci]
|
[worker.oci]
|
||||||
max-parallelism = 2
|
max-parallelism = 2
|
||||||
|
|
||||||
- name: Test release tooling and wallpaper palette
|
- name: Test release tooling and browser logic
|
||||||
run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs
|
run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs static/js/csv-core.test.cjs
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||||
@@ -47,6 +47,10 @@ jobs:
|
|||||||
platforms: linux/amd64
|
platforms: linux/amd64
|
||||||
push: false
|
push: false
|
||||||
|
|
||||||
|
- name: Test native PostgreSQL 17 before publishing
|
||||||
|
shell: bash
|
||||||
|
run: bash tools/ci/test-postgres.sh
|
||||||
|
|
||||||
- name: Log in to registry
|
- name: Log in to registry
|
||||||
uses: https://github.com/docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0
|
uses: https://github.com/docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0
|
||||||
with:
|
with:
|
||||||
@@ -91,13 +95,25 @@ jobs:
|
|||||||
org.opencontainers.image.revision=${{ github.sha }}
|
org.opencontainers.image.revision=${{ github.sha }}
|
||||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||||
|
|
||||||
|
- name: Build Gecko relay
|
||||||
|
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: Dockerfile.gecko-relay
|
||||||
|
platforms: linux/amd64
|
||||||
|
load: true
|
||||||
|
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_OWNER }}/pageswiki-gecko-relay:${{ env.IMAGE_TAG }}
|
||||||
|
labels: |
|
||||||
|
org.opencontainers.image.revision=${{ github.sha }}
|
||||||
|
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||||
|
|
||||||
# Publish only after all builds succeed. Use the host daemon for registry
|
# Publish only after all builds succeed. Use the host daemon for registry
|
||||||
# access; BuildKit does not inherit the runner's /etc/hosts entries.
|
# access; BuildKit does not inherit the runner's /etc/hosts entries.
|
||||||
- name: Push images
|
- name: Push images
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer; do
|
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer pageswiki-gecko-relay; do
|
||||||
docker push "$REGISTRY/$IMAGE_OWNER/$image:$IMAGE_TAG"
|
docker push "$REGISTRY/$IMAGE_OWNER/$image:$IMAGE_TAG"
|
||||||
done
|
done
|
||||||
|
|
||||||
@@ -105,7 +121,7 @@ jobs:
|
|||||||
if: always()
|
if: always()
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer; do
|
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer pageswiki-gecko-relay; do
|
||||||
ref="$REGISTRY/$IMAGE_OWNER/$image:$IMAGE_TAG"
|
ref="$REGISTRY/$IMAGE_OWNER/$image:$IMAGE_TAG"
|
||||||
if docker image inspect "$ref" >/dev/null 2>&1; then
|
if docker image inspect "$ref" >/dev/null 2>&1; then
|
||||||
docker image rm "$ref" || echo "Could not remove local CI tag: $ref" >&2
|
docker image rm "$ref" || echo "Could not remove local CI tag: $ref" >&2
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ data/*
|
|||||||
!data/test_cli_dr.py
|
!data/test_cli_dr.py
|
||||||
!data/pageswiki-remote
|
!data/pageswiki-remote
|
||||||
/data2/
|
/data2/
|
||||||
|
/docs/local/
|
||||||
/.codex/
|
/.codex/
|
||||||
/.agents/
|
/.agents/
|
||||||
/.env
|
/.env
|
||||||
@@ -19,6 +20,7 @@ data/*
|
|||||||
.tmp/
|
.tmp/
|
||||||
.deployment-backups/
|
.deployment-backups/
|
||||||
*.sh
|
*.sh
|
||||||
|
!tools/ci/test-postgres.sh
|
||||||
assets/editor/node_modules/
|
assets/editor/node_modules/
|
||||||
assets/city-generator/node_modules/
|
assets/city-generator/node_modules/
|
||||||
assets/excalidraw-viewer/node_modules/
|
assets/excalidraw-viewer/node_modules/
|
||||||
|
|||||||
@@ -342,6 +342,12 @@ window.PagesWikiEditor = {
|
|||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
if (options.preserveLineEndings) {
|
||||||
|
// Split only at LF, keeping any CR bytes in the document. This
|
||||||
|
// preserves mixed LF/CRLF CSV sources instead of rewriting them.
|
||||||
|
extensions.push(EditorState.lineSeparator.of("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
if (keymapName === "vim") {
|
if (keymapName === "vim") {
|
||||||
installVimCommands();
|
installVimCommands();
|
||||||
extensions.push(vim());
|
extensions.push(vim());
|
||||||
|
|||||||
@@ -66,10 +66,15 @@ func main() {
|
|||||||
if err := geckorelay.VerifyAssets(assets); err != nil {
|
if err := geckorelay.VerifyAssets(assets); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
distribution, err := geckorelay.VerifyDistribution(assets)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
relay, err := geckorelay.New(secret, assets)
|
relay, err := geckorelay.New(secret, assets)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
relay.Distribution = distribution
|
||||||
s := &http.Server{Addr: addr, Handler: relay, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
|
s := &http.Server{Addr: addr, Handler: relay, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
|
||||||
log.Printf("Gecko relay listening; authenticated TCP 80/443 only")
|
log.Printf("Gecko relay listening; authenticated TCP 80/443 only")
|
||||||
log.Fatal(s.ListenAndServe())
|
log.Fatal(s.ListenAndServe())
|
||||||
|
|||||||
@@ -16,6 +16,13 @@ import (
|
|||||||
// All role changes are operator-only and offline. Never expose this as a
|
// All role changes are operator-only and offline. Never expose this as a
|
||||||
// domain-admin API: a data directory contains multiple campuses and domains.
|
// domain-admin API: a data directory contains multiple campuses and domains.
|
||||||
func runDR(args []string, out io.Writer) error {
|
func runDR(args []string, out io.Writer) error {
|
||||||
|
backend, err := configuredDatabaseBackend()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if backend != "sqlite" {
|
||||||
|
return errors.New("DR commands require the SQLite backend; use PostgreSQL backup/restore for native instances")
|
||||||
|
}
|
||||||
const usage = "pageswiki dr {init|status|snapshot|verify|restore|promote|resume-workers} [flags]\nUse COMMAND --help. Snapshot requires all writers stopped; promotion requires external fencing."
|
const usage = "pageswiki dr {init|status|snapshot|verify|restore|promote|resume-workers} [flags]\nUse COMMAND --help. Snapshot requires all writers stopped; promotion requires external fencing."
|
||||||
if len(args) == 0 || args[0] == "--help" {
|
if len(args) == 0 || args[0] == "--help" {
|
||||||
_, err := fmt.Fprintln(out, usage)
|
_, err := fmt.Fprintln(out, usage)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -14,18 +15,30 @@ import (
|
|||||||
|
|
||||||
const managedCampusReconcileInterval = 5 * time.Second
|
const managedCampusReconcileInterval = 5 * time.Second
|
||||||
|
|
||||||
func startManagedCampusReconciler(dataDir string, st *store.Store) {
|
func startManagedCampusReconciler(ctx context.Context, dataDir string, st *store.Store) <-chan struct{} {
|
||||||
|
done := make(chan struct{})
|
||||||
instanceFQDN := strings.TrimSpace(os.Getenv("PAGESWIKI_INSTANCE_FQDN"))
|
instanceFQDN := strings.TrimSpace(os.Getenv("PAGESWIKI_INSTANCE_FQDN"))
|
||||||
if instanceFQDN == "" {
|
if instanceFQDN == "" || st.ReadOnly || st.BackgroundJobsDisabled {
|
||||||
return
|
close(done)
|
||||||
|
return done
|
||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
|
defer close(done)
|
||||||
ticker := time.NewTicker(managedCampusReconcileInterval)
|
ticker := time.NewTicker(managedCampusReconcileInterval)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
for range ticker.C {
|
for {
|
||||||
reconcileManagedCampuses(dataDir, st, instanceFQDN)
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reconcileManagedCampusesContext(ctx, dataDir, st, instanceFQDN)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
return done
|
||||||
}
|
}
|
||||||
|
|
||||||
func reconcileManagedCampuses(
|
func reconcileManagedCampuses(
|
||||||
@@ -33,12 +46,19 @@ func reconcileManagedCampuses(
|
|||||||
st *store.Store,
|
st *store.Store,
|
||||||
instanceFQDN string,
|
instanceFQDN string,
|
||||||
) {
|
) {
|
||||||
|
reconcileManagedCampusesContext(context.Background(), dataDir, st, instanceFQDN)
|
||||||
|
}
|
||||||
|
|
||||||
|
func reconcileManagedCampusesContext(ctx context.Context, dataDir string, st *store.Store, instanceFQDN string) {
|
||||||
campuses, err := st.ListCampuses()
|
campuses, err := st.ListCampuses()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("managed Campus reconciliation: %v", err)
|
log.Printf("managed Campus reconciliation: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
for _, campus := range campuses {
|
for _, campus := range campuses {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
if campus.AuthorityMode != "managed" || !campus.Enabled {
|
if campus.AuthorityMode != "managed" || !campus.Enabled {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-56
@@ -1,18 +1,26 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
"pageswiki/internal/db"
|
"pageswiki/internal/db"
|
||||||
"pageswiki/internal/dr"
|
"pageswiki/internal/dr"
|
||||||
"pageswiki/internal/server"
|
|
||||||
"pageswiki/internal/store"
|
"pageswiki/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if len(os.Args) > 1 && os.Args[1] == "migrate-postgres" {
|
||||||
|
if err := runPostgreSQLMigration(os.Args[2:], os.Stdout); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
if len(os.Args) > 1 && os.Args[1] == "schema" {
|
if len(os.Args) > 1 && os.Args[1] == "schema" {
|
||||||
if err := runSchema(os.Args[2:], os.Stdout); err != nil {
|
if err := runSchema(os.Args[2:], os.Stdout); err != nil {
|
||||||
log.Print(err)
|
log.Print(err)
|
||||||
@@ -29,6 +37,8 @@ func main() {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
enrollment, err := parseExternalCampusEnrollment(os.Args[1:])
|
enrollment, err := parseExternalCampusEnrollment(os.Args[1:])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
@@ -64,6 +74,13 @@ func main() {
|
|||||||
if err = dr.RequireRole(node, os.Getenv("PAGESWIKI_DR_EXPECT_ROLE")); err != nil {
|
if err = dr.RequireRole(node, os.Getenv("PAGESWIKI_DR_EXPECT_ROLE")); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
backend, err := configuredDatabaseBackend()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
if backend == "postgresql" && node != nil {
|
||||||
|
log.Fatal("PostgreSQL currently supports standalone instances only; DR startup refused")
|
||||||
|
}
|
||||||
if node != nil && node.Role == "standby" {
|
if node != nil && node.Role == "standby" {
|
||||||
if len(os.Args) > 1 {
|
if len(os.Args) > 1 {
|
||||||
log.Fatal("standby does not accept enrollment/startup mutation flags")
|
log.Fatal("standby does not accept enrollment/startup mutation flags")
|
||||||
@@ -79,73 +96,23 @@ func main() {
|
|||||||
}
|
}
|
||||||
st.StandbyReadUntil = node.ReadUntil()
|
st.StandbyReadUntil = node.ReadUntil()
|
||||||
log.Printf("DR standby: migrations, federation reconciliation and background workers disabled; snapshot=%s", node.SnapshotID)
|
log.Printf("DR standby: migrations, federation reconciliation and background workers disabled; snapshot=%s", node.SnapshotID)
|
||||||
if err := server.New(st).Run(":3000"); err != nil {
|
if err := serveInstance(ctx, dataDir, st, ":3000"); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dbPath :=
|
log.Printf("database backend = %s", backend)
|
||||||
filepath.Join(
|
database, st, err := openApplicationStore(ctx, dataDir)
|
||||||
dataDir,
|
|
||||||
"pages.db",
|
|
||||||
)
|
|
||||||
|
|
||||||
log.Printf(
|
|
||||||
"pages.db = %s",
|
|
||||||
dbPath,
|
|
||||||
)
|
|
||||||
|
|
||||||
database, err :=
|
|
||||||
db.Open(dbPath)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = db.Migrate(database)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
documentRoot, err :=
|
|
||||||
store.MigrateLegacyDocumentRoot(
|
|
||||||
dataDir,
|
|
||||||
)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
st :=
|
|
||||||
store.NewWithDocumentRoot(
|
|
||||||
database,
|
|
||||||
documentRoot,
|
|
||||||
)
|
|
||||||
|
|
||||||
err = st.EnsureConfigTable()
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = st.EnsurePathLinkColumns()
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
defer database.Close()
|
||||||
if err := enrollExternalCampus(dataDir, st, enrollment); err != nil {
|
if err := enrollExternalCampus(dataDir, st, enrollment); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
st.BackgroundJobsDisabled = node != nil && !node.WorkersEnabled
|
st.BackgroundJobsDisabled = node != nil && !node.WorkersEnabled
|
||||||
if !st.BackgroundJobsDisabled {
|
err = serveInstance(ctx, dataDir, st, ":3000")
|
||||||
startManagedCampusReconciler(dataDir, st)
|
|
||||||
}
|
|
||||||
|
|
||||||
srv := server.New(st)
|
|
||||||
|
|
||||||
err = srv.Run(":3000")
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
"pageswiki/internal/dr"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func runPostgreSQLMigration(args []string, out io.Writer) error {
|
||||||
|
f := flag.NewFlagSet("migrate-postgres", flag.ContinueOnError)
|
||||||
|
f.SetOutput(out)
|
||||||
|
defaultDir := os.Getenv("PAGESWIKI_DATA_DIR")
|
||||||
|
if defaultDir == "" {
|
||||||
|
defaultDir = "./data"
|
||||||
|
}
|
||||||
|
dir := f.String("data-dir", defaultDir, "stopped instance data directory; existing files are retained in place")
|
||||||
|
apply := f.Bool("apply", false, "copy into an empty PostgreSQL schema after source preflight")
|
||||||
|
insecure := f.Bool("allow-insecure", false, "allow unverified PostgreSQL TLS for isolated testing only")
|
||||||
|
timeout := f.Duration("timeout", 30*time.Minute, "migration timeout")
|
||||||
|
if err := f.Parse(args); err != nil {
|
||||||
|
if errors.Is(err, flag.ErrHelp) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if f.NArg() != 0 || *timeout <= 0 {
|
||||||
|
return errors.New("invalid migration arguments")
|
||||||
|
}
|
||||||
|
if info, err := os.Stat(*dir); err != nil || !info.IsDir() {
|
||||||
|
return errors.New("existing data directory required")
|
||||||
|
}
|
||||||
|
lock, err := dr.Lock(*dir, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer lock.Close()
|
||||||
|
if node, err := dr.Load(*dir); err != nil {
|
||||||
|
return err
|
||||||
|
} else if node != nil {
|
||||||
|
return errors.New("PostgreSQL migration does not support a configured DR instance")
|
||||||
|
}
|
||||||
|
source, err := db.OpenReadOnly(filepath.Join(*dir, "pages.db"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer source.Close()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||||
|
defer cancel()
|
||||||
|
tables, err := store.InspectSQLiteApplicationImport(ctx, source)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !*apply {
|
||||||
|
return json.NewEncoder(out).Encode(map[string]any{"mode": "preflight", "tables": tables, "copied": false})
|
||||||
|
}
|
||||||
|
target, err := db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: os.Getenv("PAGESWIKI_POSTGRES_DSN"), AllowInsecure: *insecure})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer target.Close()
|
||||||
|
root := filepath.Join(*dir, "documents")
|
||||||
|
if err = store.PreparePostgreSQLImport(ctx, target, root); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
report, err := store.ImportSQLiteApplication(ctx, source, target, root)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return json.NewEncoder(out).Encode(report)
|
||||||
|
}
|
||||||
|
|
||||||
|
func configuredDatabaseBackend() (string, error) {
|
||||||
|
b := strings.ToLower(strings.TrimSpace(os.Getenv("PAGESWIKI_DB_BACKEND")))
|
||||||
|
switch b {
|
||||||
|
case "", "sqlite":
|
||||||
|
return "sqlite", nil
|
||||||
|
case "postgresql":
|
||||||
|
return b, nil
|
||||||
|
default:
|
||||||
|
return "", errors.New("PAGESWIKI_DB_BACKEND must be sqlite or postgresql")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func openApplicationStore(ctx context.Context, dataDir string) (database *sql.DB, st *store.Store, err error) {
|
||||||
|
backend, err := configuredDatabaseBackend()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if err != nil && database != nil {
|
||||||
|
database.Close()
|
||||||
|
database = nil
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if backend == "postgresql" {
|
||||||
|
database, err = db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: os.Getenv("PAGESWIKI_POSTGRES_DSN")})
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
root := filepath.Join(dataDir, "documents")
|
||||||
|
if err = store.VerifyPostgreSQLImport(ctx, database, root); err != nil {
|
||||||
|
return database, nil, err
|
||||||
|
}
|
||||||
|
st, err = store.NewPostgreSQLWithDocumentRoot(ctx, database, root)
|
||||||
|
return database, st, err
|
||||||
|
}
|
||||||
|
database, err = db.Open(filepath.Join(dataDir, "pages.db"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if err = db.Migrate(database); err != nil {
|
||||||
|
return database, nil, err
|
||||||
|
}
|
||||||
|
root, err := store.MigrateLegacyDocumentRoot(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return database, nil, err
|
||||||
|
}
|
||||||
|
st = store.NewWithDocumentRoot(database, root)
|
||||||
|
if err = st.EnsureConfigTable(); err != nil {
|
||||||
|
return database, nil, err
|
||||||
|
}
|
||||||
|
err = st.EnsurePathLinkColumns()
|
||||||
|
return database, st, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
"pageswiki/internal/dr"
|
||||||
|
"pageswiki/internal/server"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPostgreSQLMigrationAndTLSStartup(t *testing.T) {
|
||||||
|
dsn := os.Getenv("PAGESWIKI_TEST_POSTGRES_TLS_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("set a disposable PostgreSQL verify-full DSN")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
admin, err := db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: dsn})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
schema := "pageswiki_cli_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||||
|
if _, err = admin.Exec(`CREATE SCHEMA "` + schema + `"`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _, _ = admin.Exec(`DROP SCHEMA "` + schema + `" CASCADE`); admin.Close() })
|
||||||
|
u, err := url.Parse(dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
q := u.Query()
|
||||||
|
q.Set("search_path", schema)
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
t.Setenv("PAGESWIKI_POSTGRES_DSN", u.String())
|
||||||
|
t.Setenv("PAGESWIKI_AUTH_KEY", "")
|
||||||
|
dir := t.TempDir()
|
||||||
|
database, err := db.Open(filepath.Join(dir, "pages.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = db.Migrate(database); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s := store.NewWithDocumentRoot(database, filepath.Join(dir, "documents"))
|
||||||
|
if err = s.EnsureConfigTable(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
domain, err := s.GetDefaultDomain()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
owner, err := s.BootstrapOwner(domain.UUID, "owner", "synthetic cli password", "Owner", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, err := s.CreateAuthSession(domain.UUID, owner.UUID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = database.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err = runPostgreSQLMigration([]string{"--data-dir", dir, "--apply"}, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PAGESWIKI_DB_BACKEND", "postgresql")
|
||||||
|
t.Chdir("../..")
|
||||||
|
for range 2 {
|
||||||
|
database, native, err := openApplicationStore(ctx, dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got, err := native.PrincipalForSession(domain.UUID, token); err != nil || got.UUID != owner.UUID {
|
||||||
|
database.Close()
|
||||||
|
t.Fatal("session lost", err)
|
||||||
|
}
|
||||||
|
srv, err := server.NewChecked(native)
|
||||||
|
if err != nil {
|
||||||
|
database.Close()
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
closeCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||||
|
err = srv.Close(closeCtx)
|
||||||
|
cancel()
|
||||||
|
database.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostgreSQLMigrationPreflight(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
database, err := db.Open(filepath.Join(dir, "pages.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = db.Migrate(database); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s := store.NewWithDocumentRoot(database, filepath.Join(dir, "documents"))
|
||||||
|
if err = s.EnsureConfigTable(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = database.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// No target is needed for the schema-only preflight.
|
||||||
|
t.Setenv("PAGESWIKI_POSTGRES_DSN", "")
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err = runPostgreSQLMigration([]string{"--data-dir", dir}, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var result struct {
|
||||||
|
Mode string
|
||||||
|
Copied bool
|
||||||
|
Tables []string
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(out.Bytes(), &result); err != nil || result.Mode != "preflight" || result.Copied || len(result.Tables) < 130 {
|
||||||
|
t.Fatal(result, err)
|
||||||
|
}
|
||||||
|
lock, err := dr.Lock(dir, false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer lock.Close()
|
||||||
|
if err = runPostgreSQLMigration([]string{"--data-dir", dir}, &out); err == nil {
|
||||||
|
t.Fatal("active instance maintenance accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostgreSQLBackendRefusesFallback(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
for _, backend := range []string{"unsupported", "postgresql"} {
|
||||||
|
t.Setenv("PAGESWIKI_DB_BACKEND", backend)
|
||||||
|
t.Setenv("PAGESWIKI_POSTGRES_DSN", "")
|
||||||
|
if _, _, err := openApplicationStore(context.Background(), dir); err == nil {
|
||||||
|
t.Fatal("invalid configuration accepted")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "pages.db")); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("SQLite fallback created")
|
||||||
|
}
|
||||||
|
if err := runSchema([]string{"status", "--data-dir", dir}, &bytes.Buffer{}); err == nil {
|
||||||
|
t.Fatal("legacy inspection accepted")
|
||||||
|
}
|
||||||
|
if err := runDR([]string{"init", "--data-dir", dir}, &bytes.Buffer{}); err == nil {
|
||||||
|
t.Fatal("legacy DR accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostgreSQLMigrationArguments(t *testing.T) {
|
||||||
|
for _, args := range [][]string{{"--timeout", "0"}, {"unexpected"}, {"--data-dir", filepath.Join(t.TempDir(), "missing")}} {
|
||||||
|
if err := runPostgreSQLMigration(args, &bytes.Buffer{}); err == nil {
|
||||||
|
t.Fatal("invalid arguments accepted", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
-2
@@ -12,19 +12,28 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"pageswiki/internal/db"
|
"pageswiki/internal/db"
|
||||||
|
"pageswiki/internal/metadata"
|
||||||
"pageswiki/internal/store"
|
"pageswiki/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
var errSchemaPending = errors.New("schema migrations are pending; no changes were applied")
|
var errSchemaPending = errors.New("schema migrations are pending; no changes were applied")
|
||||||
var errSchemaBlocked = errors.New("schema history or contract is incompatible; no changes were applied")
|
var errSchemaBlocked = errors.New("schema history or contract is incompatible; no changes were applied")
|
||||||
|
var errPostgreSQLNotReady = errors.New("core-only inspection cannot certify application migration; use migrate-postgres; no changes were applied")
|
||||||
|
|
||||||
func runSchema(args []string, out io.Writer) error {
|
func runSchema(args []string, out io.Writer) error {
|
||||||
const usage = "pageswiki schema {status|check} [--db FILE | --data-dir DIR] [--json] [--timeout 30s]\nRead-only inspection of managed components; legacy migrations and pending DDL are not rehearsed.\ncheck exits 2 for pending migrations, 1 for incompatible state, 0 when managed components are current."
|
backend, err := configuredDatabaseBackend()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if backend != "sqlite" {
|
||||||
|
return errors.New("legacy schema inspection requires SQLite; PostgreSQL startup validates native migrations and import receipt")
|
||||||
|
}
|
||||||
|
const usage = "pageswiki schema {status|check|portability} [--db FILE | --data-dir DIR] [--json] [--timeout 30s]\nRead-only inspection; no migration is performed.\ncheck exits 2 for pending migrations, 1 for incompatible state, 0 when managed components are current.\nportability reports PostgreSQL migration blockers and exits 1 while full application support is incomplete."
|
||||||
if len(args) == 0 || args[0] == "--help" {
|
if len(args) == 0 || args[0] == "--help" {
|
||||||
_, err := fmt.Fprintln(out, usage)
|
_, err := fmt.Fprintln(out, usage)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if args[0] != "status" && args[0] != "check" {
|
if args[0] != "status" && args[0] != "check" && args[0] != "portability" {
|
||||||
return errors.New(usage)
|
return errors.New(usage)
|
||||||
}
|
}
|
||||||
f := flag.NewFlagSet("schema "+args[0], flag.ContinueOnError)
|
f := flag.NewFlagSet("schema "+args[0], flag.ContinueOnError)
|
||||||
@@ -65,6 +74,46 @@ func runSchema(args []string, out io.Writer) error {
|
|||||||
defer database.Close()
|
defer database.Close()
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
if args[0] == "portability" {
|
||||||
|
repository, err := metadata.New(database, metadata.SQLite)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
report, err := repository.InspectPortability(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if *jsonOutput {
|
||||||
|
encoder := json.NewEncoder(out)
|
||||||
|
encoder.SetIndent("", " ")
|
||||||
|
if err := encoder.Encode(report); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if _, err := fmt.Fprintf(out, "PostgreSQL application ready: %t\nPortable core rehearsal compatible: %t\nScope: %s\n", report.ApplicationReady, report.CoreCompatible, report.Scope); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, table := range report.Tables {
|
||||||
|
if _, err := fmt.Fprintf(out, "%-28s %-20s %s\n", table.Name, table.Component, table.State); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, blocker := range report.Blockers {
|
||||||
|
if _, err := fmt.Fprintln(out, "blocked:", blocker); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !report.ApplicationReady {
|
||||||
|
if _, err := fmt.Fprintln(out, "This legacy diagnostic covers core rehearsal only. Use migrate-postgres for full application preflight and transfer."); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !report.ApplicationReady {
|
||||||
|
return errPostgreSQLNotReady
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
report, err := store.InspectSchema(ctx, database)
|
report, err := store.InspectSchema(ctx, database)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -9,9 +9,60 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"pageswiki/internal/db"
|
"pageswiki/internal/db"
|
||||||
|
"pageswiki/internal/metadata"
|
||||||
"pageswiki/internal/store"
|
"pageswiki/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestPortabilityCommandIsReadOnlyAndNeverClaimsApplicationReady(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
database, err := db.Open(filepath.Join(dir, "pages.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
if err := db.Migrate(database); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
st := store.NewWithDocumentRoot(database, filepath.Join(dir, "documents"))
|
||||||
|
if _, err := st.CreatePageAtPath("/preserved"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := database.Exec(`CREATE TABLE private_extension_data(secret TEXT); INSERT INTO private_extension_data VALUES ('DO_NOT_PRINT_PRIVATE_VALUE')`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err := runSchema([]string{"portability", "--db", filepath.Join(dir, "pages.db"), "--json"}, &out); !errors.Is(err, errPostgreSQLNotReady) {
|
||||||
|
t.Fatal("unsafe readiness result", err)
|
||||||
|
}
|
||||||
|
var report metadata.PortabilityReport
|
||||||
|
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if report.ApplicationReady || report.CoreCompatible || len(report.Blockers) == 0 {
|
||||||
|
t.Fatal("legacy application marked portable", report)
|
||||||
|
}
|
||||||
|
if bytes.Contains(out.Bytes(), []byte("DO_NOT_PRINT_PRIVATE_VALUE")) {
|
||||||
|
t.Fatal("row values leaked")
|
||||||
|
}
|
||||||
|
if _, err := st.ResolvePath("/preserved"); err != nil {
|
||||||
|
t.Fatal("inspection changed existing data", err)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := database.QueryRow(`SELECT count(*) FROM schema_migration_steps WHERE component='core-metadata'`).Scan(&count); err != nil || count != 0 {
|
||||||
|
t.Fatal("inspection migrated database", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPortabilityCommandMissingDatabaseDoesNotCreateFiles(t *testing.T) {
|
||||||
|
dir := filepath.Join(t.TempDir(), "not-created")
|
||||||
|
if err := runSchema([]string{"portability", "--data-dir", dir}, &bytes.Buffer{}); err == nil {
|
||||||
|
t.Fatal("nonexistent DB accepted")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatal("directory created", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestSchemaCommandMissingDatabaseDoesNotInitialize(t *testing.T) {
|
func TestSchemaCommandMissingDatabaseDoesNotInitialize(t *testing.T) {
|
||||||
dir := filepath.Join(t.TempDir(), "missing")
|
dir := filepath.Join(t.TempDir(), "missing")
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"pageswiki/internal/server"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Let an in-flight federation reconciliation finish before releasing the
|
||||||
|
// event-worker owner. Each remote request retains its existing network timeout;
|
||||||
|
// cancellation prevents starting another campus or reconciliation pass.
|
||||||
|
func serveInstance(ctx context.Context, dataDir string, st *store.Store, addr string) error {
|
||||||
|
srv, err := server.NewChecked(st)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reconcileCtx, stopReconciler := context.WithCancel(ctx)
|
||||||
|
reconcilerDone := startManagedCampusReconciler(reconcileCtx, dataDir, st)
|
||||||
|
serveCtx, stopServer := context.WithCancel(context.Background())
|
||||||
|
finished := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
<-reconcilerDone
|
||||||
|
stopServer()
|
||||||
|
case <-finished:
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
err = srv.RunContext(serveCtx, addr)
|
||||||
|
stopReconciler()
|
||||||
|
<-reconcilerDone
|
||||||
|
close(finished)
|
||||||
|
stopServer()
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestServeInstanceCancelled(t *testing.T) {
|
||||||
|
t.Chdir("../..")
|
||||||
|
t.Setenv("PAGESWIKI_INSTANCE_FQDN", "")
|
||||||
|
root := t.TempDir()
|
||||||
|
database, err := db.Open(root + "/pages.db")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
if err = db.Migrate(database); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
st := store.NewWithDocumentRoot(database, root+"/documents")
|
||||||
|
if err = st.EnsureConfigTable(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
st.BackgroundJobsDisabled = true
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if err = serveInstance(ctx, root, st, "127.0.0.1:0"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = database.Ping(); err != nil {
|
||||||
|
t.Fatal("server closed caller-owned DB", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestManagedReconcilerCancellationBeforeFirstPass(t *testing.T) {
|
||||||
|
t.Setenv("PAGESWIKI_INSTANCE_FQDN", "synthetic.invalid")
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
// No DB: cancellation must finish without attempting a repository read or
|
||||||
|
// accessing an external campus. This test does not make a network request.
|
||||||
|
done := startManagedCampusReconciler(ctx, t.TempDir(), &store.Store{})
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("reconciler did not stop")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -312,6 +312,9 @@ class PagesWikiCLI:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
|
backend = os.environ.get("PAGESWIKI_DB_BACKEND", "sqlite").strip().lower() or "sqlite"
|
||||||
|
if backend != "sqlite":
|
||||||
|
raise CLIError("Local data CLI requires SQLite; use the HTTP pages-cli for PostgreSQL")
|
||||||
script_dir = Path(__file__).resolve().parent
|
script_dir = Path(__file__).resolve().parent
|
||||||
self.data_dir = Path(
|
self.data_dir = Path(
|
||||||
os.environ.get("PAGESWIKI_DATA_DIR", script_dir)
|
os.environ.get("PAGESWIKI_DATA_DIR", script_dir)
|
||||||
|
|||||||
@@ -10,6 +10,11 @@ from pageswiki_cli_test import pageswiki_cli
|
|||||||
|
|
||||||
|
|
||||||
class DRGuardTest(unittest.TestCase):
|
class DRGuardTest(unittest.TestCase):
|
||||||
|
def test_postgresql_rejected_before_database_open(self):
|
||||||
|
with patch.dict(os.environ, {"PAGESWIKI_DB_BACKEND": "postgresql"}):
|
||||||
|
with self.assertRaisesRegex(pageswiki_cli.CLIError, "HTTP pages-cli"):
|
||||||
|
pageswiki_cli.PagesWikiCLI()
|
||||||
|
|
||||||
def test_standby_rejected_before_database_open(self):
|
def test_standby_rejected_before_database_open(self):
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
root = Path(directory)
|
root = Path(directory)
|
||||||
|
|||||||
@@ -14,12 +14,12 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile.gecko-relay
|
dockerfile: Dockerfile.gecko-relay
|
||||||
image: pageswiki-gecko-relay:dev
|
image: ${PAGESWIKI_GECKO_IMAGE:-pageswiki-gecko-relay:dev}
|
||||||
environment:
|
environment:
|
||||||
PAGESWIKI_GECKO_KEY_FILE: /run/secrets/gecko-key
|
PAGESWIKI_GECKO_KEY_FILE: /run/secrets/gecko-key
|
||||||
volumes:
|
volumes:
|
||||||
- ${PAGESWIKI_GECKO_KEY_PATH:?Set absolute relay key path}:/run/secrets/gecko-key:ro
|
- ${PAGESWIKI_GECKO_KEY_PATH:?Set absolute relay key path}:/run/secrets/gecko-key:ro
|
||||||
- ${PAGESWIKI_GECKO_ASSETS_DIR:?Set verified Gecko dist directory}:/gecko:ro
|
- ${PAGESWIKI_GECKO_ASSETS_DIR:?Set verified complete Gecko bundle directory}:/gecko:ro
|
||||||
networks:
|
networks:
|
||||||
gecko-front: {}
|
gecko-front: {}
|
||||||
gecko-egress: {}
|
gecko-egress: {}
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: pageswiki-app:task-index-20261109
|
||||||
|
app2:
|
||||||
|
image: pageswiki-app:task-index-20261109
|
||||||
@@ -55,7 +55,12 @@
|
|||||||
- `POST /_/api/v1/editor/convert`:作業中 HTML を安全な authoring Markdown に変換。
|
- `POST /_/api/v1/editor/convert`:作業中 HTML を安全な authoring Markdown に変換。
|
||||||
`POST /_/api/v1/render/markdown` の `authoring:true` で保護フェンスを元の HTML に戻す。
|
`POST /_/api/v1/render/markdown` の `authoring:true` で保護フェンスを元の HTML に戻す。
|
||||||
`projection:true` と併用したプレビューでは従来の sanitizer・macro 展開を適用する。
|
`projection:true` と併用したプレビューでは従来の sanitizer・macro 展開を適用する。
|
||||||
- 変換できない HTML は文書全体を保護する保守的な実装。フェンスは
|
- 2026-11-09から、全体変換が構造を保てない場合はbody直下のブロック単位に変換する。
|
||||||
|
往復で構造が一致する見出し・段落・リスト等はMarkdownへ戻し、不一致のブロックだけを保護する。
|
||||||
|
再結合後も文書全体を比較し、head内要素等を失う場合は全文保護へ戻す。
|
||||||
|
保護ブロックはDOM再シリアライズを避け、原文の引用符・タグ表記をそのまま保持する。
|
||||||
|
分割は最大1024区間。省略終了タグ等で境界を確定できない場合も全文保護へ戻す。
|
||||||
|
リスト・表の構造要素間の空白は比較時に正規化し、インラインの単語境界やコード内空白は保持する。フェンスは
|
||||||
`` ```{=html} `` 形式(本文にバッククォートがある場合はそれより長い区切り)。
|
`` ```{=html} `` 形式(本文にバッククォートがある場合はそれより長い区切り)。
|
||||||
任意の属性、コメント、未知要素、表の結合、画像キャプション、コード内空白を保持。
|
任意の属性、コメント、未知要素、表の結合、画像キャプション、コード内空白を保持。
|
||||||
フェンス内を編集でき、外側に Markdown を追記できる。通常のコードフェンス内にある
|
フェンス内を編集でき、外側に Markdown を追記できる。通常のコードフェンス内にある
|
||||||
@@ -70,7 +75,7 @@
|
|||||||
- `+` は挿入・下書き、`文` は言語の編集・分岐、`↶` は旧リビジョンを作業バッファへ
|
- `+` は挿入・下書き、`文` は言語の編集・分岐、`↶` は旧リビジョンを作業バッファへ
|
||||||
読み込む。復元は明示保存で新 Revision を追加し、旧 Revision を書き換えない。
|
読み込む。復元は明示保存で新 Revision を追加し、旧 Revision を書き換えない。
|
||||||
履歴は50件ずつ追加取得し、現在言語で絞り込む。分岐は翻訳生成ではなく本文のコピー。
|
履歴は50件ずつ追加取得し、現在言語で絞り込む。分岐は翻訳生成ではなく本文のコピー。
|
||||||
- 挿入は子ページ・表・画像キャプション・補足・コード・引用の6種の初期パレット。
|
- 挿入は子ページ・表・画像キャプション・補足・コード・引用・CSV macroの初期パレット。
|
||||||
画像 URL 等のプレースホルダーは編集が必要。ファイルピッカー、図形・外部 widget の
|
画像 URL 等のプレースホルダーは編集が必要。ファイルピッカー、図形・外部 widget の
|
||||||
パラメータ編集、プラグインによる挿入パーツ登録は既存の HTML editor 設計に残る。
|
パラメータ編集、プラグインによる挿入パーツ登録は既存の HTML editor 設計に残る。
|
||||||
- touch/coarse pointer + hover 不可の端末ではデスクトップの Vim 設定を上書きせず、
|
- touch/coarse pointer + hover 不可の端末ではデスクトップの Vim 設定を上書きせず、
|
||||||
@@ -78,11 +83,13 @@
|
|||||||
|
|
||||||
## 次段階の実装順序
|
## 次段階の実装順序
|
||||||
|
|
||||||
|
CSVの表編集は既存保存・下書き・履歴の契約へ接続済みです。CSVはHTML変換と文字列自動マージを行わず、競合時は比較して採否を決めます。BOMと混在改行を保持するため、CSV初期値はHTMLのtextarea解析を通さず安全なJS文字列として渡し、CodeMirrorはLFのみで分割します。初期フォーカスの遅延処理も、表セルなどへ移ったフォーカスを奪いません。詳細な上限と残件は[表設計](extensions.md)を参照してください。
|
||||||
|
|
||||||
1. **E6a presence**:編集中リースの共有ストアと認可付き API、別端末を含む表示。
|
1. **E6a presence**:編集中リースの共有ストアと認可付き API、別端末を含む表示。
|
||||||
管理者にだけ見える監視ではなく、同じ Page/language を編集できる参加者に限定する。
|
管理者にだけ見える監視ではなく、同じ Page/language を編集できる参加者に限定する。
|
||||||
2. **E6b realtime**:下記 CRDT 詳細設計・採用ライブラリ・同時変換ルールを確定した後に
|
2. **E6b realtime**:下記 CRDT 詳細設計・採用ライブラリ・同時変換ルールを確定した後に
|
||||||
feature flag 付きで実装。現時点の CAS を最終コミット時の保護として残す。
|
feature flag 付きで実装。現時点の CAS を最終コミット時の保護として残す。
|
||||||
3. **E5b / E3b**:HTML ブロック単位の保護、hosted editor/CLI への保護フェンス対応、
|
3. **E5b / E3b**:入れ子コンポーネント内のより細粒度なMarkdown復元、hosted editor/CLI への保護フェンス対応、
|
||||||
アセットピッカーと拡張挿入パーツ。通常の Markdown だけを扱う外部エディタへ
|
アセットピッカーと拡張挿入パーツ。通常の Markdown だけを扱う外部エディタへ
|
||||||
このフェンスを無断で渡さない。既存の外部エディタ変換経路は本変更の対象外。
|
このフェンスを無断で渡さない。既存の外部エディタ変換経路は本変更の対象外。
|
||||||
4. 保存 API の旧クライアント移行と base 必須化、下書き大容量化・明示破棄 UX、
|
4. 保存 API の旧クライアント移行と base 必須化、下書き大容量化・明示破棄 UX、
|
||||||
|
|||||||
@@ -48,11 +48,25 @@ IPアドレス管理(IPAM)、DNSゾーン/レコード管理、機器・
|
|||||||
|
|
||||||
## CSV/表・スライド拡張(設計TODO)
|
## CSV/表・スライド拡張(設計TODO)
|
||||||
|
|
||||||
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影するmacroを用意します。候補構文は `{{csv:/data/items.csv range=A1:H200 header=true}}` とし、Path、Revision(またはasset hash)、列・行上限、表示モードを正規化してキャッシュキーに含めます。macroは表示時にboundedなProjectionを作るだけで、結果HTMLを正本へ逆流させません。CSV Editorは元Revisionを編集し、表投影とは別の操作・競合・権限として扱います。
|
初期CSV macroは実装済みです。`{{csv:/data/items.csv range=A1:H200 header=true}}` を認証済みProjectionで展開し、`rev=` で同じObjectのRevisionへ固定できます。現在のPath閲覧権限を毎回検査し、外部URL、匿名公開、asset指定、共有キャッシュはこの段階に含めません。入力256 KiB・UTF-8、表示200行×32列、走査2,000行・100列、セル16 KiB、Projection当たり4種類のCSVまでに制限します。引用符・改行・BOMに対応し、セルはHTML escapeしてmacroや数式を実行しません。処理不能時は内容を漏らさない警告に置き換えます。Authoringでは元のmacroを保持します。
|
||||||
|
|
||||||
|
既存CSVの編集は `/e/-/{path}` の組み込みエディタで行います。デスクトップはソースと表を並べ、700px以下では表を全幅表示してソースへ切り替えます。セル編集、行・列追加/削除、20操作までの表のUndo/Redoに対応。表は200行・32列・セル16 KiB以内を25行ずつ描画し、先頭行を自動でヘッダ扱いしません。矩形でない行の欠落セルは表示だけでは補わず、列追加・貼り付けで必要になった部分だけ空セルを補います。全体256 KiB・UTF-8以内を対象とし、超過・不正形式の表を部分編集可能にして保存することはありません。表上限を超えても全体上限内ならソースで編集できます。
|
||||||
|
|
||||||
|
表計算ソフトからの複数セル貼り付けは、フォーカス中のセルを左上として反映します。クリップボードの `text/plain` にタブまたは改行があればタブ区切り表として解析し、引用符内の改行・タブ・二重引用符を保持します。カンマは列区切りにせずセル値として扱い、単一行の通常テキストはセル内への貼り付けです。複数行を一つのセルへ貼る場合は引用符で囲むかソースを編集します。HTML形式のクリップボードは使いません。必要な行・セルの拡張を含めて1操作でUndo/Redoでき、構文・行列・セル・変換後CSV全体の上限を検査してから一括反映します。失敗時は部分反映せず、既存のUndo履歴も変更しません。貼り付け範囲外のセルと改行形式は維持します。
|
||||||
|
|
||||||
|
CSV正本をHTMLへ変換せず、未変更fieldの引用符、BOM、混在LF/CRLFを保持します。セル内のHTML、macro、数式は実行しません。表編集も既存の下書き・認証切れ検出・言語別Revision CAS・履歴復元を使用し、他の保存と競合したCSVは文字列の自動マージをせず比較画面へ送ります。原文と編集済み表の両方を別正本として保存しません。DBスキーマ変更はありません。CSV新規作成ウィザード、TSVファイル/文字コード変換、大容量表のwindow編集、矩形選択/範囲コピー、列型/数式、ODSは残件です。
|
||||||
|
|
||||||
|
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影します。共有キャッシュを将来追加する際は、Path、Revision(またはasset hash)、列・行上限、表示モードと権限を考慮します。macroは表示時にboundedなProjectionを作るだけで、結果HTMLを正本へ逆流させません。CSV Editorは元Revisionを編集し、表投影とは別の操作・競合・権限として扱います。
|
||||||
|
|
||||||
交換形式はRFC 4180互換CSV(UTF-8、CRLF、引用符・改行を含むfield、BOMの扱いを明示)を第一正本とします。複数シート、型、数式、結合セル、書式が必要な場合はODSを別アダプタ/Assetとして扱い、CSVへの不可逆変換を黙って行いません。行数、列数、セル長、総バイト、ネストmacroを制限し、malformed inputは安全なテキスト表示へfallbackします。
|
交換形式はRFC 4180互換CSV(UTF-8、CRLF、引用符・改行を含むfield、BOMの扱いを明示)を第一正本とします。複数シート、型、数式、結合セル、書式が必要な場合はODSを別アダプタ/Assetとして扱い、CSVへの不可逆変換を黙って行いません。行数、列数、セル長、総バイト、ネストmacroを制限し、malformed inputは安全なテキスト表示へfallbackします。
|
||||||
|
|
||||||
スライドは、Markdown/HTMLの正本からReveal.js互換のProjectionを生成する連携アダプタを設けます。HedgeDoc、Slidevは外部originのホスト型アダプタとして、保存・公開・ユーザー情報をPages Wikiの権限へ自動昇格させず、read-only preview→明示的なimport/saveの順にします。JSを使用できない環境向けには、CSS scroll-snap/`:target`/print CSSだけでページ送りできるCSS-only Slide Editorを別実装します。外部ランタイム停止時は静的HTML/Markdownへ安全にfallbackし、任意script、remote import、iframe権限を本文から許可しません。
|
スライドはローカル同梱のReveal.js 6.0.2で表示します。`/v/slides/{path}` は通常のPath閲覧権限でHTML/Markdownの最新Revisionを取得し、HTMLページのスライドアイコンや「連携アダプタで開く」から移動できます。組み込みHTML/Markdownエディタのスライドアイコンは、未保存の本文を通常プレビューと同じ変換経路で投影します。表示DOMを保存せず、保存・下書き・競合処理は既存エディタに任せます。Markdownの空行で囲んだ `---`、HTMLの直下の `<hr>` が横方向の区切りで、直下の `<section>` も1枚として扱います。コードブロック内の区切りは分割しません。
|
||||||
|
|
||||||
|
Reveal実行は `allow-scripts allow-popups` のsandbox iframeに隔離し、`allow-same-origin` は付けません。本文のscript・CSS・iframe・フォーム・任意data属性を渡さず、独自プラグインや外部Markdownを読み込みません。画像は同一originだけ、リンクはHTTP(S)だけです。矢印キー・タッチ・画面内コントロールで移動し、履歴やURL hashを変更しません。ビューアは全画面に対応し、背景・文字色はテーマから引き継ぎます。ライブラリ読込失敗時は静的なサニタイズ済み本文へfallbackします。本文256 KiB・100枚・DOM 10,000ノード/深さ64を上限とし、常時バックグラウンド生成や共有キャッシュは持ちません。`viewer.slides` は拡張設定でドメイン単位に停止でき、停止後のページではビューア・編集切替・アダプタ候補を表示しません。MITライセンス・固定版・配布元・hashは `static/vendor/reveal/` に同梱します。DBスキーマ変更はありません。
|
||||||
|
|
||||||
|
700px以下の編集画面ではスライドプレビューを全幅表示し、既存のプレビュー非表示ボタンでソースへ戻ります。小画面で自動スクロール形式に変わらないよう `scrollActivationWidth: null` を指定します([Reveal.js公式仕様](https://revealjs.com/scroll-view/))。
|
||||||
|
|
||||||
|
縦方向のスライド、fragments、発表者ノート、macroの非同期展開、スライド専用印刷、外部画像の承認連携は残件です。HedgeDoc、Slidevは外部originのホスト型アダプタとして、保存・公開・ユーザー情報をPages Wikiの権限へ自動昇格させず、read-only preview→明示的なimport/saveの順にします。JSを使用できない環境向けには、CSS scroll-snap/`:target`/print CSSだけでページ送りできるCSS-only Slide Editorを別実装します。
|
||||||
|
|
||||||
ネットワーク図ではnwdiagを追加候補とします。ソースをbounded parserで検証し、renderer version/theme/document hashをキーに静的SVGをキュー生成します。include、外部画像・font、未知directive、危険なSVG属性は拒否し、renderer停止時はescaped sourceまたは最後に検証済みの静的画像へfallbackします。編集アダプタの保存はone-use ticketと楽観的Revision競合を使い、Kroki経由の場合もorigin、timeout、quotaを明示します。
|
ネットワーク図ではnwdiagを追加候補とします。ソースをbounded parserで検証し、renderer version/theme/document hashをキーに静的SVGをキュー生成します。include、外部画像・font、未知directive、危険なSVG属性は拒否し、renderer停止時はescaped sourceまたは最後に検証済みの静的画像へfallbackします。編集アダプタの保存はone-use ticketと楽観的Revision競合を使い、Kroki経由の場合もorigin、timeout、quotaを明示します。
|
||||||
|
|
||||||
|
|||||||
@@ -396,11 +396,13 @@ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。
|
|||||||
- [x] RSS-7c:Shift+j/kによるフォルダ選択。空・未分類・端・購読選択中・検索維持・入力/モーダル抑止・連打を合成試験。
|
- [x] RSS-7c:Shift+j/kによるフォルダ選択。空・未分類・端・購読選択中・検索維持・入力/モーダル抑止・連打を合成試験。
|
||||||
- [x] RSS-8a:Gecko端末描画+自前Wisp中継の方式決定。公開中継を使わず、独立・既定無効で導入する。
|
- [x] RSS-8a:Gecko端末描画+自前Wisp中継の方式決定。公開中継を使わず、独立・既定無効で導入する。
|
||||||
- [x] RSS-8b1:upstream v0.0.1/hash固定、最小埋め込みと親documentのisolation、Chromiumで合成記事の描画・遷移確認。
|
- [x] RSS-8b1:upstream v0.0.1/hash固定、最小埋め込みと親documentのisolation、Chromiumで合成記事の描画・遷移確認。
|
||||||
- [ ] RSS-8b2:Safari/iPhone SE実機、IME・コピー・find・証明書エラー・HTTPS互換性、配布license/notice整備。
|
- [ ] RSS-8b2:Safari/iPhone SE実機、IME・コピー・実サイト互換性。固定配布物のlicense/notice整備、HTTPSと証明書エラー、日本語findの合成試験は実施済み。
|
||||||
- [x] RSS-8c1:認証付きWisp TCP profile、公開IP/port制限、失効・資源上限・管理者/CLI無効化・内部status。
|
- [x] RSS-8c1:認証付きWisp TCP profile、公開IP/port制限、失効・資源上限・管理者/CLI無効化・内部status。
|
||||||
- [ ] RSS-8c2:運用ホストの外向きfirewall、設定UIへの中継監視統合、負荷時の長時間受入。
|
- [ ] RSS-8c2:運用ホストの外向きfirewall、設定UIへの中継監視統合、負荷時の長時間受入。
|
||||||
- [x] RSS-8d1:個人設定の選択、1ページのpopup閲覧、戻る/進む/再読込/別タブ/終了。
|
- [x] RSS-8d1:個人設定の選択、1ページのpopup閲覧、戻る/進む/再読込/別タブ/終了。
|
||||||
- [ ] RSS-8d2:初回/再表示・低メモリ端末の性能評価、失敗/切断・複数タブのUX、本番配備。
|
- [ ] RSS-8d2:初回/再表示・低メモリ端末の性能評価、実行中の切断・複数タブのUX、本番配備。起動上限と起動失敗時のiframe破棄・原文リンクへの退避は実装済み。
|
||||||
|
|
||||||
|
一覧には配信日と配信時刻(HH:mm)を分けて表示します。Domainの設定タイムゾーンを使い、tooltipには年・秒・タイムゾーンを含めます。配信日時不明は「—」とし、取得日時で補いません。モバイルでも時刻欄を残します。
|
||||||
|
|
||||||
隔離試験はRSS/Atom・FreshRSS login/read、欠落ID・巨大/不正feed、条件付きGET、失敗時cache保持、
|
隔離試験はRSS/Atom・FreshRSS login/read、欠落ID・巨大/不正feed、条件付きGET、失敗時cache保持、
|
||||||
本人分離・失効・readonly、二重送信・版競合・旧worker拒否、migration再実行/失敗rollback、
|
本人分離・失効・readonly、二重送信・版競合・旧worker拒否、migration再実行/失敗rollback、
|
||||||
|
|||||||
@@ -103,15 +103,15 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
|
|||||||
| SHARE-01 / P2 | 未実装:委譲share URL、期限/失効/監査、説明可能な権限総覧 | AUTH-01、PUB-01。login/adapter/federation資格情報と別目的、単一Page投影、caveat・依存物の失効を検証 | [公開](publication.md)、[Schutzaria](schutzaria.md) |
|
| SHARE-01 / P2 | 未実装:委譲share URL、期限/失効/監査、説明可能な権限総覧 | AUTH-01、PUB-01。login/adapter/federation資格情報と別目的、単一Page投影、caveat・依存物の失効を検証 | [公開](publication.md)、[Schutzaria](schutzaria.md) |
|
||||||
| COLLAB-01 / P2 | 一部実装:Page等の変更購読、最近閲覧/編集、集約通知。コメント/反応/評価は未実装 | OUT-01。現在権限で再投影、private履歴のopt-in/保持。inline commentはRevision変更時の孤立・再接続を扱う | [拡張](extensions.md) |
|
| COLLAB-01 / P2 | 一部実装:Page等の変更購読、最近閲覧/編集、集約通知。コメント/反応/評価は未実装 | OUT-01。現在権限で再投影、private履歴のopt-in/保持。inline commentはRevision変更時の孤立・再接続を扱う | [拡張](extensions.md) |
|
||||||
| BLOG-01 / P2 | 一部実装:安全なtDiary import、最近コメント、遠隔ブログ射影 | COLLAB-01、遠隔はFED-01。importは再開/重複抑止/dry-run。同一instance射影を再実装しない | [ブログ・日記](blog-diary.md) |
|
| BLOG-01 / P2 | 一部実装:安全なtDiary import、最近コメント、遠隔ブログ射影 | COLLAB-01、遠隔はFED-01。importは再開/重複抑止/dry-run。同一instance射影を再実装しない | [ブログ・日記](blog-diary.md) |
|
||||||
| CSV-01 / P2 | viewerのみ実装:別Documentを投影するCSV macro/editor、ODS境界 | 行列・セル・総量上限、Revision固定、権限、CSV引用/改行fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
|
| CSV-01 / P2 | viewer・有界CSV macro・既存CSVの表編集/複数セル貼り付けを実装。残件:新規作成UI、大容量編集、矩形選択/範囲コピー、匿名投影、asset指定、ODS境界 | BOM/改行保持、25行描画、行列・セル・総量上限、貼り付けの一括検証/Undo、Revision CAS、権限、競合確認/履歴復元fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
|
||||||
| DIAGRAM-01 / P2 | 一部実装:nwdiag/Draw.io provider、slide preview/editor | RENDER-01。安全なSVG・include拒否・renderer版固定、ticket/CAS保存、print。既存Excalidraw/Krokiとは分ける | [Kunstzeal](kunstzeal.md) |
|
| DIAGRAM-01 / P2 | Reveal.jsビューア/編集プレビューを実装。残件:nwdiag/Draw.io provider、縦スライド・notes・専用print | RENDER-01。有界入力、sandbox、固定版ローカル同梱、ドメイン単位停止、Path認可。SVG・include拒否・ticket/CAS保存はprovider別に検証 | [Kunstzeal](kunstzeal.md)、[スライド](extensions.md) |
|
||||||
| RECIPE-01 / P2 | 未実装:構造化レシピmetadataとPage投影の初期slice | 材料・数量・未知単位を保持、人数変更は派生値、Asset認可、版競合、出典・公開確認 | [料理レシピ](recipe-management.md) |
|
| RECIPE-01 / P2 | 未実装:構造化レシピmetadataとPage投影の初期slice | 材料・数量・未知単位を保持、人数変更は派生値、Asset認可、版競合、出典・公開確認 | [料理レシピ](recipe-management.md) |
|
||||||
|
|
||||||
## D. 選定・別サブプロジェクト
|
## D. 選定・別サブプロジェクト
|
||||||
|
|
||||||
| ID / 優先 | 状態・次の作業 | 着手ゲート・最初の検証 | 詳細 |
|
| ID / 優先 | 状態・次の作業 | 着手ゲート・最初の検証 | 詳細 |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| RSS-01 / P2 | 一部実装:内蔵簡易正本、FreshRSS読取connector、3ペインUI・HTML本文、Wiki保存・タスク化・dashboard、OPML確認付き入出力 | 残件はFreshRSS既読/star書戻し、購読/カテゴリnavigation、実接続受入、公平性/backoff。managed schema feeds v3・隔離fixture。本番未反映。二重正本・停止時の自動切替なし | [RSS](feeds.md) |
|
| RSS-01 / P2 | 一部実装:内蔵簡易正本、FreshRSS読取・既読/star書戻し、購読/カテゴリnavigation、3ペインUI・HTML本文、Wiki保存・タスク化・dashboard、OPML、配信時刻 | 残件は実接続受入、公平性/backoff、Gecko実機・運用受入。個別の実装/受入状況はRSS設計を参照。二重正本・停止時の自動切替なし | [RSS](feeds.md) |
|
||||||
| IMAP-01 / P3 | 未実装・選定待ち:IMAP読取同期 | provider/認証/保持を決める。UIDVALIDITY/UID、添付量、外部画像、失効をfixture化。neomutt captureは実装済みで別 | [メール](mail.md) |
|
| IMAP-01 / P3 | 未実装・選定待ち:IMAP読取同期 | provider/認証/保持を決める。UIDVALIDITY/UID、添付量、外部画像、失効をfixture化。neomutt captureは実装済みで別 | [メール](mail.md) |
|
||||||
| TICKET-01 / P3 | 未実装:queue/番号/workflow/外部依頼者 | 共有範囲と状態遷移を定義、同時採番・失効・監査。既存個人タスクをticketと呼び替えない | [タスクとticket](tasks-tickets.md) |
|
| TICKET-01 / P3 | 未実装:queue/番号/workflow/外部依頼者 | 共有範囲と状態遷移を定義、同時採番・失効・監査。既存個人タスクをticketと呼び替えない | [タスクとticket](tasks-tickets.md) |
|
||||||
| EXT-01 / P3 | built-inのみ:第三者manifest/署名/隔離runtime、停止・rollback・観測 | capability・secret・host・予算・export契約。任意コードをGoプロセス内へ直接ロードしない | [拡張](extensions.md) |
|
| EXT-01 / P3 | built-inのみ:第三者manifest/署名/隔離runtime、停止・rollback・観測 | capability・secret・host・予算・export契約。任意コードをGoプロセス内へ直接ロードしない | [拡張](extensions.md) |
|
||||||
@@ -126,7 +126,7 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
|
|||||||
- **HOLD-01**:`/tasks/` 配下のメールWikiルーティング調査。利用者の棚上げ指定を維持。関連未コミットファイルを今回の実装・文書コミットへ混ぜない。
|
- **HOLD-01**:`/tasks/` 配下のメールWikiルーティング調査。利用者の棚上げ指定を維持。関連未コミットファイルを今回の実装・文書コミットへ混ぜない。
|
||||||
- **HOLD-02**:vim.wasm runtime改善とnativeアプリ起動。既存設定UIは残すが、自動的に再開しない。
|
- **HOLD-02**:vim.wasm runtime改善とnativeアプリ起動。既存設定UIは残すが、自動的に再開しない。
|
||||||
- **HOLD-03**:全面WYSIWYG、E6 CRDT/OT共同編集。まずEDIT-01と認可/presence契約、保存量・オフライン・競合モデルを確定する。
|
- **HOLD-03**:全面WYSIWYG、E6 CRDT/OT共同編集。まずEDIT-01と認可/presence契約、保存量・オフライン・競合モデルを確定する。
|
||||||
- **HOLD-04**:本番への反映。作業履歴/日次メールのv3/v4移行を含む同世代保全と隔離復元試験、容量確認、SMTP副作用照合が必要。古いbinaryを新schemaへ向ける切戻しは禁止。
|
- **HOLD-04**:本番反映は実装と別ゲート。[v0.15.0までの配備](../../operations/releases/2026-11-08-v0.15.0.md)は完了。追加変更には同世代保全と隔離復元試験、容量確認、外部副作用照合が必要。古いbinaryを新schemaへ向ける切戻しは禁止。
|
||||||
|
|
||||||
## 実装と分けて管理する受入
|
## 実装と分けて管理する受入
|
||||||
|
|
||||||
|
|||||||
@@ -111,7 +111,8 @@ Cache-Control: private, no-store
|
|||||||
- [ ] ディスクcacheの容量・TTL・清掃、renderer更新時の不整合、障害後の一時ファイル残留を管理する。
|
- [ ] ディスクcacheの容量・TTL・清掃、renderer更新時の不整合、障害後の一時ファイル残留を管理する。
|
||||||
- [ ] provider宛通信と描画サービス内の外部参照を分け、送信許可・接続先・ネットワーク隔離・バージョン固定を契約化する。
|
- [ ] provider宛通信と描画サービス内の外部参照を分け、送信許可・接続先・ネットワーク隔離・バージョン固定を契約化する。
|
||||||
- [ ] nwdiagの有界parser・安全なSVG出力・編集preview、Draw.io等のproviderを追加する。現在のregistryにnwdiagは実装されていない。
|
- [ ] nwdiagの有界parser・安全なSVG出力・編集preview、Draw.io等のproviderを追加する。現在のregistryにnwdiagは実装されていない。
|
||||||
- [ ] Reveal互換・HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
|
- [x] Reveal.jsの有界ビューア・既存HTML/Markdownエディタ内previewをローカル固定版で接続する。Path認可・sandbox・ドメイン停止を持ち、正本への保存は既存エディタを利用する([スライド設計](extensions.md))。
|
||||||
|
- [ ] Revealの縦スライド・発表者notes・専用print、HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
|
||||||
- [ ] Excalidrawのhosted/browser実行とPDF/動画サムネイル・metadata subprocessを、各々の安全境界を維持したまま段階的に接続する。
|
- [ ] Excalidrawのhosted/browser実行とPDF/動画サムネイル・metadata subprocessを、各々の安全境界を維持したまま段階的に接続する。
|
||||||
|
|
||||||
## 検証と反映
|
## 検証と反映
|
||||||
|
|||||||
@@ -14,6 +14,14 @@ childrenは現在Pathを既定にし、表示形式は本文macroの `view` 引
|
|||||||
|
|
||||||
`/v/tree/{path}` は範囲を限定します。展開・全展開・全折りたたみ状態の保持、複数選択、rename・移動・削除はPath操作と一致させます。一般の子一覧から予約ユーザー領域を混入させません。再帰操作は事前の全対象確認と競合検出が必要です。
|
`/v/tree/{path}` は範囲を限定します。展開・全展開・全折りたたみ状態の保持、複数選択、rename・移動・削除はPath操作と一致させます。一般の子一覧から予約ユーザー領域を混入させません。再帰操作は事前の全対象確認と競合検出が必要です。
|
||||||
|
|
||||||
|
## Browserのアップロード
|
||||||
|
|
||||||
|
`/v/browser/{path}` の一覧へファイルをドロップすると、現在のPath配下へアップロードします。フォルダ行へのドロップではそのフォルダが宛先になります。既存の内部Path移動・選択操作とは区別します。
|
||||||
|
|
||||||
|
右下のフローティングカードに待機・送信中・完了・失敗・取消と進捗を表示します。追加ドロップは同じキューへ積み、送信は1件ずつ、最大100件・各256 MiBまで。待機中の取消、折りたたみ、終了分のクリアに対応します。終了後は一覧だけを再取得し、キューは残します。
|
||||||
|
|
||||||
|
既存の認可付き `/v/upload` を使用し、`If-None-Match: *` で同名Pathの上書きを防ぎます。通信断は保存結果不明として扱い、自動再送しません。キューはページ内のみで、ページ離脱・再起動後の再開やフォルダの再帰アップロードには未対応です。新規オブジェクト・Path・初回Revisionの一体的なトランザクション化は残課題です。
|
||||||
|
|
||||||
## ホームとブックマーク
|
## ホームとブックマーク
|
||||||
|
|
||||||
通常トップバー型、中央検索型、検索+セクションカード型を選びます。セクションは手動URL/Path、または指定親の子リンクを表示します。設定は歯車のポップアップで、閲覧画面を編集フォームで埋めません。カード列はviewportに適応します。
|
通常トップバー型、中央検索型、検索+セクションカード型を選びます。セクションは手動URL/Path、または指定親の子リンクを表示します。設定は歯車のポップアップで、閲覧画面を編集フォームで埋めません。カード列はviewportに適応します。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# オーガナイザーのナビゲーションと個人ダッシュボード
|
# オーガナイザーのナビゲーションと個人ダッシュボード
|
||||||
|
|
||||||
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。以下は2026-11-02のソース実装範囲で、2026-11-04にv0.7.0として本番へ反映した。移行・検証・復旧点は[本番反映記録](../../operations/deployments/2026-11-04-v0.7.0.md)を参照する。
|
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。初期実装は2026-11-04にv0.7.0として本番へ反映した。2026-11-09の追加実装は、明日の予定・コマンドウィジェット、件名Markdown、参照欄、個人の外観設定。これらの追加分は本番未反映。
|
||||||
|
|
||||||
## 入口と設定の配置
|
## 入口と設定の配置
|
||||||
|
|
||||||
@@ -10,13 +10,14 @@
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `/v/plan/dashboard` | ウィジェット形式の個人ダッシュボード |
|
| `/v/plan/dashboard` | ウィジェット形式の個人ダッシュボード |
|
||||||
| `/v/plan/tasks` | 既存のインライン編集可能なタスク一覧 |
|
| `/v/plan/tasks` | 既存のインライン編集可能なタスク一覧 |
|
||||||
|
| `/v/plan/tasks/index` | neomutt風のキーボード操作によるタスク一覧 |
|
||||||
| `/v/plan` | 既存のカレンダー表示。保存されたビューを尊重 |
|
| `/v/plan` | 既存のカレンダー表示。保存されたビューを尊重 |
|
||||||
| `/v/plan/contacts` | 個人アドレス帳・履歴・CardDAV接続 |
|
| `/v/plan/contacts` | 個人アドレス帳・履歴・CardDAV接続 |
|
||||||
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー |
|
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー、個人の外観 |
|
||||||
|
|
||||||
旧 `/v/plan/tasks/report` はダッシュボードの達成度ウィジェットへ、旧 `/v/plan/tasks/settings` は個人設定へ303リダイレクトする。カレンダーの表示選択ダイアログはその場の表示変更に使い、既定値の永続化は個人設定へ移す。
|
旧 `/v/plan/tasks/report` はダッシュボードの達成度ウィジェットへ、旧 `/v/plan/tasks/settings` は個人設定へ303リダイレクトする。カレンダーの表示選択ダイアログはその場の表示変更に使い、既定値の永続化は個人設定へ移す。
|
||||||
|
|
||||||
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer` の場合だけ個人向けハンドラーに振り分け、管理用設定やアカウント一覧は取得・描画しない。POSTの管理者チェックは緩和しない。保存先は既存の本人用APIであり、一般利用者に管理権限を付与しない。
|
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer`、またはPOSTで `panel=organizer§ion=appearance` の場合だけ個人向けハンドラーに振り分ける。管理用設定のPOSTは従来どおり管理者を要求する。個人設定の保存は本人のactiveアカウントに限定し、管理権限を付与しない。
|
||||||
|
|
||||||
## タスク編集画面と通知既定値
|
## タスク編集画面と通知既定値
|
||||||
|
|
||||||
@@ -26,6 +27,43 @@
|
|||||||
|
|
||||||
760px以下では1カラムにし、主な入力と選択ボタンは44px以上のタッチ領域を確保する。個人設定には新規タスクの期限日・取り組む日のInbox通知と通知時刻を設ける。適用条件と既存データの扱いは[タスク通知](task-reminders.md)を参照する。
|
760px以下では1カラムにし、主な入力と選択ボタンは44px以上のタッチ領域を確保する。個人設定には新規タスクの期限日・取り組む日のInbox通知と通知時刻を設ける。適用条件と既存データの扱いは[タスク通知](task-reminders.md)を参照する。
|
||||||
|
|
||||||
|
## キーボード操作のタスク一覧
|
||||||
|
|
||||||
|
`/v/plan/tasks/index` を既存のインライン編集とは別の表示として提供する。タスク画面の「キーボード一覧」から開く。左側はプロジェクト、右側は状態・件名・期限・取り組む日・優先度・関連Wikiの表。件名Markdownと選択行のテーマ色を使い、サブタスクは矢印で区別する。順序は指定ソートを優先し、親子の隣接は保証しない。
|
||||||
|
|
||||||
|
| キー | 操作 |
|
||||||
|
| --- | --- |
|
||||||
|
| `j` / `k`、上下矢印 | 次/前のタスクを選択 |
|
||||||
|
| `Ctrl+j` / `Ctrl+k` | 次/前のプロジェクトへ表示を切り替え(所属変更ではない) |
|
||||||
|
| `o` / `O` | ソート選択欄へ/昇順・降順を反転 |
|
||||||
|
| `l` / `Esc` | 絞り込み欄へ/一覧へ戻る。絞り込みはEnterで適用 |
|
||||||
|
| `d` | 選択タスクを完了。削除やアーカイブではない |
|
||||||
|
| `s` | 選択タスクで25分Pomodoroを開始。実行中セッションは上書きしない |
|
||||||
|
| `c` / `m` | 作成/既存の編集ダイアログを開く |
|
||||||
|
| `w` | 関連Wikiへ移動。リンクがなければ案内し、暗黙に新規作成しない |
|
||||||
|
| `?` | キーと絞り込み式のヘルプ |
|
||||||
|
|
||||||
|
入力欄、IME変換中、ダイアログ表示中にはショートカットを実行しない。更新系キーはキーリピートを無視する。作成時は選択中のプロジェクトを引き継ぎ、「すべて」では個人の既定値、「プロジェクトなし」では明示的な未所属とする。ブラウザやOSが予約しているキーをページ側へ渡さない環境では、同じ操作を画面のボタンから行う。
|
||||||
|
|
||||||
|
初期絞り込みは `~active`。複数条件はAND、`!` を条件の前に付けると否定する。OR・括弧・正規表現は扱わない。空欄はアーカイブ以外の全状態を表示する。
|
||||||
|
|
||||||
|
| 書式 | 意味 |
|
||||||
|
| --- | --- |
|
||||||
|
| `~s "リリース準備"` | 件名の部分一致。空白を含む値は引用符で囲む |
|
||||||
|
| `~active` / `~todo` / `~doing` / `~done` / `~cancelled` | 未完了/未着手/着手中/完了/取りやめ |
|
||||||
|
| `~overdue` | ドメインの今日より前に期限を迎えた未完了タスク |
|
||||||
|
| `~due <=today` / `~planned tomorrow` / `~start >=2026-11-01` / `~review <today` | 期限・取り組む日・着手日・見直す日。日付はYYYY-MM-DD、today、tomorrow。比較は `= < <= > >=` |
|
||||||
|
| `~due none` | 日付なし。planned、start、reviewにも使用可能 |
|
||||||
|
| `~bucket inbox` / `~bucket backlog` / `~bucket someday` | 整理先 |
|
||||||
|
| `~priority 3` | 優先度0〜3の一致 |
|
||||||
|
| `~wiki` / `~attachment` / `~archived` | 関連Wikiあり/URL・Path参照あり/アーカイブ済み |
|
||||||
|
|
||||||
|
例:`~s "リリース" ~doing !~overdue`。プロジェクト・条件・ソートはURLクエリへreplaceStateで保持し、操作ごとに履歴エントリを増やさない。
|
||||||
|
|
||||||
|
取得は既存 `items` APIの `view=index`。`filter`、`sort`(due/planned/title/status/priority/created/updated)、`order`(asc/desc)、`project`、`before`を使う。未所属は `project=none`。サーバーで対象全体を絞り込み・ソートして100件ずつ取得し、末尾での下移動または追加読込で次を取得する。ソート値とUUIDによる順序を使い、他ユーザーのカーソルから内容を返さない。日付未設定は昇順の末尾、完全な逆順では先頭になる。並行更新時の固定スナップショットではないため、再読込で最新状態を確認する。
|
||||||
|
|
||||||
|
条件は1000バイト・最大64トークン。SQLは値をバインドし、ソート列は許可リストから選ぶ。不正条件は422で、旧表示を残して操作ボタンを無効化する。プロジェクトも検索・50件単位の追加読込とし、一括取得しない。完了は表示時のversionをIf-Matchで送る。別更新があれば412で止め、メモ等を最新取得しても古い選択行からの更新を無条件に通さない。本人の権限・読み取り専用制限は既存APIに従う。この一覧追加にDBスキーマ変更はない。
|
||||||
|
|
||||||
## ウィジェット
|
## ウィジェット
|
||||||
|
|
||||||
初期構成は次の6種類。任意のHTML・iframe・外部URL・スクリプトを登録する機能ではなく、サーバーが許可する組み込みIDを使う。
|
初期構成は次の6種類。任意のHTML・iframe・外部URL・スクリプトを登録する機能ではなく、サーバーが許可する組み込みIDを使う。
|
||||||
@@ -39,13 +77,15 @@
|
|||||||
| `schedule` | 既定カレンダーにある今日の予定 |
|
| `schedule` | 既定カレンダーにある今日の予定 |
|
||||||
| `activity` | 完了数・ポイント・作業時間・集中時間、日別ヒートマップ |
|
| `activity` | 完了数・ポイント・作業時間・集中時間、日別ヒートマップ |
|
||||||
|
|
||||||
|
追加メニューには `feeds`(RSS)、`tomorrow-schedule`(明日の予定)、`commands`(タスクコマンド)も用意する。既存の保存済み配置に自動追加せず、追加後に「配置を保存」で確定する。予定は時刻範囲・件名・カレンダー名をカード状に配置し、開催中の予定を強調する。終日予定は時刻の代わりに「終日」を表示する。
|
||||||
|
|
||||||
タブはウィジェットの枠内で内容を切り替える。iframeを使わず、ページやブラウザ履歴を移動しない。タスク件名や右上の矢印は既存の詳細・一覧へ移動する。タスクの編集操作は従来の一覧・詳細画面を利用する。
|
タブはウィジェットの枠内で内容を切り替える。iframeを使わず、ページやブラウザ履歴を移動しない。タスク件名や右上の矢印は既存の詳細・一覧へ移動する。タスクの編集操作は従来の一覧・詳細画面を利用する。
|
||||||
|
|
||||||
達成率の分母は `planned_on=今日`、分子はそのうち `status=done` の件数。取りやめ・アーカイブ・プロジェクトを除く。日付はドメインのタイムゾーンで判定する。対象0件は100%でなく「—」を表示する。期限超過を含む「本日のタスク」の件数とは意図的に異なり、画面に定義を明記する。ヒートマップのポイント計算は[タスクの集計契約](task-productivity-contacts.md)に従う。
|
達成率の分母は `planned_on=今日`、分子はそのうち `status=done` の件数。取りやめ・アーカイブ・プロジェクトを除く。日付はドメインのタイムゾーンで判定する。対象0件は100%でなく「—」を表示する。期限超過を含む「本日のタスク」の件数とは意図的に異なり、画面に定義を明記する。ヒートマップのポイント計算は[タスクの集計契約](task-productivity-contacts.md)に従う。
|
||||||
|
|
||||||
## 配置と保存
|
## 配置と保存
|
||||||
|
|
||||||
デスクトップは12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
|
デスクトップは画面幅いっぱいの12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
|
||||||
|
|
||||||
歯車で配置モードを開き、ハンドルのドラッグで並べ替え、右下のハンドルでサイズを変える。矢印ボタンと幅・高さの選択欄でも同じ操作が可能。追加・除去・初期配置への復帰に対応し、「配置を保存」で確定する。タブの選択も配置の一部として保存できる。未保存の離脱を警告し、保存失敗・競合時には編集中の配置を残す。ブラウザ再起動をまたぐ未保存レイアウトの下書きは持たない。
|
歯車で配置モードを開き、ハンドルのドラッグで並べ替え、右下のハンドルでサイズを変える。矢印ボタンと幅・高さの選択欄でも同じ操作が可能。追加・除去・初期配置への復帰に対応し、「配置を保存」で確定する。タブの選択も配置の一部として保存できる。未保存の離脱を警告し、保存失敗・競合時には編集中の配置を残す。ブラウザ再起動をまたぐ未保存レイアウトの下書きは持たない。
|
||||||
|
|
||||||
@@ -69,6 +109,28 @@ APIは `/_/api/v1/extension/organizer.tasks/` 配下。
|
|||||||
|
|
||||||
## 検証と後続範囲
|
## 検証と後続範囲
|
||||||
|
|
||||||
|
### タスク表示と参照
|
||||||
|
|
||||||
|
件名の保存形式は文字列のまま。Web一覧では太字、斜体、取り消し線、インラインコード、リンクのラベルをDOMで描画する。HTML・画像・マクロを実行しない。インライン編集のフォーカス中はMarkdownソースをそのまま入力できる。関連Wikiがある行は塗りつぶした文書アイコンとテーマ色で区別する。
|
||||||
|
|
||||||
|
`TaskRecord.references` はURLまたはWiki Pathの配列(最大20件、1件4096バイト)で、タスクの編集画面の詳細設定から変更する。http/httpsと同一サイトの絶対Pathだけを認め、認証情報入りURL・プロトコル相対URL・制御文字は拒否する。リンク先の取得や公開範囲の変更は行わない。Path参照は文字列のためrenameには追従しない。rename追従が必要な主たる関連Wikiには従来の `page_uuid` を使う。
|
||||||
|
|
||||||
|
正本JSONと変更履歴に参照を保存し、タスクの列追加は不要。旧CLI等がこのフィールドを省略した更新では既存値を維持し、明示的な空配列で解除する。CalDAV更新でも維持するが、VTODOのATTACHへの投影は後続範囲。
|
||||||
|
|
||||||
|
### タスクコマンド
|
||||||
|
|
||||||
|
`add task 件名`、`today UUID`、`tomorrow UUID`、`due UUID YYYY-MM-DD`、`due UUID clear`、`done UUID`、`delete UUID` を提供する。対象は件名検索のサジェストから選ぶとUUIDが入る(250ms debounce、最大10件)。シェルコマンドではない。追加は個人の既定値を読み、通信失敗時は同じUUIDで再試行できる。既存タスクへの操作は取得時のversionをIf-Matchで送信し、競合時は上書きしない。削除は件名を確認してから実行する。今日・明日はダッシュボード読込時のドメイン日付を基準とする。
|
||||||
|
|
||||||
|
### 個人の外観とログイン画面
|
||||||
|
|
||||||
|
壁紙Path・不透明度・グラス透明度・壁紙からの色抽出を個人設定へ追加する。トップ画面の歯車も同じ本人用保存先を使う。初回は既存のドメイン設定を初期値として引き継ぎ、保存後は個人値を優先する。空の壁紙Pathは「壁紙なし」。フォルダ選択時は従来どおり閲覧可能な直下の画像から選ぶ。
|
||||||
|
|
||||||
|
`personal_appearance` はDomain UUIDと本人UUIDを複合キーにしたJSON+versionのテーブル。起動時の設定テーブル初期化で追加する。既存テーブル・正本を破壊せず、保存はversion比較で競合409を返す。タスク既定値・メール同意のversionを変更しない。ドメイン設定画面の外観項目は初期値用として区別する。
|
||||||
|
|
||||||
|
ログイン画面は壁紙なしとし、旧 `/_/auth/wallpaper` は404を返す。個人・ドメインのトップ壁紙をログイン前に公開しない。別のログイン専用背景Pathは今回追加しない。
|
||||||
|
|
||||||
|
### 回帰検証
|
||||||
|
|
||||||
合成データで、所有者分離、CAS、読み取り専用、匿名拒否、管理設定への権限拡大がないこと、空配置、禁止ウィジェット、メール設定の不変、今日の集計・予定範囲を検証する。ブラウザではデスクトップとスマホの導線、タブ、設定保存、配置保存、横はみ出しを確認し、デスクトップのドラッグ・リサイズには実ポインター入力を使う。本番の外部取り込みカレンダーは検証に使わない。
|
合成データで、所有者分離、CAS、読み取り専用、匿名拒否、管理設定への権限拡大がないこと、空配置、禁止ウィジェット、メール設定の不変、今日の集計・予定範囲を検証する。ブラウザではデスクトップとスマホの導線、タブ、設定保存、配置保存、横はみ出しを確認し、デスクトップのドラッグ・リサイズには実ポインター入力を使う。本番の外部取り込みカレンダーは検証に使わない。
|
||||||
|
|
||||||
次段階は以下を別途設計する。
|
次段階は以下を別途設計する。
|
||||||
|
|||||||
@@ -23,6 +23,12 @@
|
|||||||
|
|
||||||
### 3. テーマ・アカウント・連絡先
|
### 3. テーマ・アカウント・連絡先
|
||||||
|
|
||||||
|
- [x] 信頼できる端末の長期ログイン(2026-11-08ローカル実装、本番未反映):ログイン画面の明示選択で最大30日。Domain管理者は設定→セッションで0〜30日(0で無効)を指定する。通常ログインは既存の絶対期限を維持。パスワード/TOTP、LDAP、OIDC、SMTPマジックリンクに適用し、選択は認証challengeに固定する。CookieとBearerの期限はDBの発行期限と一致し、ログアウト・管理者失効・アカウント停止で無効になる。既存セッションの延長、TOTPの省略、アクセスによる期限延長は行わない。
|
||||||
|
- [x] 独立CLIの `pages login --remember` / `pages login --oidc --no-browser --remember`。S256 grantに選択を保存し、ブラウザ側のクエリで上書きできない。APIセッションは承認元ブラウザの残存期限を超えない。期限切れ後はlogoutなしで再認証でき、同一アカウントのcwdと未送信タスク下書きを保持する。別アカウントへの下書き移動は拒否する。旧サーバーは選択を無視する場合があるため、実際の期限は応答のexpires_inを正とする。
|
||||||
|
- [x] タスク編集フッターの関連ページ導線(2026-11-08ローカル実装、本番未反映):アーカイブ・削除・保存と同じ並びに関連ページリンクを表示。新規タブで開き、編集中の内容を保持する。保存済みの関連Pageがない場合、解除した場合、Path変更が未保存の場合は非表示。デスクトップ/モバイル4幅のブラウザテストを追加。
|
||||||
|
|
||||||
|
長期ログインのDB変更はmanaged component `cli-auth` v2の `remember` 列追加のみ。既存行はfalse、既存セッションと文書・タスクデータは変更しない。端末名・一覧・個別端末の信頼登録、refresh token rotationは別設計とし、今回は既存セッション管理から失効する。
|
||||||
|
|
||||||
- [x] 共通ナビの◐からプリセットを選択、リロードせず切替。host限定Cookieに保持し、Domain既定に戻せる。登録済みテーマのみ許可。Domain設定/アカウントの全端末設定ではなくブラウザ上書き。失敗時は現在テーマを保持する。
|
- [x] 共通ナビの◐からプリセットを選択、リロードせず切替。host限定Cookieに保持し、Domain既定に戻せる。登録済みテーマのみ許可。Domain設定/アカウントの全端末設定ではなくブラウザ上書き。失敗時は現在テーマを保持する。
|
||||||
- [x] 絶対セッション期限:設定→セッション、5〜43200分、既定1440分。Domain単位で新規ブラウザ/APIログイン(OIDC/LDAPを含む)に適用。発行時にDBの期限を固定し、Cookie/APIのexpires_inにも反映。既存セッションの期限とCalDAVアプリパスワードは変更しない。管理者認可とサーバ側失効をfixture検証。
|
- [x] 絶対セッション期限:設定→セッション、5〜43200分、既定1440分。Domain単位で新規ブラウザ/APIログイン(OIDC/LDAPを含む)に適用。発行時にDBの期限を固定し、Cookie/APIのexpires_inにも反映。既存セッションの期限とCalDAVアプリパスワードは変更しない。管理者認可とサーバ側失効をfixture検証。
|
||||||
- [ ] 無操作タイムアウトとアカウント別の短縮上書き:background pollingを人間の操作とみなさないactivity契約、再認証、既存セッションへの即時適用を別途設計する。
|
- [ ] 無操作タイムアウトとアカウント別の短縮上書き:background pollingを人間の操作とみなさないactivity契約、再認証、既存セッションへの即時適用を別途設計する。
|
||||||
|
|||||||
@@ -26,6 +26,14 @@ v0.3.0のOIDCログインは利用者の動作確認済み。v0.4.0ではOIDC承
|
|||||||
|
|
||||||
## 利用方法
|
## 利用方法
|
||||||
|
|
||||||
|
### 信頼できる端末でのログイン継続
|
||||||
|
|
||||||
|
2026-11-08ローカル実装、未リリース。独立CLIと対応サーバーを更新すると、`pages login --remember` または `pages login --oidc --no-browser --remember` で最長30日のセッションを要求できる。管理者の `auth_trusted_session_days`(既定30、0で無効)に従い、応答の `expires_in` を期限として保存する。旧サーバーでは通常の期限になる場合がある。
|
||||||
|
|
||||||
|
パスワードログインは必要なTOTPを維持する。選択はTOTP challenge/OIDC grantへ固定し、認証完了時の追加パラメーターで変更できない。CLI grantはmanaged component `cli-auth` v2で `remember` 列を追加し、既存行をfalseとして保持する。承認済みgrantの交換とセッション発行は従来どおり単一トランザクションで処理し、期限は承認元ブラウザの期限を超えない。
|
||||||
|
|
||||||
|
ローカル期限切れ後は `logout` を挟まず再ログインできる。同一アカウントならcwdと未送信タスク下書きを保持し、認証失敗時は従来のローカル状態を変更しない。ログアウト・管理者による失効・アカウント停止は長期セッションにも適用する。共有端末では使用しない。
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# 初回設定。パスワードはlogin時の非表示プロンプト、必要ならTOTPを続けて入力。
|
# 初回設定。パスワードはlogin時の非表示プロンプト、必要ならTOTPを続けて入力。
|
||||||
pages configure --origin https://pages.example.test --username anya
|
pages configure --origin https://pages.example.test --username anya
|
||||||
|
|||||||
@@ -34,7 +34,9 @@
|
|||||||
|
|
||||||
一覧GETは `kind=task|project`、`view`、`project`、`q`、`limit`、`before` を受け付けます。既定60件、上限100件。作成はPOST、更新はPUT、`If-Match: "{version}"` 必須。ヘッダーなしは428、古い版は412。UUIDをクライアントで生成し、同内容の作成再送は同じ版を返します。異内容の再送は競合です。成功時は `item` と現在読める `page_path`、ETagを返します。一覧はメモ本文を省略するため、編集やクイック完了前に必ず詳細を取得します。
|
一覧GETは `kind=task|project`、`view`、`project`、`q`、`limit`、`before` を受け付けます。既定60件、上限100件。作成はPOST、更新はPUT、`If-Match: "{version}"` 必須。ヘッダーなしは428、古い版は412。UUIDをクライアントで生成し、同内容の作成再送は同じ版を返します。異内容の再送は競合です。成功時は `item` と現在読める `page_path`、ETagを返します。一覧はメモ本文を省略するため、編集やクイック完了前に必ず詳細を取得します。
|
||||||
|
|
||||||
## タスクの削除(2026-11-08実装、未デプロイ)
|
## タスクの削除
|
||||||
|
|
||||||
|
2026-11-08、v0.14.0で本番反映済み。[配備記録](../../operations/releases/2026-11-08-task-deletion.md)。
|
||||||
|
|
||||||
UUID検索は追加せず、既存のタスク編集画面で「アーカイブ/復元」の隣に「削除」を置きます。未保存の新規タスク、readonly、プロジェクト編集には表示しません。件名と削除範囲を確認してから実行し、削除失敗時は編集内容を保持します。アーカイブ済みタスクも同じ操作で削除できます。
|
UUID検索は追加せず、既存のタスク編集画面で「アーカイブ/復元」の隣に「削除」を置きます。未保存の新規タスク、readonly、プロジェクト編集には表示しません。件名と削除範囲を確認してから実行し、削除失敗時は編集内容を保持します。アーカイブ済みタスクも同じ操作で削除できます。
|
||||||
|
|
||||||
@@ -49,6 +51,22 @@ UUID検索は追加せず、既存のタスク編集画面で「アーカイブ
|
|||||||
|
|
||||||
`internal/server/task_delete_test.go` で条件付き削除・権限・再送・DBロールバック・通知取消・作業履歴保全・DAV索引再構築/再送拒否を検証します。既存のChromiumテストに、削除ボタンの位置、確認キャンセル、版競合、成功後の一覧更新を追加しています。本番データの削除は実施しません。
|
`internal/server/task_delete_test.go` で条件付き削除・権限・再送・DBロールバック・通知取消・作業履歴保全・DAV索引再構築/再送拒否を検証します。既存のChromiumテストに、削除ボタンの位置、確認キャンセル、版競合、成功後の一覧更新を追加しています。本番データの削除は実施しません。
|
||||||
|
|
||||||
|
### 削除済みメール取り込みの再作成
|
||||||
|
|
||||||
|
PagesWiki v0.14.1/pages-cli v0.4.2で実装、2026-11-08 19:42 JSTに本番反映済み。[配備記録](../../operations/releases/2026-11-08-task-capture-recovery.md)。サーバーとCLIの両方の更新が必要です。DBスキーマ変更や既存データの削除はありません。
|
||||||
|
|
||||||
|
`POST /_/api/v1/extension/organizer.tasks/capture` は、受付記録に対応するタスクの状態を本文ハッシュより先に確認します。削除済みなら同じ内容・異なる内容とも410 `deleted`。タスクと削除記録が両方欠落していれば409 `capture_missing` とし、自動修復・再作成はしません。存続中のタスクへの異内容再送は従来どおり412です。
|
||||||
|
|
||||||
|
削除済み要求の保留下書きは `pages task retry REQUEST_UUID --recreate-deleted` で明示的に再取り込みできます。CLIは新しい要求を送る前に保存し、以降の再送用IDを表示します。通信失敗後は表示された新IDで通常の `task retry NEW_REQUEST_UUID` を使います。メール本文・Wiki suffixは保持し、以前のタスクの状態・作業時間・子タスクを復元する操作ではありません。
|
||||||
|
|
||||||
|
- APIには `replaces_deleted` に元のrequest UUIDを渡します。新しい `request_id` はURL名前空間のUUIDv5で、名前は `pages:task-recreate:` と元のrequest UUIDを連結したもの。任意の後継IDを拒否し、同じ再取り込みの二重作成を防ぎます。
|
||||||
|
- 同じDomain・所有者の受付記録と削除記録を要求し、元タスクが存続中なら412、他人の受付記録や不存在の要求は404。writer transaction内でも検査します。受付記録のない直接作成タスクには使えません。
|
||||||
|
- 新しいタスク・受付記録・変更履歴・通知予約を原子的に保存します。旧受付記録、削除記録、DAV識別子の予約は残し、旧端末の再送による復活を防ぎます。
|
||||||
|
- Wiki保存先にページが残っていれば、そのUUIDを新しいタスクに関連付けます。本文・リビジョンは上書きしません。存在しなければ保留本文から作成します。read/create/writeの現在権限と入力上限を検査し、ファイルなどページ以外との衝突は409です。保存先は保留要求と現在の既定値から解決するため、移動済みのWikiや既定Path変更を追跡して復元する機能ではありません。
|
||||||
|
- 再作成済み要求の再送は同じ新タスクを返します。そのタスクも削除済みなら410で停止し、さらに復活させません。元のメールを再入力しただけでは削除済み状態を解除しません。
|
||||||
|
|
||||||
|
`internal/server/task_capture_recreate_test.go` でライフサイクル・並行再送・所有者境界・ロールバック・Wiki保持を検証し、CLIの単体テストとHTTP結合テストでも再送IDの保持を検証します。
|
||||||
|
|
||||||
## 保存と復旧の境界
|
## 保存と復旧の境界
|
||||||
|
|
||||||
`organizer_items` はDomain・所有者・UUID・種類・検索用メタデータ・現在版を保持します。本文を含む型付きJSONは既存Document StoreへSHA-256で保存し、同じJSONをDBにも保持します。`organizer_revisions` は版からDocumentへの参照、`organizer_changes` は後続処理用の小さな変更ジャーナルです。head更新・履歴・変更ジャーナルは同じSQLiteトランザクションです。
|
`organizer_items` はDomain・所有者・UUID・種類・検索用メタデータ・現在版を保持します。本文を含む型付きJSONは既存Document StoreへSHA-256で保存し、同じJSONをDBにも保持します。`organizer_revisions` は版からDocumentへの参照、`organizer_changes` は後続処理用の小さな変更ジャーナルです。head更新・履歴・変更ジャーナルは同じSQLiteトランザクションです。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 保存基盤の多様化と運用機能の統合
|
# 保存基盤の多様化と運用機能の統合
|
||||||
|
|
||||||
状態:詳細設計・段階導入。2026-09-27。
|
状態:詳細設計・段階導入。2026-11-15 更新。
|
||||||
本書は [基本設計](arch.md) と [拡張契約](platform-extension-architecture.md) を補完する。
|
本書は [基本設計](arch.md) と [拡張契約](platform-extension-architecture.md) を補完する。
|
||||||
各 TODO は実装済みを意味しない。本番 DB・保存先の移行は別途承認する。
|
各 TODO は実装済みを意味しない。本番 DB・保存先の移行は別途承認する。
|
||||||
|
|
||||||
@@ -384,6 +384,35 @@ setup 完了後は token 再利用不可。機密欄の再表示・ログ出力
|
|||||||
|
|
||||||
### S2:外部 backend
|
### S2:外部 backend
|
||||||
|
|
||||||
|
- [x] PostgreSQL 接続層と独立した migration runner(アプリの backend 切替は未接続)。
|
||||||
|
- [x] Object/Path/Revision/Asset の共通 metadata Repository と空 DB 用スキーマ、SQLite/PostgreSQL 共通契約テスト。
|
||||||
|
- [x] 既存 Store の Campus/Domain 取得・ホスト解決・ドメイン別設定・Campus 作成/更新の native SQL 移植と共通契約テスト。
|
||||||
|
- [x] 管理者グループの初期化・メンバー更新・継承切替・projection・派生所属とセッションの失効を共通 SQL と transaction に移植。
|
||||||
|
- [x] 一般グループの作成・一覧・メンバー一覧・Path 権限設定、直接 Role binding と Group 権限の付与判定、Principal 状態更新と失効を共通 SQL に移植。
|
||||||
|
- [x] 初回 owner・パスワードアカウント・プロフィール・セッション管理、TOTP、外部認証の設定と Identity 紐付け、CLI 認証引き継ぎの DB 処理を移植し、SQLite/PostgreSQL 共通契約テストを追加。
|
||||||
|
- [x] 認可と読み取りナビゲーションの Locality 制限、City 所有者・公開範囲の上限制約、ユーザー/グループ ACL 更新、保護 Path/City 構造の DB ガードを移植。
|
||||||
|
- [x] 公開 manifest・自動公開・匿名 navigation、承認要求、ユーザー領域とプロフィール連絡先の公開制御を native SQL に移植し、共通 DB テストを追加。
|
||||||
|
- [x] Domain 作成/更新/削除と Campus 削除、管理者継承、連携トークン・instance 登録・署名 manifest の DB 処理を移植。
|
||||||
|
- [x] 通常 Revision 保存・履歴取得・履歴復元の Store 境界と HTTP 呼び出しを native metadata Repository に接続し、合成データで保存・競合・故障時の rollback を検証。
|
||||||
|
- [x] Path の再帰移動・コピー・snapshot 付き一括削除、alias/primary link と navigator の DB 処理を移植。
|
||||||
|
- [x] City map・所属 Page・Path context・health・監査履歴の取得、タイトル・境界変更、Spot 整理(移動・統合)を移植。
|
||||||
|
- [x] Asset の一覧・参照・履歴、作成/更新・復元・削除を移植し、楽観ロックと履歴保存失敗時の rollback を検証。
|
||||||
|
- [x] City の個別作成・配置・relation・再帰削除、一括変更計画の preview/apply、自動生成候補と名前競合の問い合わせを移植。
|
||||||
|
- [x] Browser・children・Path 補完・権限付き Object metadata 一覧を移植し、native canonical HTML の H1 と複数 Store 間の children cache 失効を検証。
|
||||||
|
- [x] アーカイブ import のセッション・計画・journal・Path rollback を移植。全 DB の SQLite→PostgreSQL インポートとは別機能。
|
||||||
|
- [x] タスク・プロジェクトの保存/取得/履歴/階層付き一覧/削除、DAV resource・collection・資格情報・既定リスト名の Store 操作を移植し、両 DB で契約を検証。
|
||||||
|
- [x] タスク個人設定、作業時間の開始・終了・訂正・取消と監査履歴、Pomodoro と日次集計、ダッシュボード配置・達成率、予定枠の DB 予約を移植。
|
||||||
|
- [x] 通知 Inbox の保存・重複排除・取得・既読、期限/着手日の通知配信、タイマー完了、活動 journal の outbox 補完処理を移植。scheduler と Push 配信は別途接続する。
|
||||||
|
- [x] タスク capture と Wiki 同時作成、削除後の明示的再作成、プロジェクト配下のメモ作成を移植。受付記録・本文参照・Path・outbox の原子性を検証。
|
||||||
|
- [x] 日次メールの送信予約、本人の同意・権限確認、送信履歴、明示的再試行、保持期限処理を移植。SMTP worker と scheduler は別途統合する。
|
||||||
|
- [x] カレンダーの再構築可能な月別索引、予定の取得・更新・削除、DAV resource 操作、タスク予定枠と日次予定の cache 参照を移植。正本 ICS と manifest の形式は維持する。
|
||||||
|
- [x] 連絡先の保存・検索・削除・履歴復元・export、CardDAV の resource 名・差分同期・metadata inventory と資格情報失効を移植。
|
||||||
|
- [x] ブログ・日記の設定、記事作成・登録・解除・一覧、投稿受付の重複排除、公開タイトルと別 Domain への射影設定を移植。本文と埋め込み Asset 参照の固定、監査失敗時の rollback を検証。
|
||||||
|
- [x] RSS/FreshRSS の購読元・既読/スター・記事 cache・分類・購読 import・Wiki 取り込みと受付記録、外部操作の claim・確認・履歴を移植。scheduler 登録は別途接続する。
|
||||||
|
- [ ] 通常 HTTP/scheduler/CLI 起動を経由した認証・公開・federation の PostgreSQL 統合試験。
|
||||||
|
- [x] 読み取り専用の移植診断 CLI と、対応済み core の catalog / 履歴検査。
|
||||||
|
- [x] 停止状態の core SQLite→PostgreSQL→SQLite 往復リハーサル、内容指紋・採番・参照・Document の検証。
|
||||||
|
- [ ] Object/Path/Revision/Asset の全 Store 操作と関連正本更新の接続、既存 DB 移行、共通統合テスト。
|
||||||
- [ ] PostgreSQL の全 repository 移植と SQLite との共通機能テスト。
|
- [ ] PostgreSQL の全 repository 移植と SQLite との共通機能テスト。
|
||||||
- [ ] MySQL の DDL/索引/照合順序/同時書き込み試験。
|
- [ ] MySQL の DDL/索引/照合順序/同時書き込み試験。
|
||||||
- [ ] S3 adapter と互換サービスで range/条件付き作成/破損/切断/容量制限を検証。
|
- [ ] S3 adapter と互換サービスで range/条件付き作成/破損/切断/容量制限を検証。
|
||||||
@@ -391,6 +420,790 @@ setup 完了後は token 再利用不可。機密欄の再表示・ログ出力
|
|||||||
- [ ] Redis cache adapter と停止時の制限付き縮退、policy epoch による失効。
|
- [ ] Redis cache adapter と停止時の制限付き縮退、policy epoch による失効。
|
||||||
- [ ] mutable canonical CAS と metadata 参照の回復プロトコル、HA の fencing。
|
- [ ] mutable canonical CAS と metadata 参照の回復プロトコル、HA の fencing。
|
||||||
|
|
||||||
|
#### PostgreSQL 対応の実装順序
|
||||||
|
|
||||||
|
2026-11-14 時点では `internal/db.OpenPostgreSQL` と
|
||||||
|
`ApplyPostgreSQLMigrations` を追加した。既存の `Open`、`Migrate`、通常の Store 初期化、
|
||||||
|
通常起動、DR、CLI は引き続き SQLite 用であり、PostgreSQL を本番選択可能にはしない。
|
||||||
|
利用者の DB を自動変換せず、既存 migration の checksum も変更しない。
|
||||||
|
|
||||||
|
接続には pgx の database/sql 実装を使用し、DSN はインスタンスの秘密設定として扱う。
|
||||||
|
既定で検証付き TLS と平文 fallback の禁止を要求する。開発専用の
|
||||||
|
`AllowInsecure` を明示した場合だけ非検証接続を許す。接続確認の timeout、
|
||||||
|
pool の上限、connection の寿命を設け、失敗時は pool を閉じる。
|
||||||
|
エラーは SQLSTATE と操作名だけを公開し、DSN、SQL、サーバの詳細メッセージや
|
||||||
|
constraint 内の個人情報をエラー文字列へ含めない。
|
||||||
|
|
||||||
|
PostgreSQL 用 migration は SQLite の SQL 自動翻訳ではなく、独立した append-only 定義とする。
|
||||||
|
BIGINT の epoch ms、ネイティブの `$1` 引数、明示した conflict target を使う。
|
||||||
|
runner は READ COMMITTED transaction と共通の transaction-level advisory lock で
|
||||||
|
ledger の初回作成を含めて直列化する。異なる component にも同じロックを使う。
|
||||||
|
DDL、checksum 履歴、最新 assertion の検証を同じ transaction に含め、
|
||||||
|
失敗時は rollback、正常終了時は commit と同時にロックを解放する。
|
||||||
|
未知の新しい履歴、欠けた version、変更された定義は適用を停止する。
|
||||||
|
|
||||||
|
| 順序 | 範囲 | 完了条件 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1 | 接続と migration | 実 PostgreSQL で並行適用、rollback、履歴不一致、lock 待ちキャンセルを検証 |
|
||||||
|
| 2 | Object/Path/Revision/Asset | Domain 分離、UUID 不変性、revision 保存、再帰 rename、hash 参照の SQLite 共通契約を通過 |
|
||||||
|
| 3 | 認証と ACL | ユーザー、グループ、セッション、公開範囲の共通契約を通過 |
|
||||||
|
| 4 | タスクと CalDAV | プロジェクト所属、VTODO、ETag と競合更新、通知を検証 |
|
||||||
|
| 5 | ジョブと通知 | claim token、lease、row lock、outbox と重複処理耐性を検証 |
|
||||||
|
| 6 | City と検索と管理 | rowid/PRAGMA/FTS5 依存を分離し、安定した順序・検索・schema 診断を検証 |
|
||||||
|
| 7 | 既存データ移行と運用 | 停止状態の export/import、件数・参照・hash 検査、restore rehearsal、起動設定と readiness を接続 |
|
||||||
|
|
||||||
|
#### 既存 Store の Campus と Domain と設定の移植
|
||||||
|
|
||||||
|
`internal/store` に backend を保持し、既存 API から native PostgreSQL の SQL を使える
|
||||||
|
経路を追加した。既定値は SQLite とし、従来の Store constructor と最小 fixture の
|
||||||
|
振る舞いを維持する。SQL の `?` を一括変換せず、query 構築時に placeholder を生成する。
|
||||||
|
ホスト名の判定は SQLite の `instr` と PostgreSQL の `strpos` を明示的に分ける。
|
||||||
|
|
||||||
|
移植済みの範囲は次のとおり。
|
||||||
|
|
||||||
|
- Campus の既定値取得、UUID 取得、一覧、作成と更新。
|
||||||
|
- Domain の既定値取得、UUID 取得、一覧、件数、Host 解決、実効 FQDN の取得。
|
||||||
|
- Domain ごとの設定の取得と UPSERT。欠けた設定は従来どおり空文字とし、更新時刻は既存の秒単位を維持。
|
||||||
|
- 既存 Store の Path 解決で backend を選択し、Domain が local であることを確認して共通 Repository を呼ぶ。
|
||||||
|
|
||||||
|
Campus の FQDN と Domain の相対ホスト名・FQDN 指定を同じ規則で解決する。
|
||||||
|
未知の Host を既定 Domain へ fallback せず、無効な Campus/Domain と remote Domain の
|
||||||
|
ローカル名前空間へのアクセスを既存の取得規則に従って拒否する。
|
||||||
|
Campus 作成・更新では、移植済み writer が同じ namespace lock を使う範囲で、
|
||||||
|
ホスト名競合の検査と書き込みを一つの transaction に入れる。
|
||||||
|
PostgreSQL では同一 DB の advisory lock、SQLite では書き込みロックを検査前に取得する。
|
||||||
|
transaction の期限とキャンセルは内部の SQL 呼び出しまで伝搬する。
|
||||||
|
|
||||||
|
Domain/Campus の context 付き取得 API を追加し、HTTP のリクエスト単位の Host 解決でも
|
||||||
|
request context を利用する。PostgreSQL の SQL/driver/Scan エラーから個人情報や設定値を
|
||||||
|
出力しないようにし、入力フォームへ返せる固定の validation message は区別して保持する。
|
||||||
|
|
||||||
|
PostgreSQL の初期スキーマは `store-namespaces` migration として独立させる。
|
||||||
|
対象は `campuses`、`domains`、`config`、`personal_appearance` のテーブル定義と索引であり、
|
||||||
|
後者の個人外観 API の移植まで完了したという意味ではない。
|
||||||
|
既知の列不足や適用済み定義の不一致は停止し、既存 SQLite の ALTER/adopt 処理は流用しない。
|
||||||
|
既定 Campus/Domain の初期化は transaction で直列化し、並行実行時の重複と関連付けの欠落を防ぐ。
|
||||||
|
これは旧インスタンスの全データを取り込む import 処理ではない。
|
||||||
|
|
||||||
|
Domain 作成・更新は Campus/実効 Host/配置先の検査、Domain 本体、既定 locale、
|
||||||
|
管理者グループ作成と所属 projection を同じ管理用 writer lock と transaction に含める。
|
||||||
|
同じ実効 Host の同時作成は一つだけ成功し、別 Campus への移動は旧 Campus 由来の管理者権限を取り消す。
|
||||||
|
依存テーブルや projection の障害時は Domain と設定も rollback する。
|
||||||
|
Domain/Campus 削除の参照・最終要素検査も transaction 内で実施する。
|
||||||
|
Campus 削除では連携 token、instance と capability、署名 manifest の checkpoint も削除する。
|
||||||
|
|
||||||
|
`store-federation` は token hash、instance identity、manifest 採番と受信 checkpoint を保持する。
|
||||||
|
登録と token 失効は同じ lock を使用し、登録後に失効済み token を再利用できない。
|
||||||
|
署名の検証後、初回 controller fingerprint の固定、旧 revision と同一 revision の異なる内容の拒否、
|
||||||
|
受信 Campus/Domain/管理者継承と checkpoint の保存を一つの transaction で扱う。
|
||||||
|
`store-domain-entry` は manifest v2 の許可済み entry 設定と日記/ブログの有効化・prefix を保持する。
|
||||||
|
これは日記/ブログ本文の新規作成・検索・projection repository 全体の移植完了ではない。
|
||||||
|
|
||||||
|
現時点の PostgreSQL Store は component 統合テスト内でのみ構築する。
|
||||||
|
本番用 constructor と起動フラグはまだ解放せず、通常のサーバーは SQLite のままとする。
|
||||||
|
core 限定インポートの対象も拡張しておらず、namespace を含む DB は引き続き対象外として拒否する。
|
||||||
|
|
||||||
|
#### 認証と管理者グループの移植
|
||||||
|
|
||||||
|
`store-auth-foundation` の native migration は Principal、Identity、Domain membership、
|
||||||
|
Role、直接 Role binding、Capability grant、Group、Group member と Campus 管理者継承の
|
||||||
|
provenance を定義する。アバターは BYTEA、時刻は BIGINT の Unix milliseconds、
|
||||||
|
識別子と一意制約の比較は C collation とする。既存テーブルの暗黙の取り込みや修復は行わない。
|
||||||
|
適用済み migration の列検査が失敗した場合も既存 Principal を保持したまま停止する。
|
||||||
|
|
||||||
|
既存 Store の `IsBuiltinGroupAdmin` と `IsCampusAdmin` は SQLite と PostgreSQL の
|
||||||
|
両方で動作する。context 付き API は SQL エラーと拒否を区別し、従来の bool API は
|
||||||
|
DB 障害時も権限を与えない。Domain と membership の対応、Principal・membership・Group
|
||||||
|
の有効状態、Domain の enabled、owner/manager role を同じ SQL で検査する。
|
||||||
|
SQLite と実 PostgreSQL の共通テストで状態変更、越境所属、キャンセル、DB 障害を検証する。
|
||||||
|
|
||||||
|
`EnsureBuiltinAdminGroups`、メンバーの追加・更新・削除、`SetCampusAdminInheritance`、
|
||||||
|
`ProjectCampusAdminMemberships` は両 DB 共通の実装を使う。
|
||||||
|
グループの名前・UUID による取得と member role の参照も backend に対応する。
|
||||||
|
PostgreSQL では namespace 更新と同じ advisory lock、SQLite では読み取り前の
|
||||||
|
DB writer lock を使い、元の grant 更新と継承先の再計算を同一 transaction に含める。
|
||||||
|
context 付き API の期限は内部の SQL まで伝搬する。
|
||||||
|
|
||||||
|
継承の入力は独立した grant に限り、派生 grant を新たな継承元にしない。
|
||||||
|
複数の継承元のうち最も強い role を実効値とし、継承解除時には弱いローカル role が再び現れる。
|
||||||
|
派生した membership のみを追跡し、独立した group/role binding で採用済みの所属と session は保持する。
|
||||||
|
派生権限しかない所属は削除し、その Domain の session を同じ transaction で失効する。
|
||||||
|
再有効化しても失効済み session は復活させない。
|
||||||
|
最後の独立 owner の並行削除、継承先での inherited-only grant 削除、owner の通常更新による降格は拒否する。
|
||||||
|
Role からの初期 grant は記録済みの migration marker で再投入を防ぎ、明示的に取り消した権限を
|
||||||
|
再起動で復活させない。Domain の異なる Role binding と別 Domain を指定する manage grant は初期 owner にしない。
|
||||||
|
|
||||||
|
native migration の v2 には失効処理に必要な `auth_sessions` と索引を追加する。
|
||||||
|
管理者継承の共通テストは合成 session 行で取り消しと保持を検査し、
|
||||||
|
projection 後半の故障注入でメンバー追加・削除・継承切替のすべてが rollback することを確認する。
|
||||||
|
|
||||||
|
一般グループの作成は owner の有効な Domain membership と active な Principal を確認し、
|
||||||
|
Group、owner member、派生 membership の独立所属への採用を同一 transaction に含める。
|
||||||
|
一覧の `domain` visibility は単に Principal UUID があるだけでなく、その Domain で有効な所属を要求する。
|
||||||
|
`members` visibility とメンバー一覧、role 参照、Path 権限評価でも membership の Domain 一致を検査する。
|
||||||
|
別 Domain の不正な owner 行を最後の独立 owner の代わりに数えない。
|
||||||
|
一覧は EXISTS で重複を避け、表示名・名前・UUID による安定順を持たせる。
|
||||||
|
|
||||||
|
native migration の v3 は `group_permissions` とメンバーの Identity 参照用索引を追加する。
|
||||||
|
権限設定は既存 Group を要求し、同じ Group/Path の設定を upsert する。
|
||||||
|
`read`、`read_write_once`、`read_write`、`upload_only` の既存 capability と literal Path 境界を保持する。
|
||||||
|
SQL の `%` と `_` を wildcard として扱わず、readonly Principal は read だけを許す。
|
||||||
|
|
||||||
|
直接 Role binding の付与判定も backend に対応し、Domain の異なる Role を拒否する。
|
||||||
|
exact Object モードでは Domain 全体や wildcard の grant を採用しない。
|
||||||
|
この低水準判定は Locality 制限を代替しない。`AuthorizeContext` と
|
||||||
|
`AuthorizeExactObjectContext` は Role/Group grant と Locality cap、Object の別名・別 Domain 制限を
|
||||||
|
同じ read-only transaction で評価する。PostgreSQL は REPEATABLE READ を用い、
|
||||||
|
ナビゲーション用 `LoadReadPathPolicyContext` も同じ snapshot 契約を持つ。
|
||||||
|
公開コンテンツの匿名読み取りとユーザー領域の公開制約も、下記の同一 snapshot 契約を使う。
|
||||||
|
アカウント作成時の Role/binding 書き込みは下記の transaction に含める。
|
||||||
|
それ以外の federation・管理操作からの Role/binding 書き込みは別途移植する。
|
||||||
|
|
||||||
|
`SetPrincipalState` は管理者継承と同じ writer lock を利用する。
|
||||||
|
グローバルな Principal の状態更新、active 以外への変更による全 Domain の session 失効、
|
||||||
|
派生管理者権限の再計算を同じ transaction に含め、失敗時は全体を rollback する。
|
||||||
|
既に失効した session の失効時刻を上書きせず、active へ戻しても session は復活させない。
|
||||||
|
|
||||||
|
アカウント作成は Principal、Identity、Credential、Domain membership、Role/binding を
|
||||||
|
同じ transaction に含める。初回 owner は管理者グループへの projection まで含め、
|
||||||
|
途中の失敗時にはアカウントも残さない。並行 bootstrap は一つだけ成功する。
|
||||||
|
password hash の計算は writer lock を取得する前に行う。
|
||||||
|
native migration v4〜v7 は Credential、Challenge、Provider 設定、CLI 認証引き継ぎを追加する。
|
||||||
|
v8 は既存の Group/Role mapping と認証監査ログ用テーブルを追加する。監査イベントの新しい発行機能を追加する変更ではない。
|
||||||
|
適用済み migration の SQL/checksum は変更しない。
|
||||||
|
|
||||||
|
ブラウザ/API session の発行は停止・継承失効と同じ writer lock を利用する。
|
||||||
|
token の用途 prefix を hash 対象に含め、Domain 境界と有効な所属を検査する。
|
||||||
|
プロフィールと avatar の読み書き、Domain のアカウント一覧、session 一覧・失効も両 DB に対応する。
|
||||||
|
|
||||||
|
TOTP の登録確定と counter 消費は同じ transaction 内で検証・更新する。
|
||||||
|
SQLite の JSON 関数を PostgreSQL 上で代用せず、Go 側で counter を読み、writer lock で
|
||||||
|
再利用を防ぐ。外部認証の設定保存では、空の secret を指定した更新は UPSERT 内で
|
||||||
|
現在の暗号化 secret を保持する。外部 Identity の競合で別 Principal に紐付け直さず、
|
||||||
|
重複するメールアドレスや表示名は曖昧なマッチとして拒否する。
|
||||||
|
|
||||||
|
CLI の認証要求は同時受付でも件数上限を超えないよう transaction で直列化する。
|
||||||
|
承認消費と API session 発行は一括 commit し、発行失敗時には承認も rollback する。
|
||||||
|
同時 exchange の成功は一つに限り、poll 間隔・origin・Domain・trusted choice を保持する。
|
||||||
|
共通テストは合成データだけを用い、実際の LDAP/OIDC/SMTP サーバーには接続しない。
|
||||||
|
|
||||||
|
`store-city-foundation` は階層・所有者・公開設定・監査記録・公開 manifest の保存用 schema を持つ。
|
||||||
|
`CityGovernance`、所有者候補検索、`ChangeCityGovernance`、`LocalityAccess` は native SQL を使う。
|
||||||
|
変更前に管理者継承と同じ advisory lock を取得し、epoch/topology の比較、上位の公開範囲、
|
||||||
|
所有者の委任権限を検査する。preview は rollback し、実変更は policy・epoch・監査を一括 commit する。
|
||||||
|
上位管理者の ACL を下位所有者が広げることは拒否し、対象者の削除などの縮小だけを許可する。
|
||||||
|
|
||||||
|
`store-locality-foundation` は Path と設定のガードに加え、Zone/Spot/Street所属の変更を
|
||||||
|
保護する PostgreSQL trigger を持つ。ACL のある Domain で enforcing を解除できず、
|
||||||
|
保護 Path の移動・削除・別名による脱出を拒否する。新規 Object を保護範囲内に作成することは許可する。
|
||||||
|
Path の比較には C collation の文字列範囲を使い、`%`、`_`、大小文字、日本語を LIKE の wildcard としない。
|
||||||
|
trigger を無効化・削除した状態は migration の assertion と ACL 変更時の検査で拒否する。
|
||||||
|
将来の City/namespace writer も、行ロックより先に同じ管理用 lock を取得する順序に統一する。
|
||||||
|
|
||||||
|
共通テストでは上位公開範囲の制約、所有者委任、ACL 縮小、同時変更の単一成功、
|
||||||
|
preview の非永続化、監査失敗時の rollback、保護 namespace、失効後の次リクエストを確認する。
|
||||||
|
schema の追加は City 全体の対応完了を意味しない。通常 HTTP ハンドラとの PostgreSQL 統合試験、
|
||||||
|
City 全変更系と他の管理経路からの Role/binding 操作の監査は残る。
|
||||||
|
既存 SQLite の他の mutation から呼ばれる旧 transaction wrapper は
|
||||||
|
SQLite 用のままであり、それらの PostgreSQL 化は呼び出し側の lock 契約も含めて行う。
|
||||||
|
`EnsureAuthSchema` は PostgreSQL の認証・Locality schema 初期化へ接続済み。
|
||||||
|
管理対象 migration の未移植 component は `ErrPostgreSQLComponentNotReady` で拒否し、
|
||||||
|
SQLite migration runner を PostgreSQL 接続へ流さない。本番用 PostgreSQL Store は未公開のままとする。
|
||||||
|
|
||||||
|
#### 公開とユーザー領域の移植
|
||||||
|
|
||||||
|
`store-publication` は公開 manifest の失効と navigation generation 用 trigger を持つ。
|
||||||
|
匿名 Revision 読み取りと navigation は、明示承認と自動公開候補を同一 read-only snapshot で確認する。
|
||||||
|
有効な Campus/Domain、HEAD、hash、別名、公開範囲、公開者の状態を検査し、
|
||||||
|
本文更新・別名追加・権限変更後の次リクエストに失効を反映する。
|
||||||
|
上位の手動承認必須設定は下位の自動公開を止める。
|
||||||
|
PostgreSQL の navigation trigger は statement 単位で更新し、generation を行数ではなく失効 token として扱う。
|
||||||
|
|
||||||
|
`store-publication-approval` の要求作成は domain/idempotency key の競合を UPSERT で処理する。
|
||||||
|
承認は状態・generation・期限を検査し、decision 記録と状態更新を一括 commit する。
|
||||||
|
同時承認の成功は一つだけで、期限切れ整理ジョブの実行前でも期限切れ要求は承認できない。
|
||||||
|
|
||||||
|
`store-user-space` は profile/avatar/root/descendant の公開設定、Path ごとの縮小例外、監査記録を持つ。
|
||||||
|
公開読み取りは有効な本人所属と Domain の上限、本文 HEAD を同じ snapshot で評価し、
|
||||||
|
別名付き Object は匿名公開しない。例外 Path の改名は同じ所有者の namespace に制限し、
|
||||||
|
改名・削除に policy を追従させる。policy 更新と監査記録は一括 commit する。
|
||||||
|
`store-profile-contacts` は電話番号を Principal の一般情報と分離し、
|
||||||
|
本人の同意・profile 公開設定・Domain の上限を満たす場合だけ匿名へ公開する。
|
||||||
|
競合した version は拒否し、非公開時は値だけでなく version/visibility も返さない。
|
||||||
|
|
||||||
|
既存 SQLite の同一時刻 Revision は `rowid` で HEAD を決定する一方、native PostgreSQL は UUID を用いる。
|
||||||
|
新規 native 保存は時刻を単調増加させるが、旧 DB の同時刻データにはその保証がない。
|
||||||
|
全件 import は言語別 HEAD とその参照先を移行前後で照合し、順序の保存方法を確定するまで
|
||||||
|
本番切替を許可しない。core の往復試験だけでこの条件を満たしたと判断しない。
|
||||||
|
|
||||||
|
#### 共通 metadata Repository の実装範囲
|
||||||
|
|
||||||
|
`internal/metadata` は Object 作成、Domain ごとの Path 解決と alias、再帰移動、
|
||||||
|
言語別 Revision HEAD の比較更新、履歴 UUID の参照と非破壊復元、Asset HEAD と
|
||||||
|
履歴の原子的更新を提供する。SQL の placeholder を組み立て時に生成し、
|
||||||
|
SQL 文字列の一括置換は行わない。DB には Document 本文を保持せず、
|
||||||
|
低水準の `AppendRevision` は呼び出し側が Geduldh へ先に検証・永続化した SHA-256 を公開する。
|
||||||
|
`SaveDocument` は参照固定と payload 永続化も含めた保存パイプラインを提供する。
|
||||||
|
Revision の `body` 列は既存形式との橋渡し用の空キャッシュであり、正本ではない。
|
||||||
|
|
||||||
|
PostgreSQL の書き込みは Domain 単位の transaction-level advisory lock を取得し、
|
||||||
|
Revision ではその後に Object 単位の lock も取得する。lock の取得順を統一し、
|
||||||
|
異なる Object の保存でも Domain 内の outbox sequence を直列化する。
|
||||||
|
アプリ用の `NewApplication` は、その前に namespace 管理と共通の advisory lock を取り、
|
||||||
|
有効な Campus と Domain、local 配置を transaction 内で再確認する。
|
||||||
|
順序は namespace 管理 → Domain → Object とする。本文の検証・永続化 I/O 中には取得しない。
|
||||||
|
SQLite は読み取り前に書き込みロックを取得する。
|
||||||
|
全 writer が同じ契約を使う前提で、プロセス内の mutex に依存せずに HEAD を比較する。
|
||||||
|
Revision の時刻は同一言語の前の値より必ず後にし、順序付けに隠れた rowid を使わない。
|
||||||
|
復元は新しい Revision UUID で追加し、過去の Revision を変更しない。
|
||||||
|
埋め込み Document の参照も履歴から引き継ぎ、現在の Asset HEAD へ置き換えない。
|
||||||
|
|
||||||
|
再帰移動は移動先が空であることを検査し、一つの UPDATE で配下を移動する。
|
||||||
|
全 Path のメモリ展開や一件ずつの SQL 発行はしない。Path は SQLite の binary、
|
||||||
|
PostgreSQL の C collation とし、配下の検査は索引を使える文字列範囲で行う。
|
||||||
|
日本語、大小文字、`%`、`_`、仮想フォルダ、同名の別 Domain を区別する。
|
||||||
|
同一 Domain 内の alias 追加は既存 Path を上書きしない。Domain を越えるリンクの
|
||||||
|
取り扱いは認可・共有の移植時に別途実装する。
|
||||||
|
|
||||||
|
`InitializeFresh` は専用 migration 履歴で管理する空 DB/schema 用の初期化である。
|
||||||
|
既存の未管理テーブルがある場合は採用や変換をせず失敗し、既存データを保持する。
|
||||||
|
再実行時には必要なテーブルと列の存在を SELECT assertion で検査し、不足時は停止する。
|
||||||
|
列型、照合順序、索引、一意制約の完全な catalog 検査はまだ対象外である。
|
||||||
|
既存 Store の初期化からは呼ばない。Store の PostgreSQL 分岐には Path 解決、
|
||||||
|
Object/Page 作成、通常 Revision 保存と履歴復元を接続した。アプリ用の Page 作成は
|
||||||
|
Object・origin・Path と `page.created` を一括 commit し、イベント保存失敗時は全て rollback する。
|
||||||
|
`NewApplication` 自体は通常起動の constructor や認可処理ではない。
|
||||||
|
|
||||||
|
保存パイプラインの実装と、変更系のアプリ接続前の残件は次のとおり。
|
||||||
|
|
||||||
|
- [x] DB 非依存の Asset freeze を切り出し、既存 SQLite Store からも利用。
|
||||||
|
- [x] 共通 Repository の `SaveDocument` で Document 永続化、埋め込み Asset 検証、参照記録を接続。
|
||||||
|
- [x] 共通 Repository の Revision 保存と activity outbox の追加を同じ transaction に統合。
|
||||||
|
- [x] 通常保存・復元 HTTP API を Domain 明示の Store 境界へ接続し、PostgreSQL 分岐から新パイプラインを呼び出す。
|
||||||
|
- [x] 言語別 HEAD・履歴 cursor・Document 参照一覧の native SQL と欠損 payload の失敗処理を接続。
|
||||||
|
- [x] 通常の Path 再帰変更、native filename Revision とコピー時の埋め込み参照保持、navigator の追従を接続。
|
||||||
|
- [x] Asset Store API の native SQL と履歴復元を接続。
|
||||||
|
- [ ] Web/API/CLI の変更系を新保存パイプラインへ切り替え。
|
||||||
|
- [ ] Path/City の残る入口・reconciler と関連 metadata を監査し、通常 HTTP と cache invalidation を統合試験。
|
||||||
|
- [ ] 既存 Store の残りの取得・一覧・専用リンク操作・import writer を移植。
|
||||||
|
- [ ] 既存 schema の移行計画、schema drift の assertions、整合性検査を整備。
|
||||||
|
- [ ] 同時 GC との pin 契約、巨大 Asset の検証 I/O の予算と再検証 cache を整備。
|
||||||
|
|
||||||
|
`internal/documentrefs.Freeze` は可変 `asset:` を HTML の参照属性から解決し、
|
||||||
|
SHA-256 URL と出自属性へ固定する。同一 address の解決と同一 hash の参照記録は重複させない。
|
||||||
|
通常テキスト、コード例、非 HTML payload は解決せず、変更不要の HTML token は元の byte 列を維持する。
|
||||||
|
既存 Store は従来の resolver を adapter として使い、PostgreSQL 用の保存では Domain を明示した resolver を使う。
|
||||||
|
外部 URL へアクセスする機能ではない。
|
||||||
|
|
||||||
|
`SaveDocument` は対象 Object の Domain 内の Path と言語別 HEAD を先に確認し、
|
||||||
|
解決した埋め込み payload を検証してから、凍結済み Document を Geduldh へ永続化する。
|
||||||
|
この間に DB transaction や lock は保持しない。その後に HEAD を再比較し、
|
||||||
|
Revision、`revision_document_refs`、`revision.created` の pending outbox、型別 watermark を
|
||||||
|
一つの transaction で確定する。outbox の sequence は型別 watermark から割り当て、
|
||||||
|
増え続けるイベント履歴全体を走査しない。イベント配信と worker lease の移植は別工程である。
|
||||||
|
|
||||||
|
アプリ用 Repository は未紐付け Object に限り作成元 Domain の origin を認め、
|
||||||
|
create/save/bind の順序を維持する。別 Domain に Path が存在する Object へ origin だけで書き込めない。
|
||||||
|
Object のみを渡す旧呼び出しは所属 Domain が一意の場合に限り解決し、複数なら明示指定を要求する。
|
||||||
|
これは認可の代替ではなく、HTTP 側の read/write 権限検査は維持する。
|
||||||
|
|
||||||
|
`SaveRevisionContentInDomain` は期待 HEAD の有無を区別する。空文字の期待値は未作成を要求し、
|
||||||
|
期待値なしは無条件 append とする。CAS 失敗を無条件 append で自動再試行しない。
|
||||||
|
PostgreSQL の `RestoreRevisionInDomain` は過去の本文と埋め込み参照の payload を検証し、
|
||||||
|
現在の Asset HEAD を再解決せず新しい Revision に引き継ぐ。
|
||||||
|
DocumentRoot を必須とし、正本の欠損を空の DB body cache で補修しない。
|
||||||
|
SQLite の既存 writer と復元の参照固定動作は維持しており、その統一は別の変更単位とする。
|
||||||
|
|
||||||
|
Path の native 変更処理は namespace 管理 lock を取得してから snapshot を再検証する。
|
||||||
|
移動・コピー・一括 unlink は最大 10,000 Path、30 秒の transaction 予算で実行し、
|
||||||
|
`%`・`_` をワイルドカードにしない索引範囲を使う。予算超過時に部分適用はしない。
|
||||||
|
再帰移動では City 境界、ユーザー領域の公開例外、保存した navigator の Path を同じ transaction で更新する。
|
||||||
|
既存の locality ACL によって保護された namespace の移動・削除は引き続き拒否する。
|
||||||
|
ACL を自動的に別の Path へ拡張する機能や DB guard の迂回は追加しない。
|
||||||
|
公開 manifest と navigation generation は既存の native trigger で失効する。
|
||||||
|
|
||||||
|
native のファイル名変更は、言語別 HEAD の参照 hash を保つ新 Revision を追加する。
|
||||||
|
コピーでは新 Object/Revision UUID を割り当て、全 Revision と埋め込み参照の対応を同じ transaction で複製する。
|
||||||
|
本文 blob は再利用する。unlink は履歴と blob を消さず、City の定義も自動削除しない。
|
||||||
|
コピー履歴で同時刻の旧 HEAD を維持する条件は、全件 import の順序問題と合わせて確認する。
|
||||||
|
|
||||||
|
City の読み取りは PostgreSQL の repeatable-read snapshot を利用する。
|
||||||
|
整理操作は topology version を管理 lock 内で照合し、Page placement、Spot relation、監査記録を一括更新する。
|
||||||
|
Page の URL は Spot 整理では変更しない。境界検査は最大 4,096 node に制限し、
|
||||||
|
Spot 整理の既存の選択数・展開 Page 数・relation 数上限も維持する。
|
||||||
|
Asset 復元は payload の hash を検証してから期待 HEAD を比較更新する。
|
||||||
|
削除は mutable Asset を取り除くが、履歴と既存 Revision からの参照は保持する。
|
||||||
|
|
||||||
|
payload 永続化後に競合や DB エラーが起きた場合、参照のない不変 blob が残ることは許容する。
|
||||||
|
同じ hash を別 writer が利用する可能性があるため、保存失敗時に blob を削除しない。
|
||||||
|
参照のない blob の回収は pin と保持期間を持つ GC の役割とし、同時削除を行う構成では
|
||||||
|
pin 契約の接続が済むまで新パイプラインを有効にしない。
|
||||||
|
|
||||||
|
portable core の v1 定義は変更せず、参照と outbox のスキーマを v2 として追加した。
|
||||||
|
試験用 v1 の既存行を維持した移行、DDL 途中失敗時の rollback、再試行を共通テストで確認する。
|
||||||
|
これは本番 SQLite からのデータ移行機能ではない。
|
||||||
|
|
||||||
|
既存 SQLite Store では、Revision の outbox 用 Domain 取得時に未知の SQL エラーを
|
||||||
|
無視しないよう是正した。outbox 自体がない最小 fixture は従来どおり扱うが、
|
||||||
|
outbox がある状態での取得・書き込みエラーは Revision と一緒に rollback する。
|
||||||
|
|
||||||
|
共通テストでは Domain 分離、言語の分離、同時 CAS、重複作成時の orphan 防止、
|
||||||
|
Revision の不変性、復元時の競合、Asset 履歴の故障注入 rollback を検証する。
|
||||||
|
保存パイプラインでは payload 書き込み失敗、埋め込み検証失敗、保存 I/O 中の別編集、
|
||||||
|
参照・outbox の故障注入、異なる Object の並行 sequence 採番も検証する。
|
||||||
|
これらは変更系 Web/API の PostgreSQL 対応完了を意味しない。
|
||||||
|
|
||||||
|
`PAGESWIKI_TEST_POSTGRES_DSN` に使い捨て PostgreSQL の URL を指定すると、
|
||||||
|
`go test -race -count=1 ./internal/db ./internal/metadata ./internal/documentrefs` が実 DB と参照固定のテストを実行する。
|
||||||
|
各テストはランダムな schema を作成し、終了時にその schema だけを削除する。
|
||||||
|
試験用ユーザーには CREATE SCHEMA 権限が必要で、本番 DSN は使用しない。
|
||||||
|
DSN を指定しない通常テストでは実 DB 部分だけが skip されるため、
|
||||||
|
PostgreSQL 対応のリリースゲートでは DSN 指定を必須とする。
|
||||||
|
初期検証対象は PostgreSQL 17。最低対応版の確約は CI matrix の整備後とする。
|
||||||
|
|
||||||
|
展示環境では metadata の PostgreSQL 化だけで NFS 対応完了とはしない。
|
||||||
|
Document の no-replace publish と directory fsync、カレンダー正本の lock と atomic rename、
|
||||||
|
秘密鍵とバックアップの配置を別々に検証する。PostgreSQL 自体の PGDATA を
|
||||||
|
未検証の共有 NFS へ移すことで SQLite の問題を置き換える運用は採用しない。
|
||||||
|
DB 用の適切な永続領域または外部 PostgreSQL を確保する。
|
||||||
|
|
||||||
|
#### 移植診断と停止状態の往復リハーサル
|
||||||
|
|
||||||
|
`pageswiki schema portability --db FILE --json` は既存 SQLite を読み取り専用で開き、
|
||||||
|
テーブルの担当領域、未対応テーブル・view・trigger・index、portable migration 履歴、
|
||||||
|
既知 core の catalog の差を報告する。行の値、DDL 本文、DSN、秘密鍵は出力しない。
|
||||||
|
DB がなければ作成せず終了し、初期化や migration は行わない。
|
||||||
|
アプリ全体が未対応の間は `application_ready=false` と終了コード 1 を返す。
|
||||||
|
`core_compatible=true` は下記の限定リハーサルに必要な契約であり、本番移行の許可ではない。
|
||||||
|
未対応テーブルを削除してこの診断を通すことはしない。
|
||||||
|
|
||||||
|
`InspectPortability` は SQLite では既知 core の生成 DDL と索引を厳密に照合し、
|
||||||
|
PostgreSQL では列型、NOT NULL、default、collation、identity、主キー・一意制約・外部キー・CHECK、
|
||||||
|
通常索引の定義と有効状態、sequence の設定を検査する。未知の unique index も無視しない。
|
||||||
|
PostgreSQL の RLS、独自 policy・trigger・routine・rule・sequence、継承・partition 等の未移植の状態は拒否する。
|
||||||
|
trigger は情報スキーマの権限による非表示に依存せず catalog から確認する。
|
||||||
|
PostgreSQL で検査する範囲は現在の schema であり、別 schema のアプリを含む全 DB の認証評価ではない。
|
||||||
|
backend 固有の migration ledger は checksum を検査するが、相手側へコピーしない。
|
||||||
|
|
||||||
|
`CloneCoreForRehearsal` は内部テスト用の core コピーであり、本番用 CLI には公開しない。
|
||||||
|
対象は Object、origin、Path、Revision、Asset、Asset 履歴、Revision の Document 参照、
|
||||||
|
activity outbox と型別 watermark の 9 テーブルに限る。認証、設定、タスク等の
|
||||||
|
追加テーブルがある実稼働 DB は拒否する。全 writer と GC の停止を呼び出し側の前提とし、
|
||||||
|
オンライン移行や二重書き込みを行う機能ではない。
|
||||||
|
|
||||||
|
コピーでは一つの source snapshot から主キー順に行を読み、型付きの値を保って
|
||||||
|
空の staging DB/schema に挿入する。一度に保持するのは一行分であり、最大の一行自体の
|
||||||
|
メモリ使用量は別の制約になる。移行元の DB を変更せず、移行先が空でない場合、
|
||||||
|
同じ DB を別 connection pool から指定した場合、未知の schema がある場合は拒否する。
|
||||||
|
移行先の全 core テーブルを保護し、途中でエラーが起きた場合はコピーした全行を rollback する。
|
||||||
|
文字コード不正、NUL、TEXT 列の BLOB、整数型の不整合、参照欠損を黙って変換しない。
|
||||||
|
|
||||||
|
照合は件数だけではなく、テーブル名・列順・主キー順の各行を長さ付きで SHA-256 に入力する。
|
||||||
|
64bit 整数を浮動小数へ変換せず、日本語、大小文字、異なる Unicode 表現、`%`・`_` を保つ。
|
||||||
|
履歴の採番は現存する最大 ID と generator の保持状態の両方から次の値を決め、
|
||||||
|
過去の ID が再利用されないようにする。PostgreSQL では非 transactional な `setval` ではなく、
|
||||||
|
コピー transaction 内で identity を `RESTART` する。
|
||||||
|
|
||||||
|
参照先の不変 Document は、別途保持する同一の Geduldh Store で SHA-256 を検証する。
|
||||||
|
この関数は blob、カレンダー正本、鍵、インスタンス設定をコピーしない。
|
||||||
|
SQL だけの指紋一致をインスタンス全体のバックアップや復元の成功とは扱わない。
|
||||||
|
実 DB テストでは PostgreSQL 側の追加更新を含めて別の SQLite へ戻し、内容指紋の一致と
|
||||||
|
その後の採番を確認する。未知の制約・RLS・索引の拒否、コピー途中失敗の rollback、
|
||||||
|
source の不変性、Document 欠損、同一 DB への自己コピーも検証する。
|
||||||
|
|
||||||
|
#### 本番 PostgreSQL 移行の受入ゲート
|
||||||
|
|
||||||
|
今回の対象は、全 writer を停止した状態での SQLite→PostgreSQL の片方向インポートと、
|
||||||
|
移行後の通常運用である。PostgreSQL→SQLite の逆移行、自動切り戻し、二重書き込み、
|
||||||
|
オンライン差分同期は今回の実装・受入条件から除外する。
|
||||||
|
既存の core 往復テストは回帰テストとして残すが、本番全件の逆移行へ拡張する作業は行わない。
|
||||||
|
移行前バックアップと片方向インポートの整合性検証は引き続き必須とする。
|
||||||
|
|
||||||
|
2026-11-14 の棚卸しでは Store の SQL 呼び出し点は約 100 ファイル・967 か所ある。
|
||||||
|
これはすべてが SQLite 固有であるという意味ではないが、接続層と core だけでは
|
||||||
|
通常起動・認可・全アプリ機能を満たさない。次の未完了ゲートを残す。
|
||||||
|
|
||||||
|
2026-11-15 時点の受入条件は以下の 8 工程に整理する。1 と 2 の主要 DB 処理は共通テストを通過したが、
|
||||||
|
通常 HTTP/scheduler/CLI 経由の PostgreSQL 統合は工程 7 と合わせて検証する。
|
||||||
|
工程数は受入ゲートの区分であり、8 回の変更や応答で完了するという工数見積もりではない。
|
||||||
|
|
||||||
|
| 順序 | 残工程 | 本番切替前の受入条件 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1 | 認証と権限の統合 | 認証・公開・承認・ユーザー領域の DB 処理は移植済み。残る管理経路の直接 SQL、通常 HTTP 認証と navigation cache の PostgreSQL 統合を確認 |
|
||||||
|
| 2 | Domain と Campus と federation の統合 | namespace CRUD・管理者継承・token・instance・署名 manifest は移植済み。controller/managed プロセスの再起動、鍵・instance identity の保持と HTTP 配信を確認 |
|
||||||
|
| 3 | core と Document と City の接続 | 全 Store 変更系、GC pin、検証 I/O の予算、Document root identity、Asset 復元、Path 移動・削除時の City 境界・ACL・関連リンク・filename Revision・snapshot 検査・cache 失効を接続 |
|
||||||
|
| 4 | タスクと CalDAV と各拡張 | プロジェクト所属、VTODO、ETag/ctag/sync-token、通知、連絡先・RSS・ブログ等の repository と対応テーブルを移植 |
|
||||||
|
| 5 | ジョブと通知 | claim/lease/fencing、キャンセル、outbox 消費、重複排除、再起動時の処理、ログ保持を検証 |
|
||||||
|
| 6 | 検索と管理 | FTS5/rowid/PRAGMA/JSON 関数・照合順序への依存を分離し、権限付き検索・一覧と管理設定を検証 |
|
||||||
|
| 7 | 通常起動と設定 | backend 別 bootstrap、全 Ensure、secret 参照、schema 診断、readiness、CLI/standby の接続を統一し、PostgreSQL で全体試験を通過 |
|
||||||
|
| 8 | 全件インポートと切替 | 全正本テーブルの片方向インポート、再生成可能 cache の分類と再構築、canonical files・鍵の保持、件数・参照・内容指紋・採番の整合性、移行前 backup と PostgreSQL backup/restore を検証し、停止状態で本番切替 |
|
||||||
|
|
||||||
|
MySQL、S3、Redis、HA、逆移行はこの 8 工程の完了条件に追加しない。
|
||||||
|
|
||||||
|
#### 初回切替を短縮する場合の残件
|
||||||
|
|
||||||
|
初回は単一インスタンス・ローカル Document root・停止状態での片方向 import を対象とする。
|
||||||
|
利用者は必須残件を先行し、任意機能をリリース後へ回す方針を了承した。
|
||||||
|
Push 配信・zombie GC・ログの保持期限処理・hosted editor session には native 停止ゲートを実装した。
|
||||||
|
その他の機能を停止する場合も利用者へ制限を示したうえで、
|
||||||
|
起動時・HTTP・CLI・worker の全入口を同じ機能ゲートで拒否する。
|
||||||
|
`NewPostgreSQLWithDocumentRoot` で native の通常 Store を初期化し、
|
||||||
|
合成データによる Server 起動・HTTP 操作・停止後の再初期化まで接続した。
|
||||||
|
`cmd/pageswiki/main.go` は `PAGESWIKI_DB_BACKEND=postgresql` による選択と、
|
||||||
|
全件 import の完了記録・鍵・Document root の一致検査を接続した。未指定時は SQLite のままである。
|
||||||
|
全件転送は `pageswiki migrate-postgres` を使用する。
|
||||||
|
`internal/metadata/portability.go` の core 限定リハーサルとは別の実装である。
|
||||||
|
|
||||||
|
切替に直結する実装順序は次のとおりとする。
|
||||||
|
|
||||||
|
1. ジョブ基盤と outbox の統合。DB 層の claim・完了 token・再起動時の中断扱い・重複排除、
|
||||||
|
Task/Calendar/RSS のイベント登録は移植済み。Server の起動で worker owner を取得し、
|
||||||
|
停止と join 後に解放する。native 通常 Store による HTTP・再初期化・worker 二重起動拒否を検証済み。
|
||||||
|
2. 通常起動・検索・管理経路の接続。backend 明示の Store 初期化、主要画面、
|
||||||
|
内蔵エディタ保存、認証失効、DAV discovery まで接続済み。
|
||||||
|
本番用 backend 選択も接続済み。認証、ACL、公開範囲は省略しない。
|
||||||
|
3. 全件 import。全正本テーブル・鍵・設定・受付/操作履歴・同期番号を列挙し、
|
||||||
|
cache と区別して保全する。identity 採番、本文参照、件数・内容指紋と再実行を検証する。
|
||||||
|
4. 隔離した通常 HTTP 起動と再起動試験、backup/restore 検証後に停止移行する。
|
||||||
|
実行する機能の CRUD、DAV 条件付き更新、権限失効、失敗時の rollback を通してからリリースする。
|
||||||
|
|
||||||
|
| 後回しにできる候補 | 初回切替で必要な条件と制限 |
|
||||||
|
| --- | --- |
|
||||||
|
| HA/LB/DR、無停止・オンライン移行 | 単一インスタンス、旧系の writer を停止した import に限定。PostgreSQL の backup/restore は省略しない |
|
||||||
|
| PostgreSQL から SQLite への逆移行 | 既定どおり対象外。旧 backup からの復旧は、切替後の更新を引き継ぐ逆移行とは別物 |
|
||||||
|
| 自動 GC の同時実行と pin 機構 | native zombie GC は定期実行・手動 API・Store の全入口を拒否する。本文ファイルの GC を新設せず、容量を監視する。本文参照・hash の整合性検証は残す |
|
||||||
|
| 高度な全文検索・ランキング最適化 | native は権限付き Path/ファイル名検索と City メタデータ検索を実装。Page 本文・H1 の検索とサジェストへの H1 付与は未対応。FTS5 や全本文走査で代用しない |
|
||||||
|
| hosted editor | native は起動・ticket 交換・session 取得・保存を拒否し、選択肢から除外する。設定と既存 session は保全し、内蔵エディタを使用する。session の base revision 更新と本文保存をまたぐ整合性は後続対応 |
|
||||||
|
| サムネイル再生成・リソース履歴のグラフ | 対象イベントと API を明示的に無効化。正本と派生 cache/履歴の分類を先に確定し、未分類テーブルを捨てない |
|
||||||
|
| Push/SMTP/外部サービスへの送信 | 配信だけを停止する制限運用は可能だが、Inbox と受付履歴は保持する。不明な送信結果を成功や再送待ちへ変換しない |
|
||||||
|
| ログの自動保持期限処理 | native では定期 cleanup を実行せず、手動呼び出しも拒否する。ログと集計を保全する代わりに容量監視が必要。policy 別の件数・実行時間を制限した cleanup は後続対応 |
|
||||||
|
| MySQL、S3、Redis 等の追加 backend | 今回の PostgreSQL 切替とは別プロジェクトとして扱う |
|
||||||
|
|
||||||
|
全件 import、通常起動、認証/公開権限、正本ファイルと鍵の保全、必要機能の統合試験、
|
||||||
|
移行前 backup は短縮対象にしない。機能縮小で省けるのは各機能の稼働対応であり、
|
||||||
|
その機能が持つユーザーデータの保全ではない。
|
||||||
|
|
||||||
|
#### ジョブと HTTP 接続の移植状況
|
||||||
|
|
||||||
|
`store-event-jobs` は PostgreSQL 用の独立 migration とし、定義、キュー、ログ、集計と設定を作成する。
|
||||||
|
native worker は専用接続の advisory lock により同一 DB/schema に一つだけ起動できる。
|
||||||
|
これは単一インスタンス用の排他であり、HA の lease/failover を提供するものではない。
|
||||||
|
接続が利用不能なら新規 claim を拒否する。
|
||||||
|
`Server.NewChecked` は worker owner 取得・イベント登録の失敗を起動エラーとして返す。
|
||||||
|
`Runner.Stop` は受付を止めて実行中処理を cancel し、完了状態保存を待つ。
|
||||||
|
`Server.Close` は scheduler loop・保守処理・worker の終了後に排他を解放する。
|
||||||
|
停止待ちの timeout は終了完了を意味せず、実行中処理が残る間は排他を保持する。
|
||||||
|
main の SIGTERM/Ctrl+C は Campus 同期の新規開始を止め、進行中同期の終了を待ち、
|
||||||
|
HTTP と worker の停止へ接続した。各外部同期要求は従来の network timeout を使う。
|
||||||
|
|
||||||
|
ジョブの claim、同時実行数とキュー深さの検査、再試行は writer transaction 内で行う。
|
||||||
|
完了には claim ごとの token を要求し、再試行・再起動前の worker の完了を拒否する。
|
||||||
|
完了状態の保存後にログ保存が失敗しても、副作用のあるジョブを自動で再実行しない。
|
||||||
|
再起動時に残る running は結果不明として failed にし、明示的な再試行を待つ。
|
||||||
|
schema 初期化だけで稼働中のジョブを奪わない。
|
||||||
|
|
||||||
|
定期イベントの enqueue と次回日時の更新は同一 transaction で行い、キュー満杯なら両方を rollback する。
|
||||||
|
組み込みイベントの登録は管理者による無効化や周期変更を上書きしない。
|
||||||
|
Task の活動通知、期限通知、Focus、日次メール、RSS、Calendar sweep の登録を接続した。
|
||||||
|
外部配信の実行可否は別の制限であり、登録の移植完了をもって配信を有効化しない。
|
||||||
|
|
||||||
|
outbox の正本 journal と型別 watermark は core 所有のままとし、
|
||||||
|
`store-activity-consumers` が通知先ごとの checkpoint と検索 index を追加する。
|
||||||
|
型別に件数を制限して読み込み、別 consumer の処理済み状態に影響されず、
|
||||||
|
checkpoint の更新は単調増加とする。投影処理と同一 transaction で rollback できる API を維持する。
|
||||||
|
|
||||||
|
HTTP に残っていた Object alias、Calendar の active member、City zone kind、ブログ射影先、
|
||||||
|
設定変更対象の Campus 解決、個人表示設定の直接 SQL は Store API に移した。
|
||||||
|
参照は件数/時間を制限し、alias と射影先の権限判定は引き続き HTTP 側で行う。
|
||||||
|
管理対象を解決できない場合は現在の Campus へ fallback せず拒否する。
|
||||||
|
個人表示設定は現在の membership を再検査し、CAS と read-only 拒否を適用する。
|
||||||
|
`EnsureTasksSchema` は native foundation と productivity migration へ接続した。
|
||||||
|
|
||||||
|
アナウンス、プレビュー解析 cache、リソース履歴も native migration と Store API に接続した。
|
||||||
|
アナウンスは Domain を跨いだ同一 UUID の上書きを拒否し、削除時は Inbox との transaction を維持する。
|
||||||
|
プレビュー解析 cache は PostgreSQL の byte 長で容量を制限し、resource sample は job UUID で重複排除する。
|
||||||
|
これらの変更は起動依存の移植であり、新しい表示機能の追加ではない。
|
||||||
|
|
||||||
|
Push は鍵・購読・配送状態を保持する schema のみ作成し、Inbox INSERT trigger は設置しない。
|
||||||
|
Store の登録・claim・完了・cleanup、HTTP、キー生成、配信の入口で拒否する。
|
||||||
|
native 定期 enqueue と claim は Push を除外し、既存定義の日時や不明な配送状態を書き換えない。
|
||||||
|
停止されたログの期限処理と zombie GC も、機能設定の変更で再有効化できない backend 制限とする。
|
||||||
|
|
||||||
|
HTTP 検索の SQLite 直接生成を Store 経由に変更し、native では Path と元ファイル名を検索する。
|
||||||
|
最新 revision の MIME/拡張子/更新日時、Object 作成日時による絞り込みを候補 LIMIT 前に適用する。
|
||||||
|
候補は最大 1,000 件、返却は最大 200 件、SQL と権限判定の予算は 2 秒とし、
|
||||||
|
本文ファイル・legacy body 列を検索やタイトル補完のために走査しない。
|
||||||
|
候補 cursor を閉じてから権限判定するため、1 接続の pool でも権限問い合わせを実行できる。
|
||||||
|
検索・サジェスト HTTP の `X-PagesWiki-Search-Profile: metadata-only` はこの制限を表す。
|
||||||
|
対象範囲に候補が 1,000 件を超える場合、候補制限による取りこぼしはあり得る。
|
||||||
|
|
||||||
|
City 検索は native の read snapshot 内で種類ごと最大 1,000 件のメタデータを集め、
|
||||||
|
transaction を閉じてから Quartier・Street を含む親階層の権限を確認する。
|
||||||
|
Domain/Path 境界、日付条件、未定義 Spot の Street へのリンクを維持する。
|
||||||
|
Page のファイル種別指定時には City 要素を混ぜない。
|
||||||
|
|
||||||
|
hosted editor は `store-adapter-sessions` に ticket/session/base revision を保全する。
|
||||||
|
native では Store と HTTP の操作入口を拒否し、アダプタ選択肢から editor plugin を除外する。
|
||||||
|
閲覧用 plugin と内蔵エディタはこの制限の対象外である。
|
||||||
|
既定 editor の設定を削除したり、残存 ticket を期限切れ cleanup で消したりしない。
|
||||||
|
|
||||||
|
この検索・保全ガードは合成データの PostgreSQL 17 と SQLite で検証した。
|
||||||
|
`go test ./...`、対象の race 検査、`go vet ./...`、`cmd/pageswiki` のビルドを通過した。
|
||||||
|
検索検査には 1 接続での権限問い合わせ、Domain・親階層の拒否、文字列のリテラル一致、
|
||||||
|
1,100 件の候補に対する LIMIT 前の絞り込み、過去 revision の除外、cancel を含む。
|
||||||
|
検索の repository 統合検証とは別に、次の通常 HTTP 起動検証を行う。
|
||||||
|
|
||||||
|
`NewPostgreSQLWithDocumentRoot` は鍵と Document root を先に検査し、native schema を依存順に初期化する。
|
||||||
|
欠落・不正な `auth.key` を生成し直さず、`PAGESWIKI_AUTH_KEY` を指定しない場合は既存の 32 byte 鍵を要求する。
|
||||||
|
Campus/Domain 未配置、所有 Campus が存在しない Domain、Domain が存在しない Path は起動を拒否する。
|
||||||
|
既存の無効 Campus を既定 Campus へ付け替えず、SQLite の legacy body backfill も実行しない。
|
||||||
|
`BackfillDocuments` の native 呼び出しは明示的に拒否する。
|
||||||
|
正本ファイル全件の hash 照合は import/restore 工程の責務であり、この constructor だけでは保証しない。
|
||||||
|
|
||||||
|
合成データの PostgreSQL 17 で通常 Store と `Server.NewChecked` を組み合わせ、
|
||||||
|
実 HTTP listener の本文取得、主要画面と管理パネル、内蔵エディタ保存と競合 409、
|
||||||
|
無効・失効セッションの 401、CalDAV/Task DAV/CardDAV の discovery を検証した。
|
||||||
|
同じ DB と Document root で Server を停止・再初期化し、本文と認証 session の継続を確認する。
|
||||||
|
稼働中の別 worker 起動は拒否し、停止完了後に再取得できる。
|
||||||
|
resource event の保存は同じ job UUID で再実行しても重複しない。
|
||||||
|
管理画面の最近の Object は native query に分岐し、Domain 内の代表 Path と最新 revision のみを扱う。
|
||||||
|
返却上限 200 件・SQL 予算 2 秒とし、Page 本文は読み込まない。
|
||||||
|
|
||||||
|
全件 import と内容照合、本番 backend 選択、合成データの PostgreSQL dump/restore は接続した。
|
||||||
|
停止切替のコマンドと制限は [PostgreSQL 移行手順](../operations/postgresql-migration.md) にまとめる。
|
||||||
|
本番切替には、移行前の一貫したバックアップと、そのインスタンスの schema preflight・全件 import の成功が必要である。
|
||||||
|
合成データの試験通過は、本番データの移行完了を意味しない。
|
||||||
|
|
||||||
|
`application_import_catalog.go` は保全対象と SQLite 専用索引・migration ledger の列を固定する。
|
||||||
|
未知のテーブル・列・trigger/view 定義を検出したら拒否し、cache と推測して捨てない。
|
||||||
|
移行先に既存データがある場合は schema 準備の前に拒否する。
|
||||||
|
データ転送は単一 transaction とし、schema が用意した既定行のみを置換する。
|
||||||
|
一時停止するのは派生状態を更新する user trigger だけで、FK・CHECK・UNIQUE は維持する。
|
||||||
|
各テーブルの型付き内容指紋・件数、Document の SHA-256、namespace の参照を照合する。
|
||||||
|
SQLite の削除済み最大採番も保持し、transactional identity restart で番号の再利用を防ぐ。
|
||||||
|
タスク DAV の内部索引キーと削除 tombstone は NUL 区切りから native v1 base64url 形式に変換する。
|
||||||
|
この変換を report に明示し、正本 JSON とクライアントに公開する href は変更しない。
|
||||||
|
失敗時の全件 rollback、修正後の再試行、重複 import 拒否、認証 session・画像・日本語タグ、
|
||||||
|
プロジェクト別タスク・連絡先 sync-token の継続を合成データで検証する。
|
||||||
|
同じ正本ファイルを保持した schema 単位の `pg_dump`/`pg_restore` 後も本文・認証・DAV を検証する。
|
||||||
|
|
||||||
|
#### 次の実装単位と検証状況
|
||||||
|
|
||||||
|
工程 3 の通常保存・履歴取得・復元は Store 境界へ接続済みである。
|
||||||
|
エディタ保存 API は Domain と期待 HEAD を明示し、PostgreSQL 分岐から本文永続化・参照固定・
|
||||||
|
Revision・outbox を一つの契約で扱う。SQLite は既存保存動作を維持する。
|
||||||
|
PostgreSQL の通常 HTTP 経路では保存と期待 HEAD 競合を確認済み。
|
||||||
|
履歴復元を含む残る操作の HTTP 確認は工程 7 に残る。
|
||||||
|
|
||||||
|
`path_mutation.go`/`path_snapshot.go` の通常操作、`city_operations.go`/`city_organize.go`、
|
||||||
|
City map 読み取りと Asset Store API は移植済みである。
|
||||||
|
`city.go` の個別作成・削除・relation、`city_plan.go` の一括変更計画、ページ一覧と
|
||||||
|
アーカイブ import 管理も移植済みである。City の作成・配置・再帰削除と計画適用は
|
||||||
|
共通 namespace lock の中で topology version と監査イベントを更新し、途中の SQL 失敗は rollback する。
|
||||||
|
`EnsureCitySchema` は native schema と公開制御の migration へ接続した。
|
||||||
|
|
||||||
|
自動生成の候補取得と名前判定は Store API に集約し、候補 cursor を閉じてから階層を解決する。
|
||||||
|
同じ境界の解決結果は一回の plan 構築中に再利用し、DB 故障を「既存要素なし」として扱わない。
|
||||||
|
候補は 20,000 件を上限とし、超過時に途中までの City を適用しない。
|
||||||
|
定期・編集イベントからの実行は scheduler 移植と統合して検証する。
|
||||||
|
|
||||||
|
children は Domain 全件を Go へ読み込まず、対象 subtree から直下要素を SQL で抽出する。
|
||||||
|
DB generation とプロセス内の cache epoch で別 Store の変更・取得中の失効に追従する。
|
||||||
|
Browser と children の列挙上限は 20,000 件、問い合わせは timeout 付きとし、超過を明示する。
|
||||||
|
PostgreSQL の Browser title は本文 cache ではなく canonical HTML の先頭 64 KiB から取得する。
|
||||||
|
一回の title 読み取りは 32 MiB と timeout で制限するが、DocumentSize の個別 I/O は残る。
|
||||||
|
権限付き Object metadata 一覧は既存の候補・alias 上限と継続 cursor を維持する。
|
||||||
|
|
||||||
|
アーカイブ import は独立 migration `store-imports` でセッション、計画、journal を作成する。
|
||||||
|
Path rollback とセッション状態更新は一つの transaction とし、import 時と Object が一致する
|
||||||
|
binding だけを削除する。City cleanup はそれに先行する再試行可能な別フェーズであり、
|
||||||
|
City と Path を一括 rollback する transaction ではない。
|
||||||
|
旧 worker の void 状態更新 API は失敗を呼び出し元へ返せないため、scheduler 移植時に
|
||||||
|
エラー伝播・状態遷移・再試行を併せて整理する。
|
||||||
|
|
||||||
|
工程 3 の残件は
|
||||||
|
`domain_paths.go` 等の legacy schema adoption と bootstrap の分離、残る直接 SQL writer の棚卸し、
|
||||||
|
import worker のエラー伝播、Path 変更を消費するイベント処理との統合である。
|
||||||
|
同時 GC の pin、Document root identity、巨大 payload 検証の I/O 予算も起動前のゲートとして残す。
|
||||||
|
すべての Path/Revision writer の同じ排他契約への接続が済むまで PostgreSQL の通常起動は許可しない。
|
||||||
|
|
||||||
|
工程 4 は task/CalDAV、calendar、contacts/CardDAV、feeds、periodicals の順に
|
||||||
|
保存スキーマ・変更処理・一覧・ETag/同期 token を一組ずつ移植する。
|
||||||
|
タスクやカレンダーの処理を停止して起動検証だけを通す方式は採用しない。
|
||||||
|
工程 5 と 6 の job claim、notification、全文検索も同様に機能契約を保つ。
|
||||||
|
|
||||||
|
タスク本体は `store-tasks-foundation` の native 空 DB schema と Store 操作を追加した。
|
||||||
|
保存・削除・DAV 設定更新は権限の再確認前に共通 namespace lock を取得する。
|
||||||
|
task head、履歴、変更 journal、outbox、DAV index、通知予約、達成度 index は
|
||||||
|
一つの保存 transaction に含める。削除は tombstone を残し、Wiki とカレンダーを削除しない。
|
||||||
|
一覧では JSON 抽出、文字列検索、パラメータ番号、階層 cursor の真偽値を backend 別に扱う。
|
||||||
|
|
||||||
|
SQLite の DAV 内部索引は NUL 区切りを含むが、PostgreSQL の TEXT は NUL を格納できない。
|
||||||
|
native 内部キーは `v1:{base64url(project)}:{base64url(value)}` とし、既定 collection も同じ方式にする。
|
||||||
|
外部 URI・resource 名・UID・canonical JSON は変更しない。全件 import では derived DAV index を
|
||||||
|
canonical head から再構築し、削除 tombstone の `dav_name`/`dav_uid` も旧 NUL 形式から変換する。
|
||||||
|
この変換なしに SQLite の該当列をそのままコピーしてはならない。
|
||||||
|
|
||||||
|
個人既定値、作業時間、Pomodoro、日次集計、ダッシュボードと予定枠の DB 予約は移植済みである。
|
||||||
|
設定と配置の version を独立させ、作業時間の訂正・取消は監査履歴と同時に commit する。
|
||||||
|
writer は権限確認前に共通 namespace lock を取り、対話的な更新は 5 秒で timeout する。
|
||||||
|
`store-task-productivity` の追加 migration で Focus span と予定枠の title を導入し、
|
||||||
|
既存の `store-tasks-foundation` migration は変更しない。
|
||||||
|
|
||||||
|
`store-notification-inbox` は Inbox のみを作成する。通知挿入は一意キーの競合を
|
||||||
|
transaction 内で処理し、別プロセスからの重複要求も同じ UUID を返す。
|
||||||
|
タイマー完了・期限/着手日の通知は、Inbox 挿入と元の状態更新を同じ transaction に含める。
|
||||||
|
通知保存が失敗した場合は元の状態も rollback し、次回に再試行できる。
|
||||||
|
活動 journal の補完は既存 outbox の冪等キーを再利用する。
|
||||||
|
配信候補は最大 100 件・3 秒に制限し、読めなくなった所属先の情報を通知へ複製しない。
|
||||||
|
|
||||||
|
タスク capture/Wiki 同時作成と再作成、プロジェクト配下のメモ作成は移植済みである。
|
||||||
|
native では Object の作成元 Domain と primary Path を明示し、本文は canonical Document に置く。
|
||||||
|
Task・受付記録・Object・Path・Revision・outbox は同じ transaction で commit する。
|
||||||
|
入力本文は HTML とマクロをエスケープし、削除後の明示的再作成でも既存の Wiki 本文を変更しない。
|
||||||
|
受付記録だけ残っている不整合は自動復活させず、修復が必要なエラーとして扱う。
|
||||||
|
|
||||||
|
メールダイジェストの claim・送信履歴・明示的再試行も移植済みである。
|
||||||
|
共通 namespace lock と状態条件で scheduled/manual claim を一意にし、同意・設定 version・
|
||||||
|
所属権限を再確認する。送信結果が不明な試行は自動再送せず、本人の重複送信了承を必要とする。
|
||||||
|
90 日経過で詳細履歴を削除しても、日次予約と再試行の受付記録は重複防止のため保持する。
|
||||||
|
保守処理は 3 秒・中断判定 100 件・履歴削除 500 件に制限する。
|
||||||
|
|
||||||
|
カレンダーは `calendar-cache` migration で PostgreSQL の月別/イベント索引を作成する。
|
||||||
|
正本は従来どおり月別 ICS と `calendar.json` の manifest であり、DB には移さない。
|
||||||
|
明示的な backend 選択を HTTP の Repository 初期化へ接続し、予約済みタスク予定枠の
|
||||||
|
正本作成・移動後の再試行と日次予定の cache projection を検証する。
|
||||||
|
manifest 更新後の索引再構築失敗は transaction を rollback し、次回アクセスで修復する。
|
||||||
|
cache 更新は 30 秒で打ち切る。全 writer は同じ正本 root と有効な flock を共有する必要があり、
|
||||||
|
独立した filesystem を持つ replica 間の HA は未対応である。
|
||||||
|
任意の DAV filename を UID として復号する際は UTF-8 と制御文字を検証し、
|
||||||
|
非テキストの復号結果を PostgreSQL の TEXT パラメータへ渡さない。
|
||||||
|
|
||||||
|
連絡先は `store-contacts` migration で native schema と変更 journal の trigger を導入する。
|
||||||
|
vCard 正本・履歴 hash・任意 resource 名・tombstone を維持し、更新と変更番号を同時 commit する。
|
||||||
|
CardDAV の inventory と sync-token は PostgreSQL の REPEATABLE READ で同じ snapshot から取得する。
|
||||||
|
metadata inventory は vCard 本文を返さず、UTF-8 の byte 長を返す。
|
||||||
|
保存と snapshot 取得は 5 秒で timeout し、保存は権限・資格情報確認前に共通 namespace lock を取る。
|
||||||
|
全 DB import 時は contact epoch と変更番号を保全し、identity sequence を最大値に合わせる。
|
||||||
|
|
||||||
|
ブログ・日記は `store-domain-entry` の設定 schema を再利用し、追加の `store-periodicals`
|
||||||
|
migration で記事索引・変更履歴・投稿受付記録・射影設定を作成する。
|
||||||
|
書き込みは権限確認前に共通 namespace lock を取得する。記事新規作成では Object・primary Path・
|
||||||
|
Revision・埋め込み参照・受付記録・記事 metadata・変更履歴・outbox を同じ transaction で確定する。
|
||||||
|
本文は canonical Document に保存し、Asset 名は当該 Domain の HEAD を不変 hash に解決して保持する。
|
||||||
|
記事の登録解除は索引だけを削除し、Page 自体は残す。再登録は変更履歴から version を継続する。
|
||||||
|
公開タイトルの問い合わせは許可済み navigation の UUID と Domain に限定し、入力件数も予算内に制限する。
|
||||||
|
射影は同じ Campus の有効な local Domain 同士に限り、多段射影・循環と無効な配信元を拒否する。
|
||||||
|
全件 import では投稿受付記録と記事変更履歴も正本として保全し、履歴の identity 採番を復元する。
|
||||||
|
|
||||||
|
RSS は `store-feeds` migration で購読元・記事 cache・ローカル既読状態・取り込み受付と
|
||||||
|
FreshRSS の明示的操作 receipt を保持する。書き込みは namespace lock 取得後に
|
||||||
|
native actor と拡張設定を検証する。読み取りは 3 秒、書き込みは 5 秒で制限する。
|
||||||
|
FreshRSS 分類は PostgreSQL の JSONB 関数で検索し、カテゴリなしの null/空配列を扱う。
|
||||||
|
壊れた拡張設定は当該 Domain を処理対象から外し、他の購読元の候補検索を中断させない。
|
||||||
|
送信結果が不明な操作は購読元の変更・削除後も履歴として保持し、自動再送しない。
|
||||||
|
期限切れ claim の回収は 1 transaction あたり 100 件・3 秒に制限する。
|
||||||
|
次の実装単位は scheduler の native schema と claim/lease/ログ保持、各イベント登録である。
|
||||||
|
Push 配信と scheduler のイベント登録・実行は未統合である。
|
||||||
|
外部カレンダーの内容は検証に用いない。
|
||||||
|
`EnsureTasksSchema` と `EnsureNotificationSchema` の native 通常起動は引き続き未対応として拒否する。
|
||||||
|
旧 free helper を使う未移植の呼び出し元は SQLite 用であり、native Store の receiver へ順次接続する。
|
||||||
|
DAV HTTP の discovery/REPORT/条件付き PUT/DELETE、ETag・ctag の再起動後整合性と
|
||||||
|
カレンダー共通 endpoint の実機統合も残る。task payload 永続化中に writer transaction を保持する
|
||||||
|
既存動作と GC pin は、Document の I/O 予算・参照固定の残件として扱う。
|
||||||
|
|
||||||
|
2026-11-15 の合成データによる検証では、SQLite とローカル PostgreSQL 17 を使った
|
||||||
|
全 Go テスト、移植済み Store の共通契約・PostgreSQL migration テストの race 検出、
|
||||||
|
`go vet ./...`、ローカルバイナリ生成が成功した。
|
||||||
|
公開・承認、ユーザー領域・電話番号の同意、Domain 同時作成・移動、管理者継承の取消、
|
||||||
|
Federation の token 失効・署名改ざん・replay・同時初回受信・checkpoint 故障時の rollback を含む。
|
||||||
|
通常保存の追加試験では別 Store からの同時 CAS と無条件 append、言語別履歴、
|
||||||
|
create/save/bind の origin 制約、別 Domain への移動後の拒否、現在の Asset HEAD を変更した後の
|
||||||
|
履歴復元、本文・埋め込み payload の欠損、Page/Revision の outbox 故障時の rollback を確認する。
|
||||||
|
Path/City/Asset の追加共通試験では、再帰移動・コピー・重複選択の削除、literal な `%`/`_`、
|
||||||
|
stale snapshot の拒否、保護 namespace の拒否、コピーと filename Revision の参照保持、
|
||||||
|
navigator の移動先重複解消、Spot 統合後の所属と URL 保持、同時 topology version 更新、
|
||||||
|
Asset の同時 CAS・履歴復元・欠損拒否・監査保存故障時の rollback を確認する。
|
||||||
|
City CRUD・一覧・アーカイブ import の追加試験では、stale plan、再帰削除中の監査故障、
|
||||||
|
archived 名の再利用、literal prefix、12 件以上の指定順序、canonical H1、metadata cursor の
|
||||||
|
重複防止、別 Store からの cache 失効、import 番号重複時の計画保持、Domain 分離、
|
||||||
|
Path rollback と状態更新の原子性、付け替え済み Path の保護、read-only 拒否を確認する。
|
||||||
|
タスクの追加試験では、プロジェクト別の同一 DAV UID、同一 collection 内の衝突拒否、
|
||||||
|
既定 collection の分離、親子階層、日付・優先度・添付の絞り込みと pagination、履歴、
|
||||||
|
完了時の通知予約削除、削除の再試行と復活拒否、DAV 資格情報の発行・失効を確認する。
|
||||||
|
PostgreSQL の別 Store からの同時保存は一方だけ成功し、outbox 故障では保存と削除が rollback する。
|
||||||
|
readonly Principal の書き込み拒否と、Membership 失効後の読み取り拒否も確認する。
|
||||||
|
生産性機能の共通試験では、個人設定と配置の独立した CAS、作業時間の訂正・取消・履歴の
|
||||||
|
pagination、Pomodoro の停止区間を除いた集計、完了通知の一度だけの登録、予定枠の状態変更、
|
||||||
|
期限通知の再送防止と活動 journal の重複排除を確認する。
|
||||||
|
PostgreSQL では別 Store の同時設定更新・作業開始・タイマー開始・完了処理も試験し、
|
||||||
|
監査失敗時に作業時間/Focus span が途中で更新されないこと、Inbox 故障後の再試行、
|
||||||
|
同時通知挿入の一意性、受信者 scope と失効後の拒否を確認する。
|
||||||
|
capture/メモの共通試験では日本語 Path と本文、HTML/マクロの無害化、受付の再送、
|
||||||
|
同一 Path の衝突拒否、削除後の明示的再作成と本文保持、stale project の拒否を確認する。
|
||||||
|
PostgreSQL では受付記録の故障による全関連 metadata の rollback、別 Store からの同時 capture、
|
||||||
|
canonical 本文の読み戻し、作成元 Domain・primary Path・cache generation を確認する。
|
||||||
|
メール管理の共通試験では日次 claim の重複拒否、重複送信了承・受付再送・履歴 pagination、
|
||||||
|
同意変更後の取消、保持期限後の予約・受付保持を確認する。PostgreSQL では複数 Store の
|
||||||
|
scheduled/manual claim と、送信結果保存失敗時の rollback、中断試行の自動再送防止を確認する。
|
||||||
|
カレンダーの共通試験では月またぎ移動、ETag 競合、DAV filename 保持、既定 calendar、
|
||||||
|
共同編集者の読み取り権限と失効、全 cache 消去後の再構築、削除を確認する。
|
||||||
|
PostgreSQL では別 Repository の同時編集、再構築・削除の DB 故障時の正本保持と再試行を検証する。
|
||||||
|
タスク予定枠の再送が移動済み予定を上書きしないこと、日次 projection が現在の時刻を返すこと、
|
||||||
|
外部 source は snapshot 読み込み前に拒否されることも合成 metadata で確認する。
|
||||||
|
連絡先の共通試験では日本語検索、未知の vCard property 保持、同一 UID import の再送、
|
||||||
|
削除の差分配信、履歴復元、metadata の byte 長、差分 pagination、資格情報失効を確認する。
|
||||||
|
PostgreSQL では同時 CAS と履歴保存故障時の連絡先・同期番号の rollback を確認する。
|
||||||
|
ブログ・日記の共通試験では日本語記事の作成・再送、変更された再送入力の拒否、
|
||||||
|
記事 metadata の CAS、登録解除後の Page 保持と再登録、Asset HEAD 更新後の本文参照固定、
|
||||||
|
欠損 Asset の拒否、公開タイトルの Domain 分離と件数上限、射影の循環・無効な配信元の拒否を確認する。
|
||||||
|
PostgreSQL では変更履歴の保存故障時に Path と受付記録が rollback すること、
|
||||||
|
別 Store からの同時投稿要求が一つの記事となること、Campus 無効化後の投稿拒否を確認する。
|
||||||
|
RSS の共通試験では日本語・literal 検索、日時 cursor、既読状態の CAS、
|
||||||
|
FreshRSS のカテゴリ/未分類/空フォルダ、購読 import と Wiki 取り込みの再送、
|
||||||
|
削除済み購読元の復活拒否、外部操作の確認・期限切れ・読み取り専用再確認を検証する。
|
||||||
|
購読元を変更・削除しても不明な外部操作を保持し、履歴の metadata 欠損を許容する。
|
||||||
|
PostgreSQL では複数 Store の同時 claim、cache 保存故障時の lease rollback、
|
||||||
|
100 件ずつの期限切れ回収、破損設定と Campus 無効化後の拒否を確認する。
|
||||||
|
ジョブの共通試験では claim・完了・再試行・キャンセル・一覧・ログ・集計と read-only 拒否を確認する。
|
||||||
|
PostgreSQL では同時定期登録の一意性、同時 claim の上限、二つ目の worker owner の拒否、
|
||||||
|
再起動後の結果不明ジョブの保留、古い完了 token の拒否、完了ログ故障時の状態保持を確認する。
|
||||||
|
outbox は型別・Domain 別の取得、consumer の独立性、同時 checkpoint の単調性、
|
||||||
|
rollback と read-only 拒否を両 backend で検証する。
|
||||||
|
HTTP 用 lookup と個人表示設定の共通試験では Domain 分離、無効 Principal、対象欠損時の拒否、
|
||||||
|
設定 CAS を確認する。scheduler/outbox/lookup の対象テストは race detector でも検証する。
|
||||||
|
これらは component テストであり、PostgreSQL を指定した通常アプリ起動や本番データ import の成功ではない。
|
||||||
|
|
||||||
|
検証は `GOPROXY=off GOSUMDB=off` とし、実 PostgreSQL の共通テストには
|
||||||
|
`PAGESWIKI_TEST_POSTGRES_DSN` で使い捨て DB を指定する。各テストは専用 schema を作成・削除するため、
|
||||||
|
本番 DB を指定してはならない。実際の外部カレンダー、OIDC/LDAP/SMTP、Gitea へのアクセスは不要。
|
||||||
|
|
||||||
|
2026-11-15 に Gitea の復旧連絡を受領した。移植中は引き続きローカルビルドで検証し、
|
||||||
|
全 repository・通常起動・インポートのリリースゲートを満たした後に、commit/push、
|
||||||
|
SemVer タグ、Gitea CI の image build とリリースへ進む。復旧だけを理由に未完の移植を配布しない。
|
||||||
|
ローカルビルドの成功は DB 切替の許可条件ではなく、上記ゲートと停止状態の全件インポート検証を
|
||||||
|
満たした後、移行前 backup を確保し、同じ成果物で隔離起動試験を経て本番を起動する。
|
||||||
|
|
||||||
|
未対応機能を暗黙に初期化したり、読めないテーブルを cache とみなして捨てたりしない。
|
||||||
|
外部 RDB 障害時に SQLite へ自動 fallback する設定は作らず、二つの DB が別々に
|
||||||
|
更新を受ける状態を防ぐ。最低 PostgreSQL 対応版と CI matrix の確定も切替条件とする。
|
||||||
|
|
||||||
|
#### 片方向インポートと切替の設計
|
||||||
|
|
||||||
|
本番切替は全ゲートが通った後、次の順で行う。全件移行ツールは
|
||||||
|
`pageswiki migrate-postgres` であり、core リハーサルをその代用にしない。
|
||||||
|
|
||||||
|
1. HTTP/CalDAV/CLI、scheduler、federation を含めた全 writer と GC を停止し、保守状態を確認する。
|
||||||
|
2. SQLite の整合した snapshot、Document、カレンダー正本、設定・鍵・instance identity を保全し、復元検証する。
|
||||||
|
3. 空の専用 PostgreSQL へ全件移行し、件数・内容指紋・参照・採番・payload を照合する。
|
||||||
|
4. 読み取り検証でログイン、権限、公開ナビゲーション、検索、タスク/CalDAV、管理・配信を確認する。
|
||||||
|
5. 反映する全プロセスを一斉に PostgreSQL 側へ向け、旧 SQLite は凍結したまま、書き込み再開時点を記録する。
|
||||||
|
|
||||||
|
書き込み再開前にインポートや検証が失敗した場合は移行を中止し、元の SQLite を維持する。
|
||||||
|
書き込み再開後は PostgreSQL を正本とし、障害時は PostgreSQL 側の復旧・修正を基本とする。
|
||||||
|
移行後の更新を SQLite に反映する機能は今回提供せず、接続先を旧 SQLite へ自動で戻さない。
|
||||||
|
この制約を運用手順にも明記し、逆移行の完成を本番切替の前提条件にはしない。
|
||||||
|
|
||||||
### S3:運用と移行
|
### S3:運用と移行
|
||||||
|
|
||||||
- [ ] 編集可能な設定例と薄い backup / release / deploy script。
|
- [ ] 編集可能な設定例と薄い backup / release / deploy script。
|
||||||
@@ -404,6 +1217,10 @@ setup 完了後は token 再利用不可。機密欄の再表示・ログ出力
|
|||||||
## 12. 根拠資料
|
## 12. 根拠資料
|
||||||
|
|
||||||
- [SQLite WAL:network filesystem の制約](https://sqlite.org/wal.html)
|
- [SQLite WAL:network filesystem の制約](https://sqlite.org/wal.html)
|
||||||
|
- [PostgreSQL の transaction-level advisory lock](https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS)
|
||||||
|
- [PostgreSQL の identity 変更](https://www.postgresql.org/docs/current/sql-altertable.html)
|
||||||
|
- [PostgreSQL の RESTART と transaction](https://www.postgresql.org/docs/current/sql-altersequence.html)
|
||||||
|
- [pgx の database/sql 接続](https://pkg.go.dev/github.com/jackc/pgx/v5/stdlib)
|
||||||
- [S3 の conditional writes](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html)
|
- [S3 の conditional writes](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html)
|
||||||
- [Redis persistence](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/)
|
- [Redis persistence](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/)
|
||||||
- [PostgreSQL backup / restore](https://www.postgresql.org/docs/current/backup.html)
|
- [PostgreSQL backup / restore](https://www.postgresql.org/docs/current/backup.html)
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
# Gecko連携の再配布条件
|
# Gecko連携の再配布条件
|
||||||
|
|
||||||
PagesWiki v0.13.0は、自作の連携コードと中継サービスのソースを配布し、Geckoエンジンは同梱しません。
|
PagesWiki v0.13.0ではGeckoエンジンの配布を保留しました。
|
||||||
実験機能`viewer.gecko`は既定無効のままです。既存3イメージのリリースにエンジンを追加せず、
|
現在は固定版のエンジン、対応ソース、第三者NOTICE、日本語フォントを含む配布bundleを生成できます。
|
||||||
専用relayも上流エンジンを含まないDockerfileとして提供します。
|
実験機能`viewer.gecko`は既定無効のままです。relayイメージとbundleは別物で、
|
||||||
|
起動時にbundle全体を検証してから資産を配信します。
|
||||||
本書は今回追加した部品の配布判断と残件を整理するもので、プロジェクト全体の法務監査ではありません。
|
本書は今回追加した部品の配布判断と残件を整理するもので、プロジェクト全体の法務監査ではありません。
|
||||||
|
|
||||||
## 部品と適用条件
|
## 部品と適用条件
|
||||||
@@ -17,6 +18,8 @@ PagesWiki v0.13.0は、自作の連携コードと中継サービスのソース
|
|||||||
| Emscripten runtime / WasmFS | 6.0.1と上流のpatch | Emscripten本体はMITまたはUIUC/NCSA。libc等のruntime依存には別noticeがあるため、ツールチェーンの最上位LICENSEだけでは棚卸し完了としない |
|
| Emscripten runtime / WasmFS | 6.0.1と上流のpatch | Emscripten本体はMITまたはUIUC/NCSA。libc等のruntime依存には別noticeがあるため、ツールチェーンの最上位LICENSEだけでは棚卸し完了としない |
|
||||||
| zstddec | 0.2.0 | npm metadataは`MIT AND BSD-3-Clause`。JS wrapperと組み込まれたdecoderの両noticeを保持 |
|
| zstddec | 0.2.0 | npm metadataは`MIT AND BSD-3-Clause`。JS wrapperと組み込まれたdecoderの両noticeを保持 |
|
||||||
| Liberation fonts | 上記Firefox commit内のPDF.js standard_fonts | SIL OFL 1.1。著作権表示・OFL本文・Reserved Font Namesを保持 |
|
| Liberation fonts | 上記Firefox commit内のPDF.js standard_fonts | SIL OFL 1.1。著作権表示・OFL本文・Reserved Font Namesを保持 |
|
||||||
|
| Rust standard libraryと依存crate | 1.95.0と`library/Cargo.lock` | RustのMIT/Apache-2.0と各crateの個別条件。lockに記載された全registry crateのsource・noticeを保持 |
|
||||||
|
| Noto Sans CJK JP | Sans2.004、`523d033d6cb47f4a80c58a35753646f5c3608a78` | SIL OFL 1.1。未改変OTF、Adobeの埋込著作権表示、OFL本文を保持 |
|
||||||
|
|
||||||
relayのruntimeイメージは`FROM scratch`とし、Goバイナリとlicenseだけを含めます。
|
relayのruntimeイメージは`FROM scratch`とし、Goバイナリとlicenseだけを含めます。
|
||||||
Alpine/BusyBoxを新たに再配布する構成にはしません。`go list -deps`でrelayにリンクされる外部Go moduleは
|
Alpine/BusyBoxを新たに再配布する構成にはしません。`go list -deps`でrelayにリンクされる外部Go moduleは
|
||||||
@@ -62,9 +65,28 @@ MPLはファイル単位の義務であり、別実装のWiki全体をMPLへ変
|
|||||||
4. 提供するsourceとnoticeの可用性・保全、配布物とのhash対応を検査する。
|
4. 提供するsourceとnoticeの可用性・保全、配布物とのhash対応を検査する。
|
||||||
5. Mozillaの商標はコードlicenseとは別に扱い、Firefoxの公式配布であるとの表現やロゴの流用をしない。
|
5. Mozillaの商標はコードlicenseとは別に扱い、Firefoxの公式配布であるとの表現やロゴの流用をしない。
|
||||||
|
|
||||||
現時点では2・3・4の配布用bundleが未完成です。今回のrelease artifactにエンジンは載せず、
|
### 配布bundle
|
||||||
本番では中継用鍵・資産mount・`viewer.gecko`の有効化を追加しません。
|
|
||||||
エンジン非同梱の連携コードと、通常のRSSフォルダショートカットはリリース対象です。
|
`tools/gecko/sources.lock.json`に取得元とSHA-256を固定し、`tools/gecko/bundle.py`で組み立てます。
|
||||||
|
生成物は98ファイル、合計1,196,102,561 bytes(manifest自身を除く)です。
|
||||||
|
manifestのSHA-256は`84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381`。
|
||||||
|
同じ値をrelay側で固定し、列挙された全ファイルのサイズ・hash・通常ファイルであることを起動時に検査します。
|
||||||
|
不足、改変、symlink、別版混入を許可しません。
|
||||||
|
|
||||||
|
元のsource archiveを変更せず保存し、license/copying/copyright/notice/authorsファイルを別の閲覧用テキストにも集約します。
|
||||||
|
Mozillaの条件付きnoticeは**全分岐を含む保守的な上位集合**としてテキスト化し、元のHTMLはsource archiveに保持します。
|
||||||
|
Rustの追加依存はCargo.lockのチェックサムで検証します。crateから欠けていたFortanixのMPLヘッダと
|
||||||
|
vex-sdkのMIT本文も、元ソース・固定commitから補完しています。
|
||||||
|
Notoの未改変フォントには`© 2014-2021 Adobe (http://www.adobe.com/).`が埋め込まれ、READMEにも保持します。
|
||||||
|
|
||||||
|
閲覧画面のⓘは`/_/api/v1/extension/organizer.feeds/browser/distribution/v0.0.1/index.html`を開きます。
|
||||||
|
同じ入口からNOTICE、manifest、ソース一式を取得できます。認証は必要ですが、RSS・Geckoを無効化した後も、
|
||||||
|
認証済みの受領者はソースを取得できます。readonly利用者も取得可能です。
|
||||||
|
relay自体を撤去する場合は、先にbundleと取得先を保全・移設してください。無効化はソース提供の撤回を意味しません。
|
||||||
|
|
||||||
|
CIは中継バイナリの4番目のイメージを配布しますが、約1.2GBのbundleを通常イメージへ重複同梱しません。
|
||||||
|
検証済みbundleをread-onlyでmountする運用です。再配布条件の充足はこの固定版・未改変バイナリ・
|
||||||
|
保持したsource/noticeを前提とします。依存更新時はlockとnoticeを再確認し、公開済みbundleを上書きしません。
|
||||||
|
|
||||||
## 一次資料
|
## 一次資料
|
||||||
|
|
||||||
@@ -75,3 +97,5 @@ MPLはファイル単位の義務であり、別実装のWiki全体をMPLへ変
|
|||||||
- [zstddec 0.2.0 metadata](https://registry.npmjs.org/zstddec/0.2.0)
|
- [zstddec 0.2.0 metadata](https://registry.npmjs.org/zstddec/0.2.0)
|
||||||
- [Go LICENSE](https://go.dev/LICENSE)
|
- [Go LICENSE](https://go.dev/LICENSE)
|
||||||
- [golang.org/x/net v0.35.0 LICENSE](https://go.googlesource.com/net/+/refs/tags/v0.35.0/LICENSE)
|
- [golang.org/x/net v0.35.0 LICENSE](https://go.googlesource.com/net/+/refs/tags/v0.35.0/LICENSE)
|
||||||
|
- [Noto CJK固定版OFL](https://github.com/notofonts/noto-cjk/blob/523d033d6cb47f4a80c58a35753646f5c3608a78/LICENSE)
|
||||||
|
- [vex-sdk固定版MIT](https://github.com/vexide/vex-sdk/blob/6c0b83d35b6fc31a7607efe456e387df45476314/LICENSE.md)
|
||||||
@@ -28,7 +28,8 @@ WebSocketではOriginも検査し、grantは一回限りです。既存接続の
|
|||||||
bac28056a00ef6e5fb4345117e73d3629e75aca00dac71389fabbce39c018a73
|
bac28056a00ef6e5fb4345117e73d3629e75aca00dac71389fabbce39c018a73
|
||||||
```
|
```
|
||||||
|
|
||||||
展開後の`gecko.js/dist/`をread-onlyで`/gecko`へmountします。起動時に次の両ファイルのhashを確認し、
|
エンジン単体の`dist/`ではなく、後述するsource/notice付きbundleをread-onlyで`/gecko`へmountします。
|
||||||
|
起動時に次の両ファイルに加え、manifestに列挙された全ソース・NOTICE・フォントをhash検査し、
|
||||||
欠損・改変・異なる版の混在があれば中継は起動しません。
|
欠損・改変・異なる版の混在があれば中継は起動しません。
|
||||||
|
|
||||||
| ファイル | SHA-256 |
|
| ファイル | SHA-256 |
|
||||||
@@ -37,13 +38,27 @@ bac28056a00ef6e5fb4345117e73d3629e75aca00dac71389fabbce39c018a73
|
|||||||
| gecko.wasm.zst | ebd6c75179152624d9644865e11792ed25cadc714d9e0985f412baf9c637a086 |
|
| gecko.wasm.zst | ebd6c75179152624d9644865e11792ed25cadc714d9e0985f412baf9c637a086 |
|
||||||
|
|
||||||
資産URLにも`assets/v0.0.1/`を含め、版をまたいだJS/WASMのcache混在を避けます。
|
資産URLにも`assets/v0.0.1/`を含め、版をまたいだJS/WASMのcache混在を避けます。
|
||||||
初回にはJSと圧縮WASMの合計38,175,359 bytes(約36.4MiB)の転送とWASMの展開・compileが必要です。
|
初回にはJS・圧縮WASM・日本語フォントの合計54,643,095 bytes(約52.1MiB)の転送とWASMの展開・compileが必要です。
|
||||||
|
約1.2GBの対応ソースは閲覧の起動時には取得せず、ⓘから明示的にダウンロードするときだけ配信します。
|
||||||
本体のDocker buildにFirefoxのソースビルドを加えません。
|
本体のDocker buildにFirefoxのソースビルドを加えません。
|
||||||
|
|
||||||
`Dockerfile.gecko-relay`は自前の中継バイナリだけを含みます。エンジンは同梱・再配布しません。
|
`Dockerfile.gecko-relay`は自前の中継バイナリだけを含みます。エンジンは同梱・再配布しません。
|
||||||
**エンジンをイメージへ同梱する場合だけでなく、mountした資産を利用者へ配信する前にもnoticeと対応sourceの提供が必要です。**
|
**エンジンをイメージへ同梱する場合だけでなく、mountした資産を利用者へ配信する前にもnoticeと対応sourceの提供が必要です。**
|
||||||
固定版のMPL宣言、第三者依存物、今回の配布範囲は[再配布条件](gecko-redistribution.md)を参照してください。
|
固定版のMPL宣言、第三者依存物、今回の配布範囲は[再配布条件](gecko-redistribution.md)を参照してください。
|
||||||
v0.13.0の本番配備ではエンジンを配信せず、機能の有効化も行いません。
|
v0.13.0の本番配備ではエンジンを配信していません。新しいrelayは完成したbundleを必須とします。
|
||||||
|
|
||||||
|
### bundle生成
|
||||||
|
|
||||||
|
Python 3.11以降を使い、十分な空き容量のあるディスク上で実行します。ソースarchiveは展開せず保持します。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python tools/gecko/bundle.py --cache /srv/gecko-cache --output /srv/gecko/v0.0.1-bundle1
|
||||||
|
# 同一入力からの再生成。出力先はまだ存在しない新しいディレクトリを指定する。
|
||||||
|
python tools/gecko/bundle.py --cache /srv/gecko-cache --output /srv/gecko/rebuilt --offline
|
||||||
|
```
|
||||||
|
|
||||||
|
出力manifestのSHA-256が`84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381`と一致することを確認します。
|
||||||
|
稼働中のmount先を上書きせず、source/noticeの提供を含めて不変の単位で保全します。
|
||||||
|
|
||||||
## 配置
|
## 配置
|
||||||
|
|
||||||
@@ -55,7 +70,8 @@ v0.13.0の本番配備ではエンジンを配信せず、機能の有効化も
|
|||||||
| 変数 | 内容 |
|
| 変数 | 内容 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| PAGESWIKI_GECKO_KEY_PATH | 32文字以上の十分ランダムな共有鍵のファイル絶対Path。appとrelayへ同じread-only mount |
|
| PAGESWIKI_GECKO_KEY_PATH | 32文字以上の十分ランダムな共有鍵のファイル絶対Path。appとrelayへ同じread-only mount |
|
||||||
| PAGESWIKI_GECKO_ASSETS_DIR | hash確認した`gecko.js/dist`の絶対Path |
|
| PAGESWIKI_GECKO_ASSETS_DIR | 全ファイルを検証したbundleの絶対Path。engineだけのdistは禁止 |
|
||||||
|
| PAGESWIKI_GECKO_IMAGE | Giteaで配布した`pageswiki-gecko-relay:sha-...`またはrelease tag。省略時は開発用image |
|
||||||
| PAGESWIKI_GECKO_FRONT_SUBNET | 内部接続網。既定`172.24.0.0/27`。既存LANとの重複を避ける |
|
| PAGESWIKI_GECKO_FRONT_SUBNET | 内部接続網。既定`172.24.0.0/27`。既存LANとの重複を避ける |
|
||||||
| PAGESWIKI_GECKO_EGRESS_SUBNET | 中継の外向き網。既定`172.24.0.32/27` |
|
| PAGESWIKI_GECKO_EGRESS_SUBNET | 中継の外向き網。既定`172.24.0.32/27` |
|
||||||
|
|
||||||
@@ -100,7 +116,8 @@ UDP、80/443以外のTCP、単一ラベルのホスト名は拒否します。
|
|||||||
| WebSocket受信idle | 90秒 |
|
| WebSocket受信idle | 90秒 |
|
||||||
| 宛先接続 | 名前解決込み8秒、個別dial 2秒 |
|
| 宛先接続 | 名前解決込み8秒、個別dial 2秒 |
|
||||||
| relayコンテナ | 256MiB、0.5 CPU、64 PIDs、read-only、capabilitiesなし |
|
| relayコンテナ | 256MiB、0.5 CPU、64 PIDs、read-only、capabilitiesなし |
|
||||||
| 閲覧プロファイル | volatileな32MiB・2,048 entries、端末のOPFSへ永続化しない |
|
| 閲覧プロファイル | 日本語フォントを含むvolatileな32MiB・2,048 entries、端末のOPFSへ永続化しない |
|
||||||
|
| source/noticeダウンロード | 全体2接続まで。ETag・Range対応。閲覧streamの枠とは分離 |
|
||||||
|
|
||||||
relayの稼働状態・接続数・送受信bytes・拒否数は、コンテナ内の次の操作でJSON取得できます。
|
relayの稼働状態・接続数・送受信bytes・拒否数は、コンテナ内の次の操作でJSON取得できます。
|
||||||
鍵はファイルから読み、標準出力には含めません。counterは再起動でリセットします。
|
鍵はファイルから読み、標準出力には含めません。counterは再起動でリセットします。
|
||||||
@@ -134,7 +151,10 @@ extension viewer.gecko off
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
go test -race ./internal/geckorelay ./internal/server -run 'TestGrant|TestDestinations|TestRelay|TestAssets|TestFeedGeckoAuthorization|TestFeedGeckoWebsocket'
|
go test -race ./internal/geckorelay ./internal/server -run 'TestGrant|TestDestinations|TestRelay|TestAssets|TestFeedGeckoAuthorization|TestFeedGeckoWebsocket'
|
||||||
PAGESWIKI_BROWSER_TEST=1 PAGESWIKI_GECKO_TEST_ASSETS=/verified/gecko.js/dist go test ./internal/server -run '^TestFeedGeckoChromium$' -count=1
|
PAGESWIKI_BROWSER_TEST=1 PAGESWIKI_GECKO_TEST_ASSETS=/verified/bundle go test ./internal/server -run '^TestFeedGeckoChromium$' -count=1
|
||||||
|
PAGESWIKI_GECKO_TEST_BUNDLE=/verified/bundle go test ./internal/geckorelay -run TestDistribution
|
||||||
|
# 公開テストサイトへの実通信。実RSS・外部カレンダー・メールは使用しない。
|
||||||
|
PAGESWIKI_BROWSER_TEST=1 PAGESWIKI_GECKO_TEST_ASSETS=/verified/bundle PAGESWIKI_GECKO_PUBLIC_HTTPS_TEST=1 go test ./internal/server -run '^TestFeedGeckoChromium$' -count=1
|
||||||
node internal/server/testdata/feed-gecko-profile.mjs
|
node internal/server/testdata/feed-gecko-profile.mjs
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -144,6 +164,12 @@ node internal/server/testdata/feed-gecko-profile.mjs
|
|||||||
標準のhistory.back()が失敗するため、フォーム内容やスクロール位置を復元する履歴ではありません。
|
標準のhistory.back()が失敗するため、フォーム内容やスクロール位置を復元する履歴ではありません。
|
||||||
画面のcanvasは最大1920×1080、experimental WASM JITとGPUは無効です。
|
画面のcanvasは最大1920×1080、experimental WASM JITとGPUは無効です。
|
||||||
|
|
||||||
本番の標準機能に昇格する前に、HTTPSサイトと証明書エラーの表示、Safari/iPhone SE、IME、コピー、
|
HTTPSの実描画と期限切れ証明書の拒否を確認しました。上流最小GREはエラーページの部品が不足するため、
|
||||||
find、実サイト互換性、複数タブ・起動失敗時のUX、低メモリ端末の測定、コンテナ外向きfirewallを検証します。
|
`about:neterror`/`about:certerror`を検知してcanvasを隠し、PagesWiki側で説明します。証明書の無視・例外追加は提供しません。
|
||||||
|
Noto CJKをメモリプロファイルのfontsに置き、エンジンを改変せず日本語描画も確認しています。
|
||||||
|
|
||||||
|
検索アイコンまたはCtrl/Cmd+Fからページ内検索できます。検索語は256文字まで、前後検索と一致なしの表示に対応し、合成記事で日本語検索を確認しています。起動失敗または120秒の起動上限到達時はiframeを破棄し、元記事を別タブで開く導線を残します。上流のdestroy呼出しだけではWASM資源の解放にならないため、親側のiframe破棄まで行います。`TestFeedGeckoStartupFailureChromium` はフォント取得失敗時の破棄と代替導線を検証します。
|
||||||
|
|
||||||
|
本番の標準機能に昇格する前に、Safari/iPhone SE、IME、コピー、実サイト互換性、
|
||||||
|
複数タブ・低メモリ端末の測定、コンテナ外向きfirewallを検証します。
|
||||||
外部ページのiframe拒否とは別の仕組みですが、すべてのサイトでの動作や軽さを保証するものではありません。
|
外部ページのiframe拒否とは別の仕組みですが、すべてのサイトでの動作や軽さを保証するものではありません。
|
||||||
@@ -11,6 +11,9 @@ runner の環境構築や Gitea の事前疎通診断は行わず、本番へ自
|
|||||||
| `pageswiki-app`(app / app2 共通) | `Dockerfile` |
|
| `pageswiki-app`(app / app2 共通) | `Dockerfile` |
|
||||||
| `pageswiki-adaptor-gateway` | `Dockerfile.adapter-gateway` |
|
| `pageswiki-adaptor-gateway` | `Dockerfile.adapter-gateway` |
|
||||||
| `pageswiki-excalidraw-viewer` | `Dockerfile.excalidraw-viewer` |
|
| `pageswiki-excalidraw-viewer` | `Dockerfile.excalidraw-viewer` |
|
||||||
|
| `pageswiki-gecko-relay`(任意) | `Dockerfile.gecko-relay` |
|
||||||
|
|
||||||
|
v0.15.0以降はGecko relayを含む4イメージをビルド・昇格します。以下の「3イメージ」は通常配備するapp・gateway・Excalidrawの組を指します。Gecko relayは別overlayで明示的に配備するもので、通常の本番更新では起動しません。
|
||||||
|
|
||||||
Kroki、Mermaid、code-server は upstream の配布イメージを使用する。
|
Kroki、Mermaid、code-server は upstream の配布イメージを使用する。
|
||||||
`main` / `mk_district` への push、手動実行でビルド・公開する。
|
`main` / `mk_district` への push、手動実行でビルド・公開する。
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# メールWikiのPath依存404の調査
|
||||||
|
|
||||||
|
## 状態と回避策
|
||||||
|
|
||||||
|
2026年11月6日、別インスタンスでNeoMuttから作成したWikiが一覧には見える一方、`/tasks` とその配下への直接アクセスで `{"detail":"Not Found"}` になる報告があった。同じオブジェクトに `/prj/awesome` 側のリンクを追加すると表示できた。原因は未確定で、修正済みとは扱わない。
|
||||||
|
|
||||||
|
回避策は表示できるWiki親prefixを既定値にし、既存オブジェクトには別Pathのリンクを使うこと。メールの再取り込み、オブジェクトの削除、既存Pathの一括移動は不要。Pathごとに権限が異なりうるため、新しいリンク先の公開範囲も確認する。
|
||||||
|
|
||||||
|
## アプリ内で確認した境界
|
||||||
|
|
||||||
|
タスク画面は `/v/plan/tasks`、APIは `/_/api/v1/extension/organizer.tasks/`。`/tasks` は予約ルートではなく、通常のWiki Pathとして解決する。末尾スラッシュは301で取り除く。
|
||||||
|
|
||||||
|
NeoMuttの `pipe_decode=no`・`pipe_split=yes` 相当の標準入力を使い、CLIプロセスから一時DBのフルHTTPハンドラへ取り込む試験を追加した。42パターンは、親prefix7種類、UTF-8/ISO-2022-JPの件名、ML連番/Message-ID/原文hashの組合せ。公開CLI v0.4.0でも一覧のdata-path、直接表示、末尾スラッシュ、言語指定を確認し、代表3パターンをChromiumで表示した。実メール・実アカウント設定は使用しない。
|
||||||
|
|
||||||
|
Python・Chromiumに依存しないGoテストでは、実際のAPIへ既定prefix `/tasks` を設定して取り込み、同一オブジェクトの `/tasks/...` と `/prj/awesome` の両方がHTMLの200を返すことを検証する。未認証閲覧のログイン誘導、一覧表示、旧CLI形式も対象。CIでPythonがない場合もこのテストは実行される。
|
||||||
|
|
||||||
|
親に文書がない場合は、仮想フォルダページ無効ならHTMLの404、有効ならchildren一覧の200となる。これは作成済み子ページまでJSONの404になる報告とは区別する。設定箇所は `/-/sys/config?panel=home` の「仮想フォルダページ」。設定は対象ドメイン単位で、調査のために自動変更しない。
|
||||||
|
|
||||||
|
## 機密情報を共有しない切り分け
|
||||||
|
|
||||||
|
以下は問題のインスタンス内で行う。実URL・メール本文・Cookie・Bearer token・ログ全文を外部へ共有しない。
|
||||||
|
|
||||||
|
1. 問題のPathへのGET時刻を控え、PagesWikiプロセスのアクセスログに同じ要求が到達するか確認する。到達しない場合はプロキシ、ブラウザ、キャッシュなどアプリより手前を調べる。ログ出力先の取り違えにも注意する。
|
||||||
|
2. 公開HTTPSとPagesWikiの直接待受で応答を比較する。Domainの振り分けが変わらないよう、同じHostとPathを使う。まず資格情報なし・リダイレクトを追わないGETのstatusとContent-Typeを比較すれば、メール本文を取得せずに判断できる。認証後の比較が必要ならローカル環境内の安全な手順を使い、コマンド履歴に資格情報を残さない。
|
||||||
|
3. 直接待受は正常でプロキシ経由だけ失敗する場合、`/tasks` に一致するlocation、正規表現location、rewrite、別upstream、Custom Locationsを確認する。実際の設定で確認できるまではプロキシが原因と断定しない。
|
||||||
|
4. PagesWikiへの直接要求も失敗する場合は、稼働イメージrevision、HostによるDomain選択、Path別ACL、既存リンクの対象UUIDをローカルで確認する。同一オブジェクトの別名が読めても、元Pathの権限が同じとは限らない。
|
||||||
|
|
||||||
|
X-Request-IDやServerヘッダーだけで応答元を断定しない。プロキシによる付加・上書きがありうる。原因が判明するまで、推測による `/tasks` 専用ルート追加や権限の緩和はしない。
|
||||||
|
|
||||||
|
## 回帰テストと残件
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go test ./internal/server -run 'TestTaskWikiPrefixRouting|TestNeoMuttMailViewerFlow' -count=1
|
||||||
|
# Chromiumがある開発環境のみ
|
||||||
|
PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1
|
||||||
|
# 配布ELFでも同じ一時プロファイルを用いて確認する場合
|
||||||
|
PAGES_CLI_TEST_BINARY=/absolute/path/to/pages PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1
|
||||||
|
```
|
||||||
|
|
||||||
|
- [x] `/tasks` 配下のメール作成から通常ビューアまでの合成HTTP試験。
|
||||||
|
- [x] 同一オブジェクトの別名、親の仮想フォルダ設定、認証境界のGo回帰テスト。
|
||||||
|
- [ ] 問題インスタンスで、直接待受とプロキシ経由の差分を確定する。
|
||||||
|
- [ ] 特定された原因に修正を適用し、元の `/tasks` でも表示できることを確認する。
|
||||||
|
|
||||||
|
テストと調査記録の追加は障害修正リリースではない。既存の回避策とデータを維持する。
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# PostgreSQL への停止移行
|
||||||
|
|
||||||
|
SQLite から PostgreSQL への片方向移行を、単一インスタンス・ローカルの正本ファイル配置で行う。
|
||||||
|
全 writer を停止し、空の専用 PostgreSQL database/schema へ転送する。既存 DB への merge、
|
||||||
|
オンライン差分同期、PostgreSQL から SQLite への逆移行は提供しない。
|
||||||
|
|
||||||
|
## 対応範囲と制限
|
||||||
|
|
||||||
|
検証対象は PostgreSQL 17。通常起動の既定値は引き続き SQLite である。
|
||||||
|
PostgreSQL 起動は verified TLS、全件 import の完了記録、既存の鍵と同じ絶対 Document root を必須とする。
|
||||||
|
DB 接続障害や検査失敗で SQLite に自動 fallback しない。
|
||||||
|
|
||||||
|
- native 検索は権限付きの Path・ファイル名・City メタデータ検索。本文全文検索は後続対応。
|
||||||
|
- hosted editor、Web Push 配信、zombie GC、ログの自動保持期限処理は native の停止ゲート対象。
|
||||||
|
設定・受付記録・既存データは保全する。内蔵エディタと Inbox を使用し、ログ・ファイル容量を監視する。
|
||||||
|
- DR/HA 構成への移行は拒否する。`pageswiki dr` と旧 `schema` コマンドは PostgreSQL 設定時に拒否する。
|
||||||
|
- DB 直結の `data/pageswiki-cli` は SQLite 専用。PostgreSQL では HTTP の `pages-cli` を使用する。
|
||||||
|
すべてのプロセスに backend 設定を統一し、旧 SQLite 用 CLI を起動しない。
|
||||||
|
- 外部カレンダーの実データを使った検査・再取得は行わない。検証用の予定・連絡先・タスクは合成データを使う。
|
||||||
|
|
||||||
|
## 移行前の準備
|
||||||
|
|
||||||
|
1. HTTP、CalDAV/CardDAV、CLI、scheduler、federation、外部の直接 DB writer を停止する。
|
||||||
|
コマンドは data directory の排他ロックを取るが、旧バイナリや直接 SQLite client の停止を代替しない。
|
||||||
|
2. 停止状態の data directory 全体を別の場所に保全する。SQLite と WAL、`documents`、カレンダー・タスク等の
|
||||||
|
正本ファイル、設定、`auth.key`、instance identity を同じ時点で保全する。
|
||||||
|
`PAGESWIKI_AUTH_KEY` を使用していた場合はその secret も別途保全し、移行時・起動時に同じ値を渡す。
|
||||||
|
3. 専用 PostgreSQL database/schema と、それを所有する移行ユーザーを用意する。
|
||||||
|
schema/table/trigger/identity の作成・変更権限が必要。共有アプリ DB を移行先にしない。
|
||||||
|
4. PostgreSQL の CA とホスト名を検証できる DSN を secret として用意する。
|
||||||
|
`PAGESWIKI_POSTGRES_DSN` に `sslmode=verify-full` と必要な `sslrootcert` を設定する。
|
||||||
|
DSN はコマンドラインやログに出さない。移行先の管理者による同時 schema 変更も停止する。
|
||||||
|
|
||||||
|
## コマンド
|
||||||
|
|
||||||
|
以下は、稼働時にも `/data` を使う場合の例。移行と起動で data directory の絶対パスを一致させる。
|
||||||
|
Docker では同じ `/data` マウントを使用する。別のホスト側絶対パスで import してから
|
||||||
|
コンテナ内 `/data` に切り替えると、root 検査により起動を拒否する。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# schema の読取り検査。移行先への接続・データコピーは行わない。
|
||||||
|
./pageswiki migrate-postgres --data-dir /data
|
||||||
|
|
||||||
|
# DSN は保護された環境設定から注入済みとする。
|
||||||
|
./pageswiki migrate-postgres --data-dir /data --apply --timeout 30m
|
||||||
|
|
||||||
|
# import 成功・保全確認後、同じ正本 root と鍵で起動する。
|
||||||
|
PAGESWIKI_DB_BACKEND=postgresql PAGESWIKI_DATA_DIR=/data ./pageswiki
|
||||||
|
```
|
||||||
|
|
||||||
|
`--apply` がない場合は schema preflight のみで、payload の検証成功を意味しない。
|
||||||
|
`--allow-insecure` は隔離試験専用の移行オプションであり、通常起動の TLS 検証は緩和しない。
|
||||||
|
未知のテーブル・列・trigger/view がある場合は処理を止め、保全分類と schema を修正して再試行する。
|
||||||
|
不明なデータを削除して検査を通さない。
|
||||||
|
|
||||||
|
## 転送と照合
|
||||||
|
|
||||||
|
保全対象は `internal/store/application_import_catalog.go` に列挙する。
|
||||||
|
SQLite 専用 FTS 索引・派生 latest revision index・SQLite migration ledger は除外するが、
|
||||||
|
設定、鍵への参照、認証、ACL、タスク、連絡先、同期番号、受付履歴、ジョブ・ログ等は保持する。
|
||||||
|
正本ファイルは同じ場所に残す。ファイル自体を別の volume へコピーするコマンドではない。
|
||||||
|
|
||||||
|
転送は単一 transaction。転送前に移行先の空状態を検査し、型を区別した各行の内容指紋・件数、
|
||||||
|
参照される Document の SHA-256、namespace の参照整合性を commit 前に検査する。
|
||||||
|
タスク DAV の内部索引だけは backend 形式の違いを明示的に変換する。変換後の内容指紋を照合し、
|
||||||
|
クライアント用 href・正本 JSON は保持する。削除履歴と削除済み最大採番も保全する。
|
||||||
|
|
||||||
|
JSON report は対象テーブルの件数と指紋、除外一覧、変換内容、Document 数、採番情報を返す。
|
||||||
|
本文や資格情報は含まない。成功時の report をバックアップと一緒に保管する。
|
||||||
|
失敗時はデータ転送を rollback する。準備済み schema は残り得るが、既定行だけの状態なら再試行できる。
|
||||||
|
完了済み import や既存データへの上書きは拒否する。
|
||||||
|
|
||||||
|
## 起動確認と復旧
|
||||||
|
|
||||||
|
書き込み再開前に、同じバイナリと設定で起動し、ログイン・既存 session・権限・本文・内蔵編集・
|
||||||
|
タスクのプロジェクト所属・DAV discovery/条件付き更新・連絡先・管理画面を確認する。
|
||||||
|
外部送信や取得を伴う worker の再開対象は事前に点検する。
|
||||||
|
この実装は import 済み DB を開くためのもので、空の PostgreSQL から既定 Campus を新規生成しない。
|
||||||
|
|
||||||
|
移行前 SQLite は凍結したまま保管する。書き込み再開後の新しい更新は PostgreSQL 側にしか存在しない。
|
||||||
|
旧 SQLite へ接続を戻すことはデータを引き継ぐ切り戻しではない。
|
||||||
|
|
||||||
|
PostgreSQL 運用のバックアップは、writer を停止した同じ時点の `pg_dump -Fc` と data directory 全体、
|
||||||
|
鍵・secret を組にする。復元先は空の専用 database/schema とし、`pg_restore --exit-on-error` で復元する。
|
||||||
|
ファイルを元と同じ絶対 mount path に復元し、接続先 DSN のみ変更する。
|
||||||
|
import 完了記録も dump に含める。DB 単独や正本ファイル単独のバックアップでは復元条件を満たさない。
|
||||||
|
復元後は停止状態で本文・参照・認証・DAV 同期の検証を実施してから writer を再開する。
|
||||||
|
|
||||||
|
## 検証とリリース前チェック
|
||||||
|
|
||||||
|
- 合成データで全件移行、途中失敗の rollback、再試行、上書き拒否、schema drift 拒否を検証する。
|
||||||
|
- 日本語本文・タグ、バイナリ画像、認証 session、プロジェクト別 DAV、削除 tombstone、連絡先 sync-token を照合する。
|
||||||
|
- 隔離した PostgreSQL 17 に対し schema 単位の dump/restore と、同じ正本 root の読み戻しを検証する。
|
||||||
|
- `go test ./...`、対象 race test、`go vet ./...`、通常バイナリ build を通す。
|
||||||
|
- 実インスタンスの停止バックアップと import 結果は、合成データ試験とは別に確認する。
|
||||||
|
- image build workflow は `tools/ci/test-postgres.sh` で PostgreSQL 17 の全 Go テストを実行してから publish する。
|
||||||
|
DB container は外部ネットワーク・公開 port を持たず、テスト container がその network namespace を共有する。
|
||||||
|
DSN 未設定で実行したローカルテストの skip を移植検証の成功として扱わない。
|
||||||
|
|
||||||
|
任意のテスト DSN に本番を指定しない。`PAGESWIKI_TEST_POSTGRES_DSN` は使い捨て DB に限定する。
|
||||||
|
CLI と verified TLS の試験は `PAGESWIKI_TEST_POSTGRES_TLS_DSN` を指定する。
|
||||||
|
`PAGESWIKI_TEST_POSTGRES_CONTAINER` を追加指定すると、同じ隔離 DB を持つ Docker container 内の
|
||||||
|
`pg_dump`/`pg_restore` でテスト専用 schema の復元試験を実行する。
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# PagesWiki v0.14.1とpages-cli v0.4.2
|
||||||
|
|
||||||
|
削除済みタスクの受付記録が残り、変更した下書きの再送で412になっていた問題を修正します。
|
||||||
|
削除済みなら410、受付記録に対応するタスクと削除記録が両方欠落していれば409 `capture_missing` で停止します。
|
||||||
|
存続中のタスクを異内容のcaptureで上書きすることは許可しません。
|
||||||
|
|
||||||
|
2026-11-08 19:42:51 JSTに本番配備後の確認を完了しました。
|
||||||
|
DBスキーマ変更・既存データの削除・実タスクの再取り込みは行っていません。
|
||||||
|
Gecko等の未コミット変更は含みません。
|
||||||
|
|
||||||
|
## 再取り込み
|
||||||
|
|
||||||
|
サーバーをv0.14.1、利用するCLIをv0.4.2に更新してから実行します。
|
||||||
|
別インスタンスへ接続している場合は、その接続先サーバーの更新も必要です。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pages --version
|
||||||
|
pages task retry REQUEST_UUID --recreate-deleted
|
||||||
|
```
|
||||||
|
|
||||||
|
保持した下書きから、新UUIDのタスクを作成します。旧UUIDの削除記録とDAV識別子予約を残し、
|
||||||
|
通常の再送で古いタスクが復活するのを防ぎます。再取り込み用IDは決定的で、応答消失や並行再送でも重複作成しません。
|
||||||
|
既存Wikiが保存先にあれば本文・リビジョンは変更せず、新タスクから関連付けます。
|
||||||
|
ページがなければ保留本文から作ります。移動済みページの自動探索や旧作業記録の復元ではありません。
|
||||||
|
|
||||||
|
通信失敗時はCLIが表示する新IDで `pages task retry NEW_REQUEST_UUID` を実行します。
|
||||||
|
セッションファイルや受付記録を手動で消さないでください。
|
||||||
|
詳細は[実装契約](../../design/ja/tasks-implementation.md#削除済みメール取り込みの再作成)と
|
||||||
|
[CLIのNeoMutt手順](https://git.anya.jp/anya/pages-cli/src/tag/v0.4.2/docs/neomutt.md)を参照してください。
|
||||||
|
|
||||||
|
## リリースと検証
|
||||||
|
|
||||||
|
| 対象 | タグ | commit | CI |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| PagesWiki | [v0.14.1](https://git.anya.jp/anya/pages/releases/tag/v0.14.1) | `4049acf76e36c12b8f3c506de5eaf1e920ac7e86` | [build 72](https://git.anya.jp/anya/pages/actions/runs/72)、[release 75](https://git.anya.jp/anya/pages/actions/runs/75) success |
|
||||||
|
| pages-cli | [v0.4.2](https://git.anya.jp/anya/pages-cli/releases/tag/v0.4.2) | `e27c023d66a61b73d3fe47e982daa6f34213c41f` | [build 73](https://git.anya.jp/anya/pages-cli/actions/runs/73)、[release 74](https://git.anya.jp/anya/pages-cli/actions/runs/74) success |
|
||||||
|
|
||||||
|
- 正確なリリースソースで `go test ./...`。server/storeのgo vet、削除・再取り込み・並行再送のrace検査が成功。
|
||||||
|
- CLIの52単体テスト、サーバーとCLIのHTTP結合テストが成功。Wiki本文・版の保全、他所有者拒否、readonly、kill switch、入力上限、保存途中のロールバックを検証。
|
||||||
|
- 公開されたCLIの4配布ファイルをSHA256SUMSで照合し、Pythonソースとcommitを照合。
|
||||||
|
- 配布Linux ELFでバージョン、メール取り込み、下書き差し替え、削除済み再取り込み、認証・ファイル権限のスモークテストとTLS関連6テストが成功。
|
||||||
|
- Linux ELFはglibc 2.36以降。macOS/Windowsの未検証バイナリは配布していません。
|
||||||
|
|
||||||
|
## 本番切り替えと復旧点
|
||||||
|
|
||||||
|
app・app2・adaptor-gateway・excalidraw-viewerを同じv0.14.1へ更新しました。
|
||||||
|
`.env.release` の選択は `PAGESWIKI_IMAGE_TAG=v0.14.1` です。
|
||||||
|
|
||||||
|
- 19:40:36 JSTに停止開始。
|
||||||
|
- 19:42:17 JSTに、停止時点のdata/data2についてchecksum同期、再走査の差分ゼロ、DBファイル一致を確認。
|
||||||
|
- 19:42:23 JSTに新版の起動と両アプリのhealth応答を確認。
|
||||||
|
- 設定と停止時データは `.deployment-backups/release-v0.14.1-20261108/` の `config/` と `cutover/data`、`cutover/data2` に保存。DBのinodeは稼働元と独立しています。
|
||||||
|
- 旧3イメージを `rollback-before-v0.14.1-20261108` タグで保持。旧バックアップも残しています。
|
||||||
|
|
||||||
|
v0.14.0への切り戻しはイメージ選択のみで行い、DBを過去へ戻しません。
|
||||||
|
その場合は再取り込みAPIが利用できなくなるため、CLIの再取り込み操作を止めてください。
|
||||||
|
v0.14.0より前への切り戻しは削除記録の扱いが異なり、[v0.14.0の注意点](2026-11-08-task-deletion.md#dbと切り戻し)が引き続き適用されます。
|
||||||
|
|
||||||
|
## 配備後確認
|
||||||
|
|
||||||
|
- 4サービスのrevisionが対象commitと一致、running、再起動回数0。
|
||||||
|
- app/app2のhealth正常。管理対象13スキーマはcurrent。これはlegacy領域を含む全移行検証ではありませんが、今回の変更にスキーマ移行はありません。
|
||||||
|
- 両DBの `quick_check` はok。
|
||||||
|
- 外部HTTPSのhealth・ログイン画面200。匿名のタスク/ダッシュボード/RSS画面303、タスクAPI401。匿名DELETEとcapture POSTも401。
|
||||||
|
- tasks.js、tasks.css、organizer-dashboard.js、feeds.js、feed-gecko.jsのSHA-256がリリースcommitと一致。
|
||||||
|
- 起動直後のfatal/panic、DB lock、schema/migration failure、event job failureは両アプリとも0件。
|
||||||
|
- 実際のメール本文・利用者の保留下書きを使った再取り込みは実施していません。
|
||||||
|
|
||||||
|
## 配布イメージ
|
||||||
|
|
||||||
|
SHAタグから再ビルドせず昇格。本番で取得したdigestとCI結果は一致しています。
|
||||||
|
|
||||||
|
| イメージ(`git.anya.jp/anya/`、タグ`v0.14.1`) | manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:11488fb958db12ec5a25aa265fc8179a31ab5728800f47605759822a44eb81e6` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:ca17704eb5e88a4e73827ff2a5fafda7c4bb7d9be3987b5a83a3a5ae0c780098` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:a2b692c3864b8c4f13412e746fcea7cd9a2c03d49e0d5ead252432f37930c4c4` |
|
||||||
@@ -14,7 +14,7 @@ Geckoの追加整備やRSSの追加ショートカットなど、並行作業中
|
|||||||
- CalDAV一覧/REPORTから削除対象を除外。削除済みのUUIDとcollection内のDAV UID/hrefを予約し、古い端末からの再作成を拒否。
|
- CalDAV一覧/REPORTから削除対象を除外。削除済みのUUIDとcollection内のDAV UID/hrefを予約し、古い端末からの再作成を拒否。
|
||||||
- 従来のDAV DELETEをアーカイブへ変換する動作は維持。
|
- 従来のDAV DELETEをアーカイブへ変換する動作は維持。
|
||||||
|
|
||||||
詳細は[タスクの実装契約](../../design/ja/tasks-implementation.md#タスクの削除2026-11-08実装未デプロイ)を参照してください。
|
詳細は[タスクの実装契約](../../design/ja/tasks-implementation.md#タスクの削除)を参照してください。
|
||||||
|
|
||||||
## DBと切り戻し
|
## DBと切り戻し
|
||||||
|
|
||||||
@@ -27,7 +27,44 @@ Geckoの追加整備やRSSの追加ショートカットなど、並行作業中
|
|||||||
|
|
||||||
## 検証と配備
|
## 検証と配備
|
||||||
|
|
||||||
配備前に、リリース対象だけを切り出したソースの全体テストとCIビルド、
|
対象commitは `38a4fcf5301e0c7c6cad12070e040dc62a03d41b`。
|
||||||
本番DBの隔離コピーを使った追加スキーマの整合性検査を実施します。
|
2026-11-08 18:20:25 JSTに配備後の検証を完了しました。
|
||||||
停止時点のデータ・設定と旧イメージを保全し、配備後にhealth、認証境界、静的ファイルの配信を検証します。
|
|
||||||
本番のタスク削除や外部カレンダー本文を用いた検証は行いません。
|
- [ビルドCI run 68](https://git.anya.jp/anya/pages/actions/runs/68)、[リリースCI run 69](https://git.anya.jp/anya/pages/actions/runs/69)はともにsuccess。
|
||||||
|
- [Gitea Release v0.14.0](https://git.anya.jp/anya/pages/releases/tag/v0.14.0)と注釈付きGitタグを公開。
|
||||||
|
- リリース対象だけの独立ソースで `go test -p 1 ./...`、server/storeのgo vet、配布ツール等15テスト、PC・モバイル幅のChromium回帰試験が成功。
|
||||||
|
- 両本番DBのオンラインバックアップを隔離し、`EnsureTasksSchema`を各2回実行。task head・版参照・DAV resource/collection識別子のdigestが移行前後で一致し、削除記録は0件、`integrity_check`はok。
|
||||||
|
- app・app2・adaptor-gateway・excalidraw-viewerを同じv0.14.0へ更新。他サービス・Gecko設定・利用者設定は変更なし。
|
||||||
|
|
||||||
|
本番のタスク削除や外部カレンダー本文を用いた検証は行っていません。
|
||||||
|
|
||||||
|
### 復旧点
|
||||||
|
|
||||||
|
`.deployment-backups/release-v0.14.0-20261108/` の `config/` に旧構成、
|
||||||
|
`cutover/data`・`cutover/data2`に停止時点のデータを保存しています。
|
||||||
|
18:18:53 JSTに停止を開始、18:19:57 JSTにchecksum同期・再走査の差分ゼロ・DB一致を確認しました。
|
||||||
|
稼働元とinodeを共有しません。旧バックアップは削除していません。
|
||||||
|
旧3イメージは `rollback-before-v0.14.0-20261108` タグで保持しています。
|
||||||
|
|
||||||
|
`.env.release` は `PAGESWIKI_IMAGE_TAG=v0.14.0`。
|
||||||
|
新版の4サービスは18:20:12〜18:20:18 JSTに起動しました。
|
||||||
|
|
||||||
|
### 配備後検証
|
||||||
|
|
||||||
|
- 4サービスのrevisionが対象commitと一致、running、再起動回数0。
|
||||||
|
- app・app2のhealthと管理スキーマ検査が正常。legacy task領域は上記の隔離コピー移行試験で別途確認。
|
||||||
|
- 両DBの `quick_check` がok、削除記録0件。
|
||||||
|
- 外部HTTPSのhealth・ログイン画面200。匿名のタスク/ダッシュボード/RSS画面は303、タスクAPIは401。
|
||||||
|
- 実在しないUUIDへの匿名DELETEを401で拒否。
|
||||||
|
- tasks.js、tasks.css、organizer-dashboard.js、feeds.js、feed-gecko.jsの配信SHA-256がリリースcommitと一致。未完了Gecko変更の混入なし。
|
||||||
|
- 起動直後のfatal/panic、DB lock、event job failed、schema/migration errorは両アプリとも各0件。
|
||||||
|
|
||||||
|
### 配布イメージ
|
||||||
|
|
||||||
|
SHAタグから再ビルドせず昇格し、本番ホストで取得したdigestとCIの昇格結果が一致しています。
|
||||||
|
|
||||||
|
| イメージ(`git.anya.jp/anya/`、タグ`v0.14.0`) | manifest digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:46edb2640bfda3be73d8bed354bb1e014b050d68b6c17af8036d65d7732378af` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:696f2d0bcdf1a3dce8821c061a78ad9f3d6fcaadda32cc1cb4e5d5a117028fc0` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:4d72abb4c1964553458af2b95e19722e18ae05fcfa2b02ff086407ad962ca62c` |
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# PagesWiki v0.15.0とpages-cli v0.5.0
|
||||||
|
|
||||||
|
ブラウザアップロード、信頼端末ログイン、RSSの配信時刻、CSV投影とタスクの関連ページ導線を追加します。Geckoの整備コードと配布イメージも含みますが、専用relayの本番有効化は行いません。
|
||||||
|
|
||||||
|
## 変更内容
|
||||||
|
|
||||||
|
- `/v/browser` のファイルドロップと右下のキュー。逐次送信、待機取消、折りたたみ、同名保護、一覧だけの更新。ページを閉じた後の再開とフォルダ再帰アップロードは未対応。
|
||||||
|
- ログイン時の信頼端末選択。管理者指定の最大30日・絶対期限で、既存セッションは延長しません。パスワード/TOTP、OIDC、LDAP、マジックリンクに選択を引き継ぎます。
|
||||||
|
- CLIの `login --remember` と期限切れ再ログイン時の作業パス/保留下書き保持。
|
||||||
|
- RSS一覧の配信時刻とDomainタイムゾーン。本文の日付表示も同じタイムゾーンへ統一。
|
||||||
|
- 保存済みタスクの関連Wikiページを開くボタン。
|
||||||
|
- 認証済み閲覧者の権限を確認する有界CSV macro。`{{csv:/data/items.csv range=A1:H200 header=true}}` と同じObjectのRevision固定に対応。CSV編集・匿名投影・外部URL取得は含みません。
|
||||||
|
- Geckoの日本語ページ内検索、起動上限・失敗時のiframe破棄、固定ソース/notice付き配布物検査。Safari実機、IME・コピー、運用firewallと低メモリ受入は残件。
|
||||||
|
|
||||||
|
## リリースと検証
|
||||||
|
|
||||||
|
本体commitは `b90aef79d03c21332cd49a47aba015a30f6de1a0`。Gitea [build 76](https://git.anya.jp/anya/pages/actions/runs/76)、[release 79](https://git.anya.jp/anya/pages/actions/runs/79) が成功し、SHAイメージを再ビルドせず `v0.15.0` へ昇格しました。
|
||||||
|
|
||||||
|
CLI commitは `bee03094f3bf2fa0c2dab80313d2f4bd15452c3d`。[v0.5.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.5.0) のCIと55単体テストが成功。公開した4ファイルのSHA256SUMS照合、Pythonソース一致、取得したLinux ELFのバージョン・ログイン・タスク/メール取り込み・下書き回復等の合成スモークテストを確認しました。未検証のmacOS/Windowsバイナリは追加していません。
|
||||||
|
|
||||||
|
本体は `go test ./...`、`go vet ./...`、リリースツールと壁紙テスト、Gecko配布ツールのテストが成功。Chromiumで認証・タスク・RSS・Gecko・アップロードの合成試験を実施しました。アップロードキューは1280px/390px幅、逐次送信、同名保護、取消、一覧更新を検証しています。
|
||||||
|
|
||||||
|
## DBと復旧
|
||||||
|
|
||||||
|
`cli-auth` v1→v2で `auth_cli_requests.remember` を既定0・0/1制約付きで追加します。他の管理対象componentのversionは変わりません。両インスタンスの独立コピーで、ネットワークを遮断しworkerを停止して新イメージを起動し、schema checkとSQLite integrity_checkが成功しました。実外部カレンダーやメール内容は検証に使用していません。
|
||||||
|
|
||||||
|
保全先は `.deployment-backups/release-v0.15.0-20261108/`。`config/` に旧設定、`cutover/data` と `cutover/data2` に停止時点のデータを保存します。旧3イメージの `rollback-before-v0.15.0-20261108` タグと既存バックアップを保持します。
|
||||||
|
|
||||||
|
新しいmigration履歴を旧版が受け付けるとは限らないため、旧イメージだけのダウングレードは行いません。切戻しが必要ならwriterを止め、切替後データも保全し、停止時バックアップとの変更差分を扱ってからDB・ファイル・設定・イメージを同じ復旧点へ戻します。運用開始後の書き込みを黙って破棄しません。
|
||||||
|
|
||||||
|
## 本番反映
|
||||||
|
|
||||||
|
2026-11-08 20:41:33 JSTに配備後確認を完了しました。20:40:05に停止し、20:41:10に停止時バックアップを検証、20:41:16に新版の起動とhealthを確認しています。
|
||||||
|
|
||||||
|
- app・app2・adaptor-gateway・excalidraw-viewerはすべて対象commitと一致し、running・再起動回数0。
|
||||||
|
- 両DBのquick_checkはok、管理対象13componentはcurrent。legacy領域全体の検証を意味するものではありません。
|
||||||
|
- 外部HTTPSのhealth・ログイン画面200。匿名タスク/dashboard/RSS画面303、タスクAPI・DELETE・captureは401。
|
||||||
|
- tasks、RSS、Gecko、アップロードキュー、信頼端末UIの配信JS/CSSはリリースcommitとSHA-256一致。公開ログイン画面の信頼端末選択も確認。
|
||||||
|
- 起動直後のfatal/panic、DB/schema failure、event job failureは両アプリとも0件。
|
||||||
|
- `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.15.0`。Gecko relayコンテナは起動せず、通常3イメージ・4サービスだけを更新。
|
||||||
|
|
||||||
|
配備イメージのmanifest digest:
|
||||||
|
|
||||||
|
| イメージ(`git.anya.jp/anya/`) | digest |
|
||||||
|
| --- | --- |
|
||||||
|
| pageswiki-app | `sha256:43c398f2c294c7802987aaae1bfdf27b3d0c7ea24fa73df912ac03ea312366b0` |
|
||||||
|
| pageswiki-adaptor-gateway | `sha256:aebc515c3b3e36b58b03ecab1646e6d95b0dd21074a1a863ca5806cb7fde4df1` |
|
||||||
|
| pageswiki-excalidraw-viewer | `sha256:4a80354aa4567abe52ff17e32a6f224e85d8cd2e0f1a466e5690b4b353d901cc` |
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# PagesWiki v0.16.0
|
||||||
|
|
||||||
|
2026-11-09 05:58:14 JSTに本番の配備後確認を完了しました。CSVの表編集・複数セル貼り付けと、Reveal.jsのビューア・編集プレビューを追加します。
|
||||||
|
|
||||||
|
## 変更と利用方法
|
||||||
|
|
||||||
|
- 既存CSVを `/e/-/{path}` で表編集。行列操作、Undo/Redo、タブ区切りの複数セル貼り付け、既存の下書き・履歴・競合確認に対応します。未変更セルの引用符・BOM・改行を保持し、上限超過時は部分反映しません。
|
||||||
|
- HTMLページのスライドアイコン、または `/v/slides/{path}` でReveal.js表示。エディタのスライドアイコンで未保存HTML/Markdownをプレビューします。Markdownの空行で囲んだ `---`、HTML直下の `<hr>` で区切ります。
|
||||||
|
- Reveal.js 6.0.2をMITライセンスとともにローカル同梱。sandbox、Path認可、入力上限、テーマ追従、スマホの全幅プレビューに対応。拡張設定の `viewer.slides` でドメイン単位に停止できます。
|
||||||
|
|
||||||
|
CSVは全体256 KiB、表200行・32列・セル16 KiB以内。スライドは256 KiB・100枚以内です。縦スライド・発表者ノート・専用印刷・外部画像承認連携は含みません。通常HTMLの自動表示をスライドへ置き換えません。
|
||||||
|
|
||||||
|
## リリースと検証
|
||||||
|
|
||||||
|
対象commitは `02fb77f72b45c342c6b458d733f840b38cc3ae56`。[build 80](https://git.anya.jp/anya/pages/actions/runs/80)と[release 81](https://git.anya.jp/anya/pages/actions/runs/81)が成功し、同じSHAのイメージを再ビルドせずv0.16.0へ昇格しました。
|
||||||
|
|
||||||
|
開発環境で全Goテスト・go vet・JS単体テスト、1280px/390pxのChromium試験を実施しました。CSV保存・競合・履歴・貼り付け拒否、スライドのライブ更新・通常プレビュー復帰・左右キー・履歴非変更・隔離を確認しています。
|
||||||
|
|
||||||
|
本番ではapp・app2・adaptor-gateway・excalidraw-viewerのrevision一致、running、再起動0を確認。両アプリのhealth、外部HTTPSのhealth/login 200、匿名タスク・スライドの303、タスクAPIの401を確認しました。CSV/Reveal.js関連の11配信ファイルはリリースcommitとSHA-256一致。両DBのquick_checkはok、管理対象13componentはcurrentで版変更なしです。legacy領域全体の移行検証を意味しません。起動直後のpanic・fatal・DB/schema失敗・event job失敗に該当するログはありませんでした。
|
||||||
|
|
||||||
|
本番の実コンテンツを編集する試験、外部カレンダー・メール内容の取得は行っていません。pages-cliは変更せず、Gecko relayも起動していません。
|
||||||
|
|
||||||
|
## 保全と切替
|
||||||
|
|
||||||
|
DBスキーマ・ストレージ形式の変更はありません。保全先は `.deployment-backups/release-v0.16.0-20261109/`。`config/` に旧設定、`cutover/data` と `cutover/data2` に停止時点のファイルを保持しています。DBだけは容量を考慮して `pages.db.gz` とし、gzip検査と展開内容のバイト一致を確認しました。他のファイルは停止時checksum比較で一致しています。復旧用に展開する場合は、稼働DBを上書きせず別の停止済み復旧領域に `pages.db` として展開します。
|
||||||
|
|
||||||
|
初回は圧縮で変わったバックアップ先フォルダmtimeを厳密差分検査が検出し、新版起動前にv0.15.0へ自動復帰しました。圧縮後にフォルダmtimeを元に合わせる修正を行い、内容の検証は省略せず再実行しています。再試行は05:54:59 JSTに停止、05:57:28にバックアップ検証完了、05:57:34に新版health確認完了です。
|
||||||
|
|
||||||
|
旧イメージは `rollback-before-v0.16.0-20261109` タグで保持し、過去のバックアップも削除していません。今回のUI機能を切り戻す場合はwriterを止め、現データを保持してv0.15.0のイメージへ戻せます。バックアップ時点へのデータ復旧を選ぶ場合は、切替後の書き込みを別途保全して差分を扱い、黙って破棄しません。
|
||||||
|
|
||||||
|
`.env.release` は `PAGESWIKI_IMAGE_TAG=v0.16.0`。配備後の空き容量は約8.1 GiBのため、次の大きなビルド・バックアップの前に保持世代と不要キャッシュの整理が必要です。
|
||||||
|
|
||||||
|
## 配備イメージ
|
||||||
|
|
||||||
|
- `pageswiki-app`: `sha256:428f4c38297e7d2b529af13b32d45e6a9b40f58915fbd170148a0ad07958a034`
|
||||||
|
- `pageswiki-adaptor-gateway`: `sha256:cdf99b4f02a9abade8862caea1c23cfe775f229118c5c1aabf2584d84a02be50`
|
||||||
|
- `pageswiki-excalidraw-viewer`: `sha256:854fa1d0bb931642e81af394ab4631b47397a94264eb1b34d4f8ff0ca5435e25`
|
||||||
|
|
||||||
|
レジストリのprefixは `git.anya.jp/anya/`、共通タグは `v0.16.0` です。
|
||||||
@@ -7,11 +7,19 @@ require (
|
|||||||
github.com/go-ldap/ldap/v3 v3.4.8
|
github.com/go-ldap/ldap/v3 v3.4.8
|
||||||
github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df
|
github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/jackc/pgx/v5 v5.13.0
|
||||||
github.com/microcosm-cc/bluemonday v1.0.27
|
github.com/microcosm-cc/bluemonday v1.0.27
|
||||||
golang.org/x/text v0.22.0
|
golang.org/x/text v0.41.0
|
||||||
modernc.org/sqlite v1.32.0
|
modernc.org/sqlite v1.32.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||||
|
golang.org/x/sync v0.22.0 // indirect
|
||||||
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||||
github.com/SherClockHolmes/webpush-go v1.4.0
|
github.com/SherClockHolmes/webpush-go v1.4.0
|
||||||
@@ -30,9 +38,9 @@ require (
|
|||||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
github.com/teambition/rrule-go v1.8.2
|
github.com/teambition/rrule-go v1.8.2
|
||||||
golang.org/x/crypto v0.33.0
|
golang.org/x/crypto v0.37.0
|
||||||
golang.org/x/net v0.35.0
|
golang.org/x/net v0.35.0
|
||||||
golang.org/x/sys v0.30.0 // indirect
|
golang.org/x/sys v0.32.0
|
||||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
|
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
|
||||||
modernc.org/libc v1.55.3 // indirect
|
modernc.org/libc v1.55.3 // indirect
|
||||||
modernc.org/mathutil v1.6.0 // indirect
|
modernc.org/mathutil v1.6.0 // indirect
|
||||||
|
|||||||
@@ -41,6 +41,14 @@ github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/C
|
|||||||
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||||
|
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
|
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
|
||||||
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
|
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
|
||||||
github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=
|
github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=
|
||||||
@@ -70,11 +78,14 @@ github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NF
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
|
||||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
github.com/teambition/rrule-go v1.8.2 h1:lIjpjvWTj9fFUZCmuoVDrKVOtdiyzbzc93qTmRVe/J8=
|
github.com/teambition/rrule-go v1.8.2 h1:lIjpjvWTj9fFUZCmuoVDrKVOtdiyzbzc93qTmRVe/J8=
|
||||||
github.com/teambition/rrule-go v1.8.2/go.mod h1:Ieq5AbrKGciP1V//Wq8ktsTXwSwJHDD5mD/wLBGl3p4=
|
github.com/teambition/rrule-go v1.8.2/go.mod h1:Ieq5AbrKGciP1V//Wq8ktsTXwSwJHDD5mD/wLBGl3p4=
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
@@ -88,14 +99,15 @@ golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDf
|
|||||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||||
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||||
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
|
|
||||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
|
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||||
|
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
@@ -116,8 +128,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
|||||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
|
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||||
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
@@ -130,8 +142,8 @@ golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
|||||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
@@ -151,15 +163,16 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
|||||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
|
|
||||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||||
|
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||||
|
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package calendar
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewPostgreSQL initializes disposable indexes, not canonical calendar data.
|
||||||
|
// All writers sharing this DB must share Root and its working flock semantics.
|
||||||
|
// Separate replicas with independent filesystems are not a supported HA mode.
|
||||||
|
func NewPostgreSQL(ctx context.Context, root string, database *sql.DB) (*Repository, error) {
|
||||||
|
if root == "" || database == nil {
|
||||||
|
return nil, errors.New("calendar storage unavailable")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
err := db.ApplyPostgreSQLMigrations(ctx, database, "calendar-cache", []db.PostgreSQLMigration{{Version: 1, Name: "rebuildable monthly calendar indexes", Statements: []string{
|
||||||
|
`CREATE TABLE calendar_index_state(domain TEXT COLLATE "C" NOT NULL,calendar TEXT COLLATE "C" NOT NULL,version TEXT NOT NULL,PRIMARY KEY(domain,calendar))`,
|
||||||
|
`CREATE TABLE calendar_month_cache(domain TEXT COLLATE "C" NOT NULL,calendar TEXT COLLATE "C" NOT NULL,month TEXT COLLATE "C" NOT NULL,hash TEXT NOT NULL,PRIMARY KEY(domain,calendar,month))`,
|
||||||
|
`CREATE TABLE calendar_event_cache(domain TEXT COLLATE "C" NOT NULL,calendar TEXT COLLATE "C" NOT NULL,uid TEXT COLLATE "C" NOT NULL,month TEXT COLLATE "C" NOT NULL,start BIGINT NOT NULL,"end" BIGINT NOT NULL,etag TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain,calendar,uid))`,
|
||||||
|
`CREATE INDEX calendar_event_range ON calendar_event_cache(domain,calendar,start,"end")`,
|
||||||
|
}, Assertions: []string{
|
||||||
|
`SELECT domain,calendar,version FROM calendar_index_state WHERE 1=0`,
|
||||||
|
`SELECT domain,calendar,month,hash FROM calendar_month_cache WHERE 1=0`,
|
||||||
|
`SELECT domain,calendar,uid,month,start,"end",etag,data FROM calendar_event_cache WHERE 1=0`,
|
||||||
|
}}})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Repository{Root: root, DB: database, postgres: true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compose source-owned SQL; never translate arbitrary SQL at runtime.
|
||||||
|
func (r *Repository) p(n int) string {
|
||||||
|
if r.postgres {
|
||||||
|
return fmt.Sprintf("$%d", n)
|
||||||
|
}
|
||||||
|
return "?"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) failure(err error) error {
|
||||||
|
if !r.postgres || err == nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, known := range []error{ErrForbidden, ErrConflict, ErrPreconditionRequired, ErrMissing, ErrLimit, ErrInvalid, ErrNameTaken, sql.ErrNoRows, context.Canceled, context.DeadlineExceeded} {
|
||||||
|
if errors.Is(err, known) {
|
||||||
|
return known
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var safe *db.PostgreSQLError
|
||||||
|
if errors.As(err, &safe) {
|
||||||
|
return safe
|
||||||
|
}
|
||||||
|
var pg *pgconn.PgError
|
||||||
|
if errors.As(err, &pg) {
|
||||||
|
return &db.PostgreSQLError{Operation: "calendar cache", SQLState: pg.Code}
|
||||||
|
}
|
||||||
|
// Encoding/Scan errors can contain event contents too.
|
||||||
|
return errors.New("calendar operation failed")
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"strings"
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
)
|
)
|
||||||
|
|
||||||
func DAVFilename(c Calendar, uid string) string {
|
func DAVFilename(c Calendar, uid string) string {
|
||||||
@@ -36,7 +38,7 @@ func DAVUID(c Calendar, name string) (string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
b, err := base64.RawURLEncoding.DecodeString(strings.TrimSuffix(name, ".ics"))
|
b, err := base64.RawURLEncoding.DecodeString(strings.TrimSuffix(name, ".ics"))
|
||||||
if err != nil || len(b) == 0 || len(b) > 512 {
|
if err != nil || len(b) == 0 || len(b) > 512 || !utf8.Valid(b) || strings.IndexFunc(string(b), unicode.IsControl) >= 0 {
|
||||||
return "", ErrMissing
|
return "", ErrMissing
|
||||||
}
|
}
|
||||||
return string(b), nil
|
return string(b), nil
|
||||||
@@ -44,7 +46,8 @@ func DAVUID(c Calendar, name string) (string, error) {
|
|||||||
|
|
||||||
// DAVSnapshot is complete or fails; a truncated listing can cause client deletes.
|
// DAVSnapshot is complete or fails; a truncated listing can cause client deletes.
|
||||||
// The metadata lock keeps href mappings and event generations in one snapshot.
|
// The metadata lock keeps href mappings and event generations in one snapshot.
|
||||||
func (r *Repository) DAVSnapshot(ctx context.Context, domain, id, actor string, withData bool) (Calendar, []Event, error) {
|
func (r *Repository) DAVSnapshot(ctx context.Context, domain, id, actor string, withData bool) (result Calendar, itemsResult []Event, resultErr error) {
|
||||||
|
defer func() { resultErr = r.failure(resultErr) }()
|
||||||
c, _, unlock, err := r.locked(ctx, domain, id, actor)
|
c, _, unlock, err := r.locked(ctx, domain, id, actor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c, nil, err
|
return c, nil, err
|
||||||
@@ -54,7 +57,7 @@ func (r *Repository) DAVSnapshot(ctx context.Context, domain, id, actor string,
|
|||||||
if withData {
|
if withData {
|
||||||
cols = "uid,etag,data"
|
cols = "uid,etag,data"
|
||||||
}
|
}
|
||||||
rows, err := r.DB.QueryContext(ctx, `SELECT `+cols+` FROM calendar_event_cache WHERE domain=? AND calendar=? ORDER BY uid LIMIT 10001`, domain, id)
|
rows, err := r.DB.QueryContext(ctx, `SELECT `+cols+` FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` ORDER BY uid LIMIT 10001`, domain, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c, nil, err
|
return c, nil, err
|
||||||
}
|
}
|
||||||
@@ -77,7 +80,8 @@ func (r *Repository) DAVSnapshot(ctx context.Context, domain, id, actor string,
|
|||||||
|
|
||||||
// ChangeDAV reserves resource identities in the same manifest commit as the
|
// ChangeDAV reserves resource identities in the same manifest commit as the
|
||||||
// monthly snapshots. Existing resources still require an exact strong ETag.
|
// monthly snapshots. Existing resources still require an exact strong ETag.
|
||||||
func (r *Repository) ChangeDAV(ctx context.Context, domain, id, actor, name, match string, item *Event, authorize func() error) (Event, bool, error) {
|
func (r *Repository) ChangeDAV(ctx context.Context, domain, id, actor, name, match string, item *Event, authorize func() error) (eventResult Event, created bool, resultErr error) {
|
||||||
|
defer func() { resultErr = r.failure(resultErr) }()
|
||||||
if !ValidDAVFilename(name) {
|
if !ValidDAVFilename(name) {
|
||||||
return Event{}, false, ErrInvalid
|
return Event{}, false, ErrInvalid
|
||||||
}
|
}
|
||||||
@@ -94,7 +98,7 @@ func (r *Repository) ChangeDAV(ctx context.Context, domain, id, actor, name, mat
|
|||||||
uid, _ := DAVUID(c, name)
|
uid, _ := DAVUID(c, name)
|
||||||
var exists bool
|
var exists bool
|
||||||
if uid != "" {
|
if uid != "" {
|
||||||
if err = r.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?)`, domain, id, uid).Scan(&exists); err != nil {
|
if err = r.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3)+`)`, domain, id, uid).Scan(&exists); err != nil {
|
||||||
return Event{}, false, err
|
return Event{}, false, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -114,7 +118,7 @@ func (r *Repository) ChangeDAV(ctx context.Context, domain, id, actor, name, mat
|
|||||||
}
|
}
|
||||||
uid = item.UID
|
uid = item.UID
|
||||||
var tag string
|
var tag string
|
||||||
err = r.DB.QueryRowContext(ctx, `SELECT etag FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?`, domain, id, uid).Scan(&tag)
|
err = r.DB.QueryRowContext(ctx, `SELECT etag FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&tag)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return Event{}, false, ErrConflict
|
return Event{}, false, ErrConflict
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package calendar
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -9,6 +10,22 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestDAVUIDRejectsBinaryFallback(t *testing.T) {
|
||||||
|
for _, raw := range []string{"\xff\xfe", "uid\x00value", "uid\nvalue"} {
|
||||||
|
name := base64.RawURLEncoding.EncodeToString([]byte(raw)) + ".ics"
|
||||||
|
if _, err := DAVUID(Calendar{}, name); !errors.Is(err, ErrMissing) {
|
||||||
|
t.Fatalf("binary UID accepted: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name := "client.ics"
|
||||||
|
if _, err := DAVUID(Calendar{}, name); !errors.Is(err, ErrMissing) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if uid, err := DAVUID(Calendar{DAVNames: map[string]string{"日本語@example.invalid": name}}, name); err != nil || uid != "日本語@example.invalid" {
|
||||||
|
t.Fatal(uid, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCalendarDAVIdentityAtomicAndRebuild(t *testing.T) {
|
func TestCalendarDAVIdentityAtomicAndRebuild(t *testing.T) {
|
||||||
r, domain, actor, c := fixture(t)
|
r, domain, actor, c := fixture(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ type Repository struct {
|
|||||||
Root string
|
Root string
|
||||||
DB *sql.DB
|
DB *sql.DB
|
||||||
PublicAllowed func(string) bool
|
PublicAllowed func(string) bool
|
||||||
|
postgres bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) canRead(domain string, c Calendar, actor string) bool {
|
func (r *Repository) canRead(domain string, c Calendar, actor string) bool {
|
||||||
@@ -66,8 +67,8 @@ func New(root string, db *sql.DB) (*Repository, error) {
|
|||||||
}
|
}
|
||||||
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS calendar_index_state(domain TEXT NOT NULL,calendar TEXT NOT NULL,version TEXT NOT NULL,PRIMARY KEY(domain,calendar));
|
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS calendar_index_state(domain TEXT NOT NULL,calendar TEXT NOT NULL,version TEXT NOT NULL,PRIMARY KEY(domain,calendar));
|
||||||
CREATE TABLE IF NOT EXISTS calendar_month_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,month TEXT NOT NULL,hash TEXT NOT NULL,PRIMARY KEY(domain,calendar,month));
|
CREATE TABLE IF NOT EXISTS calendar_month_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,month TEXT NOT NULL,hash TEXT NOT NULL,PRIMARY KEY(domain,calendar,month));
|
||||||
CREATE TABLE IF NOT EXISTS calendar_event_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,uid TEXT NOT NULL,month TEXT NOT NULL,start INTEGER NOT NULL,end INTEGER NOT NULL,etag TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain,calendar,uid));
|
CREATE TABLE IF NOT EXISTS calendar_event_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,uid TEXT NOT NULL,month TEXT NOT NULL,start INTEGER NOT NULL,"end" INTEGER NOT NULL,etag TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain,calendar,uid));
|
||||||
CREATE INDEX IF NOT EXISTS calendar_event_range ON calendar_event_cache(domain,calendar,start,end);`)
|
CREATE INDEX IF NOT EXISTS calendar_event_range ON calendar_event_cache(domain,calendar,start,"end");`)
|
||||||
return &Repository{Root: root, DB: db}, err
|
return &Repository{Root: root, DB: db}, err
|
||||||
}
|
}
|
||||||
func validID(s string) bool { u, err := uuid.Parse(s); return err == nil && u.String() == s }
|
func validID(s string) bool { u, err := uuid.Parse(s); return err == nil && u.String() == s }
|
||||||
@@ -347,7 +348,10 @@ func (r *Repository) Settings(ctx context.Context, domain, id, actor, version, n
|
|||||||
// with event/source writes. Cache rows are disposable, but deleting them
|
// with event/source writes. Cache rows are disposable, but deleting them
|
||||||
// before the atomic directory rename means a failed rename can safely rebuild
|
// before the atomic directory rename means a failed rename can safely rebuild
|
||||||
// them from the still-visible canonical files on the next access.
|
// them from the still-visible canonical files on the next access.
|
||||||
func (r *Repository) Delete(ctx context.Context, domain, id, actor, version string) error {
|
func (r *Repository) Delete(ctx context.Context, domain, id, actor, version string) (resultErr error) {
|
||||||
|
defer func() { resultErr = r.failure(resultErr) }()
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
dir, err := r.dir(domain, id)
|
dir, err := r.dir(domain, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -382,7 +386,7 @@ func (r *Repository) Delete(ctx context.Context, domain, id, actor, version stri
|
|||||||
}
|
}
|
||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
for _, table := range []string{"calendar_event_cache", "calendar_month_cache", "calendar_index_state"} {
|
for _, table := range []string{"calendar_event_cache", "calendar_month_cache", "calendar_index_state"} {
|
||||||
if _, err = tx.ExecContext(ctx, `DELETE FROM `+table+` WHERE domain=? AND calendar=?`, domain, id); err != nil {
|
if _, err = tx.ExecContext(ctx, `DELETE FROM `+table+` WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, id); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -413,9 +417,12 @@ func syncDirectory(path string) error {
|
|||||||
|
|
||||||
// refresh reconciles only changed monthly generations. A crash after manifest
|
// refresh reconciles only changed monthly generations. A crash after manifest
|
||||||
// commit but before index commit repairs itself on the next request.
|
// commit but before index commit repairs itself on the next request.
|
||||||
func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir string) error {
|
func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir string) (resultErr error) {
|
||||||
|
defer func() { resultErr = r.failure(resultErr) }()
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
var version string
|
var version string
|
||||||
if err := r.DB.QueryRowContext(ctx, `SELECT version FROM calendar_index_state WHERE domain=? AND calendar=?`, domain, c.ID).Scan(&version); err == nil && version == c.Version {
|
if err := r.DB.QueryRowContext(ctx, `SELECT version FROM calendar_index_state WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, c.ID).Scan(&version); err == nil && version == c.Version {
|
||||||
return nil
|
return nil
|
||||||
} else if err != nil && err != sql.ErrNoRows {
|
} else if err != nil && err != sql.ErrNoRows {
|
||||||
return err
|
return err
|
||||||
@@ -425,7 +432,7 @@ func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir
|
|||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
rows, e := tx.QueryContext(ctx, `SELECT month,hash FROM calendar_month_cache WHERE domain=? AND calendar=?`, domain, c.ID)
|
rows, e := tx.QueryContext(ctx, `SELECT month,hash FROM calendar_month_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, c.ID)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
@@ -445,10 +452,10 @@ func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir
|
|||||||
}
|
}
|
||||||
for m, h := range known {
|
for m, h := range known {
|
||||||
if c.Months[m] != h {
|
if c.Months[m] != h {
|
||||||
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_event_cache WHERE domain=? AND calendar=? AND month=?`, domain, c.ID, m); e != nil {
|
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3), domain, c.ID, m); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_month_cache WHERE domain=? AND calendar=? AND month=?`, domain, c.ID, m); e != nil {
|
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_month_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3), domain, c.ID, m); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -480,15 +487,15 @@ func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir
|
|||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_event_cache(domain,calendar,uid,month,start,end,etag,data) VALUES(?,?,?,?,?,?,?,?)`, domain, c.ID, event.UID, m, event.Start.Unix(), event.End.Unix(), event.ETag, event.Data); e != nil {
|
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_event_cache(domain,calendar,uid,month,start,"end",etag,data) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`,`+r.p(5)+`,`+r.p(6)+`,`+r.p(7)+`,`+r.p(8)+`)`, domain, c.ID, event.UID, m, event.Start.Unix(), event.End.Unix(), event.ETag, event.Data); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_month_cache(domain,calendar,month,hash) VALUES(?,?,?,?)`, domain, c.ID, m, h); e != nil {
|
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_month_cache(domain,calendar,month,hash) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`)`, domain, c.ID, m, h); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_index_state(domain,calendar,version) VALUES(?,?,?) ON CONFLICT(domain,calendar) DO UPDATE SET version=excluded.version`, domain, c.ID, c.Version); e != nil {
|
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_index_state(domain,calendar,version) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`) ON CONFLICT(domain,calendar) DO UPDATE SET version=excluded.version`, domain, c.ID, c.Version); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
return tx.Commit()
|
return tx.Commit()
|
||||||
@@ -540,7 +547,8 @@ func (r *Repository) query(ctx context.Context, domain, id, actor string, start,
|
|||||||
func (r *Repository) Upcoming(ctx context.Context, domain, id, actor string, start, end time.Time) ([]Event, error) {
|
func (r *Repository) Upcoming(ctx context.Context, domain, id, actor string, start, end time.Time) ([]Event, error) {
|
||||||
return r.queryLimit(ctx, domain, id, actor, start, end, true, 20)
|
return r.queryLimit(ctx, domain, id, actor, start, end, true, 20)
|
||||||
}
|
}
|
||||||
func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, start, end time.Time, withData bool, limit int) ([]Event, error) {
|
func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, start, end time.Time, withData bool, limit int) (result []Event, resultErr error) {
|
||||||
|
defer func() { resultErr = r.failure(resultErr) }()
|
||||||
if !end.After(start) || end.Sub(start) > 370*24*time.Hour {
|
if !end.After(start) || end.Sub(start) > 370*24*time.Hour {
|
||||||
return nil, ErrInvalid
|
return nil, ErrInvalid
|
||||||
}
|
}
|
||||||
@@ -553,7 +561,7 @@ func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, s
|
|||||||
if withData {
|
if withData {
|
||||||
columns = "data"
|
columns = "data"
|
||||||
}
|
}
|
||||||
rows, e := r.DB.QueryContext(ctx, `SELECT `+columns+` FROM calendar_event_cache WHERE domain=? AND calendar=? AND start<? AND (end>? OR (start=end AND start>=?)) ORDER BY start,uid LIMIT ?`, domain, id, end.Unix(), start.Unix(), start.Unix(), limit)
|
rows, e := r.DB.QueryContext(ctx, `SELECT `+columns+` FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND start<`+r.p(3)+` AND ("end">`+r.p(4)+` OR (start="end" AND start>=`+r.p(5)+`)) ORDER BY start,uid LIMIT `+r.p(6), domain, id, end.Unix(), start.Unix(), start.Unix(), limit)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return nil, e
|
return nil, e
|
||||||
}
|
}
|
||||||
@@ -583,14 +591,15 @@ func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, s
|
|||||||
}
|
}
|
||||||
return out, rows.Err()
|
return out, rows.Err()
|
||||||
}
|
}
|
||||||
func (r *Repository) Event(ctx context.Context, domain, id, actor, uid string) (Event, error) {
|
func (r *Repository) Event(ctx context.Context, domain, id, actor, uid string) (result Event, resultErr error) {
|
||||||
|
defer func() { resultErr = r.failure(resultErr) }()
|
||||||
_, _, unlock, e := r.locked(ctx, domain, id, actor)
|
_, _, unlock, e := r.locked(ctx, domain, id, actor)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return Event{}, e
|
return Event{}, e
|
||||||
}
|
}
|
||||||
defer unlock()
|
defer unlock()
|
||||||
var data string
|
var data string
|
||||||
e = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?`, domain, id, uid).Scan(&data)
|
e = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&data)
|
||||||
if e == sql.ErrNoRows {
|
if e == sql.ErrNoRows {
|
||||||
e = ErrMissing
|
e = ErrMissing
|
||||||
}
|
}
|
||||||
@@ -611,13 +620,14 @@ func (r *Repository) Change(ctx context.Context, domain, id, actor, uid, match s
|
|||||||
return r.changeLocked(ctx, domain, actor, uid, match, item, c, dir)
|
return r.changeLocked(ctx, domain, actor, uid, match, item, c, dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match string, item *Event, c Calendar, dir string) (Event, error) {
|
func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match string, item *Event, c Calendar, dir string) (result Event, resultErr error) {
|
||||||
|
defer func() { resultErr = r.failure(resultErr) }()
|
||||||
id := c.ID
|
id := c.ID
|
||||||
if !c.CanWrite(actor) {
|
if !c.CanWrite(actor) {
|
||||||
return Event{}, ErrForbidden
|
return Event{}, ErrForbidden
|
||||||
}
|
}
|
||||||
var oldData, oldMonth, oldTag string
|
var oldData, oldMonth, oldTag string
|
||||||
e := r.DB.QueryRowContext(ctx, `SELECT data,month,etag FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?`, domain, id, uid).Scan(&oldData, &oldMonth, &oldTag)
|
e := r.DB.QueryRowContext(ctx, `SELECT data,month,etag FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&oldData, &oldMonth, &oldTag)
|
||||||
exists := e == nil
|
exists := e == nil
|
||||||
if e != nil && e != sql.ErrNoRows {
|
if e != nil && e != sql.ErrNoRows {
|
||||||
return Event{}, e
|
return Event{}, e
|
||||||
@@ -650,7 +660,7 @@ func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match
|
|||||||
months[newMonth] = true
|
months[newMonth] = true
|
||||||
}
|
}
|
||||||
for month := range months {
|
for month := range months {
|
||||||
rows, e := r.DB.QueryContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=? AND calendar=? AND month=? AND uid<>? ORDER BY uid`, domain, id, month, uid)
|
rows, e := r.DB.QueryContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3)+` AND uid<>`+r.p(4)+` ORDER BY uid`, domain, id, month, uid)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return Event{}, e
|
return Event{}, e
|
||||||
}
|
}
|
||||||
@@ -717,7 +727,7 @@ func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match
|
|||||||
_ = os.Remove(file)
|
_ = os.Remove(file)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// The committed files, not SQLite, determine success. A subsequent read
|
// The committed files, not the database cache, determine success. A subsequent read
|
||||||
// reconciles the cache; retries with the old ETag correctly get 412.
|
// reconciles the cache; retries with the old ETag correctly get 412.
|
||||||
return next, nil
|
return next, nil
|
||||||
}
|
}
|
||||||
@@ -25,14 +25,15 @@ func (r *Repository) ReadPersonalLocalIndex(ctx context.Context, domain, id, act
|
|||||||
// TaskBlock gets a current event, or creates it if absent and a draft is supplied.
|
// TaskBlock gets a current event, or creates it if absent and a draft is supplied.
|
||||||
// Retries NEVER overwrite an event moved/edited in the calendar. Metadata policy
|
// Retries NEVER overwrite an event moved/edited in the calendar. Metadata policy
|
||||||
// is checked under the same lock as snapshot access and the eventual commit.
|
// is checked under the same lock as snapshot access and the eventual commit.
|
||||||
func (r *Repository) TaskBlock(ctx context.Context, domain, id, actor, uid string, draft *Event) (Calendar, Event, error) {
|
func (r *Repository) TaskBlock(ctx context.Context, domain, id, actor, uid string, draft *Event) (calendarResult Calendar, eventResult Event, resultErr error) {
|
||||||
|
defer func() { resultErr = r.failure(resultErr) }()
|
||||||
c, dir, unlock, err := r.lockedWithGuard(ctx, domain, id, actor, func(c Calendar) bool { return c.PersonalLocal(actor) })
|
c, dir, unlock, err := r.lockedWithGuard(ctx, domain, id, actor, func(c Calendar) bool { return c.PersonalLocal(actor) })
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Calendar{}, Event{}, err
|
return Calendar{}, Event{}, err
|
||||||
}
|
}
|
||||||
defer unlock()
|
defer unlock()
|
||||||
var data string
|
var data string
|
||||||
err = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?`, domain, id, uid).Scan(&data)
|
err = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&data)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
event, e := Parse(data)
|
event, e := Parse(data)
|
||||||
return c, event, e
|
return c, event, e
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"github.com/jackc/pgx/v5/stdlib"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PostgreSQLOptions is an instance-level secret-bearing configuration. Do not
|
||||||
|
// log it. Application startup additionally requires a verified full-import
|
||||||
|
// receipt; opening a connection alone does not authorize backend cutover.
|
||||||
|
type PostgreSQLOptions struct {
|
||||||
|
DSN string
|
||||||
|
MaxOpenConns int
|
||||||
|
MaxIdleConns int
|
||||||
|
ConnectTimeout time.Duration
|
||||||
|
// AllowInsecure permits plaintext or unverified TLS for isolated development
|
||||||
|
// only. Production defaults require verified TLS and no plaintext fallback.
|
||||||
|
AllowInsecure bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// PostgreSQLError deliberately excludes server messages, SQL, connection
|
||||||
|
// strings and constraint details, all of which can contain credentials or data.
|
||||||
|
// SQLState remains available for retry/conflict classification.
|
||||||
|
type PostgreSQLError struct {
|
||||||
|
Operation string
|
||||||
|
SQLState string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *PostgreSQLError) Error() string {
|
||||||
|
if e.SQLState != "" {
|
||||||
|
return fmt.Sprintf("PostgreSQL %s failed (SQLSTATE %s)", e.Operation, e.SQLState)
|
||||||
|
}
|
||||||
|
return "PostgreSQL " + e.Operation + " failed"
|
||||||
|
}
|
||||||
|
|
||||||
|
func postgresError(operation string, err error) error {
|
||||||
|
if errors.Is(err, context.Canceled) {
|
||||||
|
return context.Canceled
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
return context.DeadlineExceeded
|
||||||
|
}
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
result := &PostgreSQLError{Operation: operation}
|
||||||
|
if errors.As(err, &pgErr) {
|
||||||
|
result.SQLState = pgErr.Code
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func OpenPostgreSQL(ctx context.Context, options PostgreSQLOptions) (*sql.DB, error) {
|
||||||
|
if options.DSN == "" {
|
||||||
|
return nil, fmt.Errorf("PostgreSQL DSN is required")
|
||||||
|
}
|
||||||
|
if options.MaxOpenConns < 0 || options.MaxIdleConns < 0 || options.ConnectTimeout < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid PostgreSQL pool or timeout configuration")
|
||||||
|
}
|
||||||
|
config, err := pgx.ParseConfig(options.DSN)
|
||||||
|
if err != nil {
|
||||||
|
return nil, postgresError("configuration", err)
|
||||||
|
}
|
||||||
|
if !options.AllowInsecure {
|
||||||
|
if config.TLSConfig == nil || config.TLSConfig.InsecureSkipVerify {
|
||||||
|
return nil, fmt.Errorf("PostgreSQL requires verified TLS; use sslmode=verify-full")
|
||||||
|
}
|
||||||
|
for _, fallback := range config.Fallbacks {
|
||||||
|
if fallback.TLSConfig == nil || fallback.TLSConfig.InsecureSkipVerify {
|
||||||
|
return nil, fmt.Errorf("PostgreSQL insecure connection fallback is not allowed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
timeout := options.ConnectTimeout
|
||||||
|
if timeout == 0 {
|
||||||
|
timeout = 10 * time.Second
|
||||||
|
}
|
||||||
|
config.ConnectTimeout = timeout
|
||||||
|
config.RuntimeParams["application_name"] = "pageswiki"
|
||||||
|
database := stdlib.OpenDB(*config)
|
||||||
|
maxOpen := options.MaxOpenConns
|
||||||
|
if maxOpen == 0 {
|
||||||
|
maxOpen = 10
|
||||||
|
}
|
||||||
|
maxIdle := options.MaxIdleConns
|
||||||
|
if maxIdle == 0 {
|
||||||
|
maxIdle = 2
|
||||||
|
}
|
||||||
|
if maxIdle > maxOpen {
|
||||||
|
maxIdle = maxOpen
|
||||||
|
}
|
||||||
|
database.SetMaxOpenConns(maxOpen)
|
||||||
|
database.SetMaxIdleConns(maxIdle)
|
||||||
|
database.SetConnMaxLifetime(30 * time.Minute)
|
||||||
|
database.SetConnMaxIdleTime(5 * time.Minute)
|
||||||
|
pingCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
defer cancel()
|
||||||
|
if err := database.PingContext(pingCtx); err != nil {
|
||||||
|
_ = database.Close()
|
||||||
|
return nil, postgresError("connect", err)
|
||||||
|
}
|
||||||
|
return database, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PostgreSQLMigration contains native PostgreSQL SQL ($1 parameters, BIGINT
|
||||||
|
// timestamps). SQLite migration definitions must not be translated implicitly.
|
||||||
|
// Definitions are append-only after release. Assertions return no rows on success.
|
||||||
|
type PostgreSQLMigration struct {
|
||||||
|
Version int
|
||||||
|
Name string
|
||||||
|
Statements []string
|
||||||
|
Assertions []string `json:",omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func postgresMigrationChecksum(step PostgreSQLMigration) string {
|
||||||
|
encoded, _ := json.Marshal(step)
|
||||||
|
sum := sha256.Sum256(encoded)
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyPostgreSQLMigrations uses one transaction-scoped advisory lock for the
|
||||||
|
// migration namespace, including ledger creation. Component-specific locks
|
||||||
|
// would race concurrent first creation of the shared ledger. READ COMMITTED
|
||||||
|
// ensures a waiter sees the previous owner's committed migration history.
|
||||||
|
// Callers must use the same search_path and lock convention for a database.
|
||||||
|
func ApplyPostgreSQLMigrations(ctx context.Context, database *sql.DB, component string, steps []PostgreSQLMigration) error {
|
||||||
|
if strings.TrimSpace(component) == "" {
|
||||||
|
return fmt.Errorf("migration component is required")
|
||||||
|
}
|
||||||
|
for i, step := range steps {
|
||||||
|
if step.Version != i+1 || strings.TrimSpace(step.Name) == "" || len(step.Statements)+len(step.Assertions) == 0 {
|
||||||
|
return fmt.Errorf("invalid PostgreSQL migration sequence for %s", component)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx, err := database.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
||||||
|
if err != nil {
|
||||||
|
return postgresError("migration begin", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
// Stable application-specific key, independent of Go hashes and versions.
|
||||||
|
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1835624306)`); err != nil {
|
||||||
|
return postgresError("migration lock", err)
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migration_steps (
|
||||||
|
component TEXT NOT NULL, version INTEGER NOT NULL, name TEXT NOT NULL,
|
||||||
|
checksum TEXT NOT NULL, applied_at_ms BIGINT NOT NULL,
|
||||||
|
PRIMARY KEY(component,version))`); err != nil {
|
||||||
|
return postgresError("migration ledger", err)
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT version,name,checksum FROM schema_migration_steps WHERE component=$1 ORDER BY version`, component)
|
||||||
|
if err != nil {
|
||||||
|
return postgresError("migration history", err)
|
||||||
|
}
|
||||||
|
applied := 0
|
||||||
|
for rows.Next() {
|
||||||
|
var version int
|
||||||
|
var name, checksum string
|
||||||
|
if err := rows.Scan(&version, &name, &checksum); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return postgresError("migration history", err)
|
||||||
|
}
|
||||||
|
if version != applied+1 || version > len(steps) || steps[version-1].Name != name || postgresMigrationChecksum(steps[version-1]) != checksum {
|
||||||
|
rows.Close()
|
||||||
|
return fmt.Errorf("PostgreSQL migration history mismatch: component=%s version=%d", component, version)
|
||||||
|
}
|
||||||
|
applied++
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
closeErr := rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return postgresError("migration history", err)
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return postgresError("migration history close", closeErr)
|
||||||
|
}
|
||||||
|
for _, step := range steps[applied:] {
|
||||||
|
for i, statement := range step.Statements {
|
||||||
|
if _, err := tx.ExecContext(ctx, statement); err != nil {
|
||||||
|
return postgresError(fmt.Sprintf("migration %s/%d statement %d", component, step.Version, i+1), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migration_steps(component,version,name,checksum,applied_at_ms) VALUES($1,$2,$3,$4,$5)`, component, step.Version, step.Name, postgresMigrationChecksum(step), time.Now().UnixMilli()); err != nil {
|
||||||
|
return postgresError("migration record", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(steps) > 0 {
|
||||||
|
step := steps[len(steps)-1]
|
||||||
|
for i, assertion := range step.Assertions {
|
||||||
|
rows, err := tx.QueryContext(ctx, assertion)
|
||||||
|
if err != nil {
|
||||||
|
return postgresError("schema assertion", err)
|
||||||
|
}
|
||||||
|
violated := rows.Next()
|
||||||
|
err = rows.Err()
|
||||||
|
closeErr := rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return postgresError("schema assertion", err)
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return postgresError("schema assertion close", closeErr)
|
||||||
|
}
|
||||||
|
if violated {
|
||||||
|
return fmt.Errorf("PostgreSQL schema contract %s/%d assertion %d failed", component, step.Version, i+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return postgresError("migration commit", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPostgreSQLConfigurationAndRedaction(t *testing.T) {
|
||||||
|
for _, options := range []PostgreSQLOptions{
|
||||||
|
{}, {DSN: "postgres://test:secret@localhost/db", MaxOpenConns: -1},
|
||||||
|
{DSN: "postgres://test:secret@localhost/db?sslmode=disable"},
|
||||||
|
{DSN: "postgres://test:secret@localhost/db?sslmode=require"},
|
||||||
|
{DSN: "postgres://test:secret@localhost/db?sslmode=prefer"},
|
||||||
|
{DSN: "postgres://test:secret@localhost/db?sslmode=invalid"},
|
||||||
|
} {
|
||||||
|
database, err := OpenPostgreSQL(context.Background(), options)
|
||||||
|
if database != nil || err == nil {
|
||||||
|
t.Fatal("invalid configuration accepted")
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "secret") {
|
||||||
|
t.Fatal("password disclosed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err := postgresError("write", &pgconn.PgError{Code: "23505", Message: "secret", Detail: "private row"})
|
||||||
|
var safe *PostgreSQLError
|
||||||
|
if !errors.As(err, &safe) || safe.SQLState != "23505" || strings.Contains(err.Error(), "secret") {
|
||||||
|
t.Fatal("unsafe error classification")
|
||||||
|
}
|
||||||
|
if !errors.Is(postgresError("read", context.Canceled), context.Canceled) {
|
||||||
|
t.Fatal("cancellation lost")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
database, err := OpenPostgreSQL(ctx, PostgreSQLOptions{DSN: "postgres://test:secret@127.0.0.1:1/db?sslmode=disable", AllowInsecure: true})
|
||||||
|
if database != nil || !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatal("connection cancellation lost")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// These tests create and drop only a random schema. Use a disposable database
|
||||||
|
// and URL DSN, never a production connection. No fixtures contain real events.
|
||||||
|
func postgresTestDatabase(t *testing.T) *sql.DB {
|
||||||
|
t.Helper()
|
||||||
|
dsn := os.Getenv("PAGESWIKI_TEST_POSTGRES_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("set PAGESWIKI_TEST_POSTGRES_DSN to a disposable PostgreSQL URL")
|
||||||
|
}
|
||||||
|
u, err := url.Parse(dsn)
|
||||||
|
if err != nil || (u.Scheme != "postgres" && u.Scheme != "postgresql") {
|
||||||
|
t.Fatal("test DSN must be a PostgreSQL URL")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
root, err := OpenPostgreSQL(ctx, PostgreSQLOptions{DSN: dsn, AllowInsecure: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
schema := "pageswiki_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||||
|
if _, err := root.ExecContext(ctx, `CREATE SCHEMA "`+schema+`"`); err != nil {
|
||||||
|
root.Close()
|
||||||
|
t.Fatal(postgresError("test schema", err))
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := root.ExecContext(cleanup, `DROP SCHEMA "`+schema+`" CASCADE`); err != nil {
|
||||||
|
t.Error(postgresError("test cleanup", err))
|
||||||
|
}
|
||||||
|
root.Close()
|
||||||
|
})
|
||||||
|
query := u.Query()
|
||||||
|
query.Set("search_path", schema)
|
||||||
|
u.RawQuery = query.Encode()
|
||||||
|
database, err := OpenPostgreSQL(ctx, PostgreSQLOptions{DSN: u.String(), AllowInsecure: true, MaxOpenConns: 6})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { database.Close() })
|
||||||
|
return database
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostgreSQLMigrationConcurrencyAndHistory(t *testing.T) {
|
||||||
|
database := postgresTestDatabase(t)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
steps := []PostgreSQLMigration{{Version: 1, Name: "initial", Statements: []string{
|
||||||
|
`CREATE TABLE sample (uuid TEXT PRIMARY KEY, created_at_ms BIGINT NOT NULL)`,
|
||||||
|
`INSERT INTO sample VALUES ('synthetic', 1800000000000)`,
|
||||||
|
}, Assertions: []string{`SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM sample WHERE created_at_ms=1800000000000)`}}}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errs := make(chan error, 6)
|
||||||
|
for i := 0; i < 6; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() { defer wg.Done(); errs <- ApplyPostgreSQLMigrations(ctx, database, "test", steps) }()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(errs)
|
||||||
|
for err := range errs {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := database.QueryRowContext(ctx, `SELECT count(*) FROM sample`).Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatalf("rows=%d error=%v", count, err)
|
||||||
|
}
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "test", nil); err == nil {
|
||||||
|
t.Fatal("downgrade accepted")
|
||||||
|
}
|
||||||
|
changed := append([]PostgreSQLMigration(nil), steps...)
|
||||||
|
changed[0].Name = "changed"
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "test", changed); err == nil {
|
||||||
|
t.Fatal("changed history accepted")
|
||||||
|
}
|
||||||
|
changed = append([]PostgreSQLMigration(nil), steps...)
|
||||||
|
changed[0].Statements = []string{`SELECT 1`}
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "test", changed); err == nil {
|
||||||
|
t.Fatal("changed SQL checksum accepted")
|
||||||
|
}
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "other", []PostgreSQLMigration{{Version: 2, Name: "gap", Statements: []string{`SELECT 1`}}}); err == nil {
|
||||||
|
t.Fatal("version gap accepted")
|
||||||
|
}
|
||||||
|
// Assertions are checked again even when no migrations remain to apply.
|
||||||
|
if _, err := database.ExecContext(ctx, `DELETE FROM sample`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "test", steps); err == nil {
|
||||||
|
t.Fatal("schema assertion skipped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostgreSQLMigrationRollbackAndLockCancellation(t *testing.T) {
|
||||||
|
database := postgresTestDatabase(t)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
broken := []PostgreSQLMigration{{Version: 1, Name: "broken", Statements: []string{`CREATE TABLE partial (id INTEGER)`, `NOT VALID SQL`}}}
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "test", broken); err == nil {
|
||||||
|
t.Fatal("SQL error ignored")
|
||||||
|
}
|
||||||
|
var name sql.NullString
|
||||||
|
if err := database.QueryRowContext(ctx, `SELECT to_regclass('partial')::text`).Scan(&name); err != nil || name.Valid {
|
||||||
|
t.Fatal("DDL not rolled back", err)
|
||||||
|
}
|
||||||
|
if err := database.QueryRowContext(ctx, `SELECT to_regclass('schema_migration_steps')::text`).Scan(&name); err != nil || name.Valid {
|
||||||
|
t.Fatal("ledger not rolled back", err)
|
||||||
|
}
|
||||||
|
broken[0].Statements = broken[0].Statements[:1]
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "test", broken); err != nil {
|
||||||
|
t.Fatal("retry failed", err)
|
||||||
|
}
|
||||||
|
assertionFailure := append(append([]PostgreSQLMigration(nil), broken...), PostgreSQLMigration{
|
||||||
|
Version: 2, Name: "assertion failure", Statements: []string{`CREATE TABLE should_rollback (id INTEGER)`}, Assertions: []string{`SELECT 1`},
|
||||||
|
})
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "test", assertionFailure); err == nil {
|
||||||
|
t.Fatal("assertion failure ignored")
|
||||||
|
}
|
||||||
|
if err := database.QueryRowContext(ctx, `SELECT to_regclass('should_rollback')::text`).Scan(&name); err != nil || name.Valid {
|
||||||
|
t.Fatal("assertion DDL not rolled back", err)
|
||||||
|
}
|
||||||
|
var version int
|
||||||
|
if err := database.QueryRowContext(ctx, `SELECT max(version) FROM schema_migration_steps WHERE component=$1`, "test").Scan(&version); err != nil || version != 1 {
|
||||||
|
t.Fatal("assertion ledger not rolled back", err)
|
||||||
|
}
|
||||||
|
tx, err := database.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1835624306)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waitCtx, stop := context.WithTimeout(ctx, 100*time.Millisecond)
|
||||||
|
defer stop()
|
||||||
|
if err := ApplyPostgreSQLMigrations(waitCtx, database, "test", broken); err == nil {
|
||||||
|
t.Fatal("blocked migration ignored deadline")
|
||||||
|
}
|
||||||
|
if err := tx.Rollback(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := ApplyPostgreSQLMigrations(ctx, database, "test", broken); err != nil {
|
||||||
|
t.Fatal(fmt.Sprintf("lock not released: %v", err))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
// Package documentrefs freezes mutable Asset references without interpreting
|
||||||
|
// ordinary text or code examples. Resolvers must authorize the source Domain.
|
||||||
|
package documentrefs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/net/html"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrUnavailable = errors.New("embedded asset is unavailable")
|
||||||
|
|
||||||
|
type Resolver func(context.Context, string) (string, error)
|
||||||
|
|
||||||
|
// Freeze retains original bytes for unchanged tokens and deduplicates hashes
|
||||||
|
// in appearance order. Repeated addresses resolve only once per payload.
|
||||||
|
func Freeze(ctx context.Context, payload []byte, contentType string, resolve Resolver) ([]byte, []string, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||||
|
if err != nil || !strings.EqualFold(mediaType, "text/html") {
|
||||||
|
return payload, nil, nil
|
||||||
|
}
|
||||||
|
z := html.NewTokenizer(bytes.NewReader(payload))
|
||||||
|
var output bytes.Buffer
|
||||||
|
seen := map[string]bool{}
|
||||||
|
resolved := map[string]string{}
|
||||||
|
var hashes []string
|
||||||
|
lookup := func(address string) (string, error) {
|
||||||
|
if hash := resolved[address]; hash != "" {
|
||||||
|
return hash, nil
|
||||||
|
}
|
||||||
|
if resolve == nil {
|
||||||
|
return "", ErrUnavailable
|
||||||
|
}
|
||||||
|
hash, err := resolve(ctx, address)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(hash) != 64 {
|
||||||
|
return "", fmt.Errorf("%w: %s", ErrUnavailable, address)
|
||||||
|
}
|
||||||
|
if _, err := hex.DecodeString(hash); err != nil {
|
||||||
|
return "", fmt.Errorf("%w: %s", ErrUnavailable, address)
|
||||||
|
}
|
||||||
|
hash = strings.ToLower(hash)
|
||||||
|
resolved[address] = hash
|
||||||
|
if !seen[hash] {
|
||||||
|
seen[hash] = true
|
||||||
|
hashes = append(hashes, hash)
|
||||||
|
}
|
||||||
|
return hash, nil
|
||||||
|
}
|
||||||
|
for {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
typ := z.Next()
|
||||||
|
if typ == html.ErrorToken {
|
||||||
|
if errors.Is(z.Err(), io.EOF) {
|
||||||
|
return output.Bytes(), hashes, nil
|
||||||
|
}
|
||||||
|
return nil, nil, z.Err()
|
||||||
|
}
|
||||||
|
if typ != html.StartTagToken && typ != html.SelfClosingTagToken {
|
||||||
|
output.Write(z.Raw())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Token() may alter the tokenizer buffer. Copy original bytes first.
|
||||||
|
raw := append([]byte(nil), z.Raw()...)
|
||||||
|
token := z.Token()
|
||||||
|
changed := false
|
||||||
|
assetRef := attribute(token.Attr, "asset-ref")
|
||||||
|
legacy := attribute(token.Attr, "immutable-ref")
|
||||||
|
if assetRef == "" && strings.HasPrefix(legacy, "asset:") {
|
||||||
|
assetRef = legacy
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(assetRef, "asset:") {
|
||||||
|
hash, err := lookup(assetRef)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
setAttribute(&token, "asset-ref", assetRef)
|
||||||
|
setAttribute(&token, "immutable-ref", "sha256:"+hash)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
for _, name := range []string{"src", "href", "poster", "data"} {
|
||||||
|
provenance := "data-pageswiki-asset-" + name
|
||||||
|
address := attribute(token.Attr, provenance)
|
||||||
|
if address == "" {
|
||||||
|
candidate := attribute(token.Attr, name)
|
||||||
|
if strings.HasPrefix(candidate, "asset:") {
|
||||||
|
address = candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(address, "asset:") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
hash, err := lookup(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
setAttribute(&token, provenance, address)
|
||||||
|
setAttribute(&token, name, "/_/obj/sha256:"+hash)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if changed {
|
||||||
|
output.WriteString(token.String())
|
||||||
|
} else {
|
||||||
|
output.Write(raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func attribute(attrs []html.Attribute, name string) string {
|
||||||
|
for _, a := range attrs {
|
||||||
|
if strings.EqualFold(a.Key, name) {
|
||||||
|
return strings.TrimSpace(a.Val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
func setAttribute(token *html.Token, name, value string) {
|
||||||
|
for i := range token.Attr {
|
||||||
|
if strings.EqualFold(token.Attr[i].Key, name) {
|
||||||
|
token.Attr[i].Key = name
|
||||||
|
token.Attr[i].Val = value
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
token.Attr = append(token.Attr, html.Attribute{Key: name, Val: value})
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package documentrefs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFreezePreservesUnchangedHTML(t *testing.T) {
|
||||||
|
body := `<!DOCTYPE html><!-- sample --><DIV class='A' title="&">日本語<code><img src="asset:image:example"></code><script>const x="asset:image:sample";</script><a HREF='/plain?a=1&b=2'>Link</a></DIV>`
|
||||||
|
got, refs, err := Freeze(context.Background(), []byte(body), "text/html; charset=utf-8", func(context.Context, string) (string, error) { t.Fatal("ordinary text resolved"); return "", nil })
|
||||||
|
if err != nil || string(got) != body || len(refs) != 0 {
|
||||||
|
t.Fatal("unchanged HTML lost bytes", err, string(got))
|
||||||
|
}
|
||||||
|
for _, mime := range []string{"text/plain", "application/octet-stream", "text/html-not-really"} {
|
||||||
|
got, refs, err := Freeze(context.Background(), []byte(`<img src="asset:image:sample">`), mime, nil)
|
||||||
|
if err != nil || len(refs) != 0 || string(got) != `<img src="asset:image:sample">` {
|
||||||
|
t.Fatal("non-HTML modified", mime, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFreezeDeduplicatesAndFollowsProvenance(t *testing.T) {
|
||||||
|
hash := strings.Repeat("a", 64)
|
||||||
|
calls := 0
|
||||||
|
resolve := func(context.Context, string) (string, error) { calls++; return hash, nil }
|
||||||
|
body := `<img src="asset:image:a"><video poster="asset:image:a"></video><object data="asset:image:b"></object><a href="asset:image:a">a</a><embedded-object immutable-ref="asset:image:a"></embedded-object>`
|
||||||
|
got, refs, err := Freeze(context.Background(), []byte(body), "text/html", resolve)
|
||||||
|
if err != nil || len(refs) != 1 || refs[0] != hash || calls != 2 {
|
||||||
|
t.Fatal("deduplication", err, refs, calls)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(got), `immutable-ref="sha256:`+hash+`"`) || !strings.Contains(string(got), `data-pageswiki-asset-src="asset:image:a"`) {
|
||||||
|
t.Fatal("provenance missing")
|
||||||
|
}
|
||||||
|
hash = strings.Repeat("b", 64)
|
||||||
|
calls = 0
|
||||||
|
updated, refs, err := Freeze(context.Background(), got, "text/html", resolve)
|
||||||
|
if err != nil || len(refs) != 1 || refs[0] != hash || calls != 2 || strings.Contains(string(updated), strings.Repeat("a", 64)) {
|
||||||
|
t.Fatal("resave did not follow HEAD", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFreezeRejectsMissingInvalidAndCanceled(t *testing.T) {
|
||||||
|
for _, hash := range []string{"", strings.Repeat("x", 64)} {
|
||||||
|
if _, _, err := Freeze(context.Background(), []byte(`<img src="asset:image:a">`), "text/html", func(context.Context, string) (string, error) { return hash, nil }); !errors.Is(err, ErrUnavailable) {
|
||||||
|
t.Fatal("invalid hash accepted", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if _, _, err := Freeze(ctx, []byte("text"), "text/plain", nil); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatal("cancellation ignored", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,12 @@ type Runner struct {
|
|||||||
registry *Registry
|
registry *Registry
|
||||||
opts RunnerOptions
|
opts RunnerOptions
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
|
stopping bool
|
||||||
|
stopCtx context.Context
|
||||||
|
cancel context.CancelFunc
|
||||||
|
workers sync.WaitGroup
|
||||||
|
stopOnce sync.Once
|
||||||
|
done chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRunner(queue Queue, registry *Registry, opts RunnerOptions) *Runner {
|
func NewRunner(queue Queue, registry *Registry, opts RunnerOptions) *Runner {
|
||||||
@@ -41,7 +47,30 @@ func NewRunner(queue Queue, registry *Registry, opts RunnerOptions) *Runner {
|
|||||||
if opts.Active == nil {
|
if opts.Active == nil {
|
||||||
opts.Active = new(atomic.Int64)
|
opts.Active = new(atomic.Int64)
|
||||||
}
|
}
|
||||||
return &Runner{queue: queue, registry: registry, opts: opts}
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
return &Runner{queue: queue, registry: registry, opts: opts, stopCtx: ctx, cancel: cancel, done: make(chan struct{})}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop closes admission permanently, cancels handlers and waits for persisted
|
||||||
|
// completions. A timeout does not mean workers have exited: callers must keep
|
||||||
|
// ownership/database resources alive and may call Stop again to await them.
|
||||||
|
func (r *Runner) Stop(ctx context.Context) error {
|
||||||
|
r.stopOnce.Do(func() {
|
||||||
|
r.cancel()
|
||||||
|
go func() {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.stopping = true
|
||||||
|
r.mu.Unlock()
|
||||||
|
r.workers.Wait()
|
||||||
|
close(r.done)
|
||||||
|
}()
|
||||||
|
})
|
||||||
|
select {
|
||||||
|
case <-r.done:
|
||||||
|
return nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Runner) report(stage string, job *Job, err error) {
|
func (r *Runner) report(stage string, job *Job, err error) {
|
||||||
@@ -57,7 +86,10 @@ func (r *Runner) Running() int64 { return r.opts.Active.Load() }
|
|||||||
func (r *Runner) Dispatch(ctx context.Context) {
|
func (r *Runner) Dispatch(ctx context.Context) {
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
defer r.mu.Unlock()
|
defer r.mu.Unlock()
|
||||||
for n := 0; n < 32 && ctx.Err() == nil; n++ {
|
if r.stopping || r.stopCtx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for n := 0; n < 32 && ctx.Err() == nil && r.stopCtx.Err() == nil; n++ {
|
||||||
settings, err := r.queue.Settings(ctx)
|
settings, err := r.queue.Settings(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
r.report("settings", nil, err)
|
r.report("settings", nil, err)
|
||||||
@@ -81,7 +113,15 @@ func (r *Runner) Dispatch(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
r.opts.Active.Add(1)
|
r.opts.Active.Add(1)
|
||||||
r.report("start-log", job, r.queue.Started(ctx, job))
|
r.report("start-log", job, r.queue.Started(ctx, job))
|
||||||
go r.execute(ctx, job)
|
workerCtx, cancel := context.WithCancel(ctx)
|
||||||
|
stop := context.AfterFunc(r.stopCtx, cancel)
|
||||||
|
r.workers.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer r.workers.Done()
|
||||||
|
defer cancel()
|
||||||
|
defer stop()
|
||||||
|
r.execute(workerCtx, job)
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,53 @@ type finishedJob struct {
|
|||||||
err error
|
err error
|
||||||
at time.Time
|
at time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRunnerStopWaitsAndClosesAdmission(t *testing.T) {
|
||||||
|
q := newFakeQueue(1)
|
||||||
|
reg := &Registry{}
|
||||||
|
started := make(chan struct{})
|
||||||
|
cancelled := make(chan struct{})
|
||||||
|
exit := make(chan struct{})
|
||||||
|
if err := reg.Register("synthetic", func(ctx context.Context, _ *Job) error {
|
||||||
|
close(started)
|
||||||
|
<-ctx.Done()
|
||||||
|
close(cancelled)
|
||||||
|
<-exit // simulate cleanup that cannot be interrupted
|
||||||
|
return ctx.Err()
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := NewRunner(q, reg, RunnerOptions{})
|
||||||
|
r.Dispatch(context.Background())
|
||||||
|
receive(t, started)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if err := r.Stop(ctx); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
receive(t, cancelled)
|
||||||
|
if r.Running() != 1 {
|
||||||
|
t.Fatal("worker exited before cleanup")
|
||||||
|
}
|
||||||
|
r.Dispatch(context.Background())
|
||||||
|
if q.claimed != 1 {
|
||||||
|
t.Fatal("admission remained open")
|
||||||
|
}
|
||||||
|
close(exit)
|
||||||
|
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := r.Stop(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
receive(t, q.finished)
|
||||||
|
if r.Running() != 0 {
|
||||||
|
t.Fatal("worker slot retained after stop")
|
||||||
|
}
|
||||||
|
if err := r.Stop(ctx); err != nil {
|
||||||
|
t.Fatal("idempotent stop", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type fakeQueue struct {
|
type fakeQueue struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
settings Settings
|
settings Settings
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Job struct {
|
type Job struct {
|
||||||
|
// ClaimToken fences native database completion; never expose it to clients.
|
||||||
|
ClaimToken string `json:"-"`
|
||||||
UUID string `json:"uuid"`
|
UUID string `json:"uuid"`
|
||||||
EventUUID string `json:"event_uuid,omitempty"`
|
EventUUID string `json:"event_uuid,omitempty"`
|
||||||
Type string `json:"event_type"`
|
Type string `json:"event_type"`
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ type Manifest struct {
|
|||||||
|
|
||||||
func Catalog() []Manifest {
|
func Catalog() []Manifest {
|
||||||
return []Manifest{
|
return []Manifest{
|
||||||
|
{ID: "viewer.slides", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "slides.title", DescriptionKey: "slides.help", Capabilities: []string{"path.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "client-compute+bounded-read"},
|
||||||
{ID: "viewer.gecko", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "feeds.gecko", DescriptionKey: "feeds.gecko_help", Capabilities: []string{"feeds.own.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: false, ResourceClass: "client-compute+relay-network"},
|
{ID: "viewer.gecko", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "feeds.gecko", DescriptionKey: "feeds.gecko_help", Capabilities: []string{"feeds.own.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: false, ResourceClass: "client-compute+relay-network"},
|
||||||
{ID: "organizer.feeds", APIVersion: 1, Version: "0.1.0", Kind: "feeds", Scope: "domain", NameKey: "feeds.title", DescriptionKey: "feeds.help", Capabilities: []string{"feeds.own.read", "feeds.own.write"}, Events: []string{"feed.source.sync"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "background+network+index"},
|
{ID: "organizer.feeds", APIVersion: 1, Version: "0.1.0", Kind: "feeds", Scope: "domain", NameKey: "feeds.title", DescriptionKey: "feeds.help", Capabilities: []string{"feeds.own.read", "feeds.own.write"}, Events: []string{"feed.source.sync"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "background+network+index"},
|
||||||
{ID: "organizer.contacts", APIVersion: 1, Version: "0.2.0", Kind: "contacts", Scope: "domain", NameKey: "contacts.title", DescriptionKey: "contacts.help", Capabilities: []string{"contacts.own.read", "contacts.own.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
{ID: "organizer.contacts", APIVersion: 1, Version: "0.2.0", Kind: "contacts", Scope: "domain", NameKey: "contacts.title", DescriptionKey: "contacts.help", Capabilities: []string{"contacts.own.read", "contacts.own.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package geckorelay
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
)
|
||||||
|
|
||||||
|
const DistributionPrefix = "/distribution/v0.0.1/"
|
||||||
|
|
||||||
|
// Updated only after the reproducible source/notice bundle has been reviewed.
|
||||||
|
const DistributionManifestSHA256 = "84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381"
|
||||||
|
|
||||||
|
type DistributionFile struct {
|
||||||
|
File string `json:"file"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var distributionName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,150}$`)
|
||||||
|
|
||||||
|
func VerifyDistribution(dir string) (map[string]DistributionFile, error) {
|
||||||
|
return verifyDistribution(dir, DistributionManifestSHA256)
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyDistribution(dir, expected string) (map[string]DistributionFile, error) {
|
||||||
|
path := filepath.Join(dir, "manifest.json")
|
||||||
|
info, err := os.Lstat(path)
|
||||||
|
if err != nil || !info.Mode().IsRegular() || info.Size() > 1<<20 {
|
||||||
|
return nil, fmt.Errorf("Gecko distribution manifest missing or invalid")
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256(raw)
|
||||||
|
if hex.EncodeToString(sum[:]) != expected {
|
||||||
|
return nil, fmt.Errorf("Gecko distribution manifest checksum mismatch")
|
||||||
|
}
|
||||||
|
var manifest struct {
|
||||||
|
Format string `json:"format"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
Files []DistributionFile `json:"files"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(raw, &manifest) != nil || manifest.Format != "pageswiki.gecko-distribution.v1" || manifest.Version != "v0.0.1" || len(manifest.Files) > 512 {
|
||||||
|
return nil, fmt.Errorf("invalid Gecko distribution format")
|
||||||
|
}
|
||||||
|
files := map[string]DistributionFile{}
|
||||||
|
for _, entry := range manifest.Files {
|
||||||
|
if !distributionName.MatchString(entry.File) || entry.File == "manifest.json" || entry.Size < 1 || entry.Size > 2<<30 || len(entry.SHA256) != 64 {
|
||||||
|
return nil, fmt.Errorf("invalid distribution entry")
|
||||||
|
}
|
||||||
|
if _, exists := files[entry.File]; exists {
|
||||||
|
return nil, fmt.Errorf("duplicate distribution entry")
|
||||||
|
}
|
||||||
|
info, err := os.Lstat(filepath.Join(dir, entry.File))
|
||||||
|
if err != nil || !info.Mode().IsRegular() || info.Size() != entry.Size {
|
||||||
|
return nil, fmt.Errorf("distribution file missing or invalid: %s", entry.File)
|
||||||
|
}
|
||||||
|
file, err := os.Open(filepath.Join(dir, entry.File))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
hash := sha256.New()
|
||||||
|
_, err = io.Copy(hash, io.LimitReader(file, entry.Size+1))
|
||||||
|
file.Close()
|
||||||
|
if err != nil || hex.EncodeToString(hash.Sum(nil)) != entry.SHA256 {
|
||||||
|
return nil, fmt.Errorf("distribution file checksum mismatch: %s", entry.File)
|
||||||
|
}
|
||||||
|
files[entry.File] = entry
|
||||||
|
}
|
||||||
|
for _, name := range []string{"index.html", "README.txt", "gecko.js", "gecko.wasm.zst", "firefox.tar.gz", "firefox.tar.gz.notices.txt", "wrapper.tar.gz", "wrapper-MPL.txt", "emscripten.tar.gz", "emscripten.tar.gz.notices.txt", "rust-src.tar.xz", "rust-src.tar.xz.notices.txt", "zstddec.tgz", "zstddec.tgz.notices.txt", "NotoSansCJKjp-Regular.otf", "NotoSansCJK-LICENSE.txt"} {
|
||||||
|
if _, ok := files[name]; !ok {
|
||||||
|
return nil, fmt.Errorf("distribution incomplete: %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files["manifest.json"] = DistributionFile{File: "manifest.json", SHA256: expected, Size: int64(len(raw)), Kind: "manifest"}
|
||||||
|
return files, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package geckorelay
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDistribution(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if _, err := VerifyDistribution(dir); err == nil {
|
||||||
|
t.Fatal("missing distribution accepted")
|
||||||
|
}
|
||||||
|
names := []string{"index.html", "README.txt", "gecko.js", "gecko.wasm.zst", "firefox.tar.gz", "firefox.tar.gz.notices.txt", "wrapper.tar.gz", "wrapper-MPL.txt", "emscripten.tar.gz", "emscripten.tar.gz.notices.txt", "rust-src.tar.xz", "rust-src.tar.xz.notices.txt", "zstddec.tgz", "zstddec.tgz.notices.txt", "NotoSansCJKjp-Regular.otf", "NotoSansCJK-LICENSE.txt"}
|
||||||
|
content := []byte("synthetic source and notice")
|
||||||
|
hash := sha256.Sum256(content)
|
||||||
|
var entries []DistributionFile
|
||||||
|
for _, name := range names {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), content, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
entries = append(entries, DistributionFile{File: name, Size: int64(len(content)), SHA256: hex.EncodeToString(hash[:])})
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(map[string]any{"format": "pageswiki.gecko-distribution.v1", "version": "v0.0.1", "files": entries})
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), raw, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256(raw)
|
||||||
|
want := hex.EncodeToString(sum[:])
|
||||||
|
files, err := verifyDistribution(dir, want)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
relay, _ := New(testKey, dir)
|
||||||
|
relay.Distribution = files
|
||||||
|
for _, name := range []string{"index.html", "firefox.tar.gz", "manifest.json", "unknown", "../manifest.json"} {
|
||||||
|
req := httptest.NewRequest("GET", DistributionPrefix+name, nil)
|
||||||
|
req.Header.Set(GrantHeader, Sign(testKey, Grant{Subject: "test:user", Nonce: "download-test-0123456789", Expires: time.Now().Add(30 * time.Second).Unix()}))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
relay.ServeHTTP(rec, req)
|
||||||
|
expected := 200
|
||||||
|
if strings.Contains(name, "unknown") || strings.Contains(name, "../") {
|
||||||
|
expected = 404
|
||||||
|
}
|
||||||
|
if rec.Code != expected {
|
||||||
|
t.Fatalf("%s: %d", name, rec.Code)
|
||||||
|
}
|
||||||
|
if expected == 200 && rec.Header().Get("ETag") == "" {
|
||||||
|
t.Fatal("no ETag")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "README.txt"), []byte("tampered"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := verifyDistribution(dir, want); err == nil {
|
||||||
|
t.Fatal("tampered notice accepted")
|
||||||
|
}
|
||||||
|
if err := os.Remove(filepath.Join(dir, "README.txt")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(filepath.Join(dir, "gecko.js"), filepath.Join(dir, "README.txt")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := verifyDistribution(dir, want); err == nil {
|
||||||
|
t.Fatal("symlink accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDistributionRealBundle(t *testing.T) {
|
||||||
|
dir := os.Getenv("PAGESWIKI_GECKO_TEST_BUNDLE")
|
||||||
|
if dir == "" {
|
||||||
|
t.Skip("opt-in complete distribution")
|
||||||
|
}
|
||||||
|
if _, err := VerifyDistribution(dir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -28,6 +29,8 @@ const (
|
|||||||
|
|
||||||
type Relay struct {
|
type Relay struct {
|
||||||
Key, Assets string
|
Key, Assets string
|
||||||
|
Distribution map[string]DistributionFile
|
||||||
|
downloads chan struct{}
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
active map[string]bool
|
active map[string]bool
|
||||||
used map[string]int64
|
used map[string]int64
|
||||||
@@ -40,7 +43,7 @@ func New(key, assets string) (*Relay, error) {
|
|||||||
if len(key) < 32 {
|
if len(key) < 32 {
|
||||||
return nil, errors.New("relay key must contain at least 32 bytes")
|
return nil, errors.New("relay key must contain at least 32 bytes")
|
||||||
}
|
}
|
||||||
r := &Relay{Key: key, Assets: assets, active: map[string]bool{}, used: map[string]int64{}}
|
r := &Relay{Key: key, Assets: assets, active: map[string]bool{}, used: map[string]int64{}, downloads: make(chan struct{}, 2)}
|
||||||
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
||||||
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -72,6 +75,47 @@ func (r *Relay) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|||||||
json.NewEncoder(w).Encode(map[string]any{"active_sessions": active, "received_bytes": r.rx.Load(), "sent_bytes": r.tx.Load(), "rejected": r.rejected.Load(), "profile": "tcp-80-443", "max_sessions": 4, "max_streams": maxStreams, "bytes_per_second": bytesPerSecond, "max_session_bytes": maxBytes})
|
json.NewEncoder(w).Encode(map[string]any{"active_sessions": active, "received_bytes": r.rx.Load(), "sent_bytes": r.tx.Load(), "rejected": r.rejected.Load(), "profile": "tcp-80-443", "max_sessions": 4, "max_streams": maxStreams, "bytes_per_second": bytesPerSecond, "max_session_bytes": maxBytes})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if strings.HasPrefix(req.URL.Path, DistributionPrefix) {
|
||||||
|
name := strings.TrimPrefix(req.URL.Path, DistributionPrefix)
|
||||||
|
entry, ok := r.Distribution[name]
|
||||||
|
if !ok {
|
||||||
|
http.NotFound(w, req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case r.downloads <- struct{}{}:
|
||||||
|
defer func() { <-r.downloads }()
|
||||||
|
default:
|
||||||
|
http.Error(w, "download limit", 429)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("ETag", `"`+entry.SHA256+`"`)
|
||||||
|
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
||||||
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
w.Header().Set("Content-Security-Policy", "default-src 'none'; base-uri 'none'; frame-ancestors 'self'")
|
||||||
|
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||||
|
switch {
|
||||||
|
case name == "index.html":
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
case strings.HasSuffix(name, ".txt"):
|
||||||
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
|
case name == "manifest.json":
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
default:
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
|
||||||
|
}
|
||||||
|
// ServeContent avoids ServeFile's /index.html -> ./ redirect, which
|
||||||
|
// would escape the explicit file allowlist at the proxy boundary.
|
||||||
|
file, err := os.Open(filepath.Join(r.Assets, name))
|
||||||
|
if err != nil {
|
||||||
|
http.NotFound(w, req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
http.ServeContent(w, req, name, time.Time{}, file)
|
||||||
|
return
|
||||||
|
}
|
||||||
if req.URL.Path == AssetsPrefix+"gecko.js" || req.URL.Path == AssetsPrefix+"gecko.wasm.zst" {
|
if req.URL.Path == AssetsPrefix+"gecko.js" || req.URL.Path == AssetsPrefix+"gecko.wasm.zst" {
|
||||||
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
|
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||||
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package grammaratur
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -12,17 +14,93 @@ import (
|
|||||||
|
|
||||||
// HTMLToMarkdownAuthoring keeps source HTML when conversion loses structure,
|
// HTMLToMarkdownAuthoring keeps source HTML when conversion loses structure,
|
||||||
// attributes, comments or text. This is not a sanitization boundary.
|
// attributes, comments or text. This is not a sanitization boundary.
|
||||||
|
var nestedListGap = regexp.MustCompile(`\n[\t ]*\n([\t ]+(?:[-+*]|[0-9]+\.) )`)
|
||||||
|
|
||||||
|
func authoringMarkdown(source string) (string, error) {
|
||||||
|
md, err := HTMLToMarkdown(source)
|
||||||
|
if err != nil {
|
||||||
|
return md, err
|
||||||
|
}
|
||||||
|
// The converter inserts a loose-list gap before nested lists. Only accept
|
||||||
|
// tightening when the resulting DOM matches; code and real paragraphs stay protected.
|
||||||
|
tight := nestedListGap.ReplaceAllString(md, "\n$1")
|
||||||
|
if tight != md && htmlStructure(source) == htmlStructure(MarkdownToHTML(tight)) {
|
||||||
|
return tight, nil
|
||||||
|
}
|
||||||
|
return md, nil
|
||||||
|
}
|
||||||
|
|
||||||
func HTMLToMarkdownAuthoring(source string) (string, error) {
|
func HTMLToMarkdownAuthoring(source string) (string, error) {
|
||||||
converted, err := HTMLToMarkdown(source)
|
converted, err := authoringMarkdown(source)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if htmlStructure(source) != htmlStructure(MarkdownToHTML(converted)) {
|
if htmlStructure(source) != htmlStructure(MarkdownToHTML(converted)) {
|
||||||
return rawHTMLBlock(source), nil
|
// Protect only the blocks which cannot round-trip. One custom component
|
||||||
|
// must not turn the headings, lists and paragraphs around it into HTML.
|
||||||
|
blocks, ok := authoringBlocks(source)
|
||||||
|
if !ok {
|
||||||
|
return rawHTMLBlock(source), nil
|
||||||
|
}
|
||||||
|
var parts []string
|
||||||
|
for _, raw := range blocks {
|
||||||
|
if strings.TrimSpace(raw) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
md, e := authoringMarkdown(raw)
|
||||||
|
if e != nil || htmlStructure(raw) != htmlStructure(MarkdownToHTML(md)) {
|
||||||
|
md = rawHTMLBlock(raw)
|
||||||
|
}
|
||||||
|
parts = append(parts, md)
|
||||||
|
}
|
||||||
|
mixed := strings.Join(parts, "\n\n")
|
||||||
|
// Includes head content, comments outside body and fragment edge cases.
|
||||||
|
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(mixed)) {
|
||||||
|
return rawHTMLBlock(source), nil
|
||||||
|
}
|
||||||
|
return mixed, nil
|
||||||
}
|
}
|
||||||
return converted, nil
|
return converted, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Token boundaries retain the exact source of protected components (including
|
||||||
|
// attribute quoting and void-element syntax). Never serialize the parsed DOM
|
||||||
|
// back over their source. Malformed/implicit nesting uses whole-document fallback.
|
||||||
|
func authoringBlocks(source string) ([]string, bool) {
|
||||||
|
z := html.NewTokenizer(strings.NewReader(source))
|
||||||
|
var stack, blocks []string
|
||||||
|
start, offset := 0, 0
|
||||||
|
for {
|
||||||
|
kind := z.Next()
|
||||||
|
if kind == html.ErrorToken {
|
||||||
|
return blocks, z.Err() == io.EOF && len(stack) == 0 && offset == len(source)
|
||||||
|
}
|
||||||
|
offset += len(z.Raw())
|
||||||
|
switch kind {
|
||||||
|
case html.StartTagToken:
|
||||||
|
name, _ := z.TagName()
|
||||||
|
switch string(name) {
|
||||||
|
case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr":
|
||||||
|
default:
|
||||||
|
stack = append(stack, string(name))
|
||||||
|
}
|
||||||
|
case html.EndTagToken:
|
||||||
|
name, _ := z.TagName()
|
||||||
|
if len(stack) == 0 || stack[len(stack)-1] != string(name) {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
stack = stack[:len(stack)-1]
|
||||||
|
}
|
||||||
|
if len(stack) == 0 {
|
||||||
|
blocks = append(blocks, source[start:offset])
|
||||||
|
start = offset
|
||||||
|
if len(blocks) > 1024 {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// {=html} is an explicit authoring fence, not an ordinary code sample. The
|
// {=html} is an explicit authoring fence, not an ordinary code sample. The
|
||||||
// closing delimiter is longer than any run in the source, so arbitrary HTML
|
// closing delimiter is longer than any run in the source, so arbitrary HTML
|
||||||
// (including Markdown examples) cannot accidentally terminate it.
|
// (including Markdown examples) cannot accidentally terminate it.
|
||||||
@@ -110,6 +188,28 @@ func htmlStructure(source string) string {
|
|||||||
literal = literal || n.Data == "pre" || n.Data == "code" || n.Data == "script" || n.Data == "style"
|
literal = literal || n.Data == "pre" || n.Data == "code" || n.Data == "script" || n.Data == "style"
|
||||||
data := n.Data
|
data := n.Data
|
||||||
if n.Type == html.TextNode && !literal {
|
if n.Type == html.TextNode && !literal {
|
||||||
|
// Formatting whitespace beside a nested block is not an inline word
|
||||||
|
// separator. Keep all whitespace between inline siblings significant.
|
||||||
|
if n.Parent != nil && n.Parent.Data == "li" {
|
||||||
|
isList := func(x *html.Node) bool {
|
||||||
|
return x != nil && x.Type == html.ElementNode && (x.Data == "ul" || x.Data == "ol")
|
||||||
|
}
|
||||||
|
if isList(n.NextSibling) {
|
||||||
|
data = strings.TrimRight(data, " \t\r\n")
|
||||||
|
}
|
||||||
|
if isList(n.PrevSibling) {
|
||||||
|
data = strings.TrimLeft(data, " \t\r\n")
|
||||||
|
}
|
||||||
|
if data == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(data) == "" && n.Parent != nil {
|
||||||
|
switch n.Parent.Data {
|
||||||
|
case "ul", "ol", "table", "thead", "tbody", "tfoot", "tr":
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
if strings.TrimSpace(data) == "" && (n.Parent == nil || n.Parent.Data == "body" || n.Parent.Data == "html") {
|
if strings.TrimSpace(data) == "" && (n.Parent == nil || n.Parent.Data == "body" || n.Parent.Data == "html") {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,3 +65,19 @@ func TestAuthoringWhitespaceComparisonIsConservative(t *testing.T) {
|
|||||||
t.Fatal("word boundaries ignored")
|
t.Fatal("word boundaries ignored")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAuthoringPartialMarkdownRecovery(t *testing.T) {
|
||||||
|
source := `<h1>Title</h1><p>Some <strong>bold</strong> text.</p><figure data-x="keep"><img src="/image"><figcaption>Caption</figcaption></figure><ul><li>First</li><li>Second</li></ul>`
|
||||||
|
md, err := HTMLToMarkdownAuthoring(source)
|
||||||
|
if err != nil || !strings.HasPrefix(md, "# Title") || !strings.Contains(md, "**bold**") || strings.Count(md, "{=html}") != 1 || !strings.Contains(md, "- First") {
|
||||||
|
t.Fatalf("markdown not recovered: %q %v", md, err)
|
||||||
|
}
|
||||||
|
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
|
||||||
|
t.Fatal("HTML lost during partial conversion")
|
||||||
|
}
|
||||||
|
protected := `<figure data-x='original'><img src=/image><figcaption>Caption</figcaption></figure>`
|
||||||
|
md, err = HTMLToMarkdownAuthoring("<h1>Title</h1>" + protected + "<p>Tail</p>")
|
||||||
|
if err != nil || !strings.Contains(MarkdownAuthoringHTML(md), protected) || !strings.HasPrefix(md, "# Title") {
|
||||||
|
t.Fatalf("protected bytes changed: %q %v", md, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package grammaratur
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAuthoringNestedLists(t *testing.T) {
|
||||||
|
for _, source := range []string{
|
||||||
|
"<ul><li>Parent<ul><li>Child</li></ul></li></ul>",
|
||||||
|
"<ul>\n<li>Parent\n<ul>\n<li>Child</li>\n</ul>\n</li>\n</ul>",
|
||||||
|
"<ul><li>Parent<ul><li>Child<ul><li>Grandchild</li></ul></li></ul></li><li>Sibling</li></ul>",
|
||||||
|
"<ol><li>Parent<ul><li>Child</li></ul></li></ol>",
|
||||||
|
"<ul><li><strong>Parent</strong><ul><li>Child</li></ul></li></ul>",
|
||||||
|
} {
|
||||||
|
md, err := HTMLToMarkdownAuthoring(source)
|
||||||
|
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
|
||||||
|
t.Errorf("list structure changed: %q", md)
|
||||||
|
}
|
||||||
|
if err != nil || strings.Contains(md, "{=html}") {
|
||||||
|
plain, _ := HTMLToMarkdown(source)
|
||||||
|
t.Errorf("source=%q md=%q plain=%q rendered=%q err=%v", source, md, plain, MarkdownToHTML(plain), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthoringNestedListPreservesAttributes(t *testing.T) {
|
||||||
|
source := `<ul><li data-custom="keep">Parent<ul><li>Child</li></ul></li></ul>`
|
||||||
|
md, err := HTMLToMarkdownAuthoring(source)
|
||||||
|
if err != nil || MarkdownAuthoringHTML(md) != source {
|
||||||
|
t.Fatalf("protected list changed: %q %v", md, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -227,4 +227,9 @@ func textMediaType(descriptor Descriptor) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Catalog returns a copy; callers cannot reorder or disable the shared registry.
|
// Catalog returns a copy; callers cannot reorder or disable the shared registry.
|
||||||
func Catalog() []Adapter { return append([]Adapter(nil), projectionAdapters...) }
|
func Catalog() []Adapter {
|
||||||
|
items := append([]Adapter(nil), projectionAdapters...)
|
||||||
|
// Explicitly selected projection. It must not replace normal HTML/text
|
||||||
|
// viewing in the automatic MIME classifier.
|
||||||
|
return append(items, Adapter{ID: "reveal", Kind: "slides", Delivery: DeliveryRawFrame, Match: func(Descriptor) bool { return false }})
|
||||||
|
}
|
||||||
@@ -47,7 +47,7 @@ func TestAdapterCatalogIsCopyAndConcurrent(t *testing.T) {
|
|||||||
for _, a := range catalog {
|
for _, a := range catalog {
|
||||||
ids = append(ids, a.ID)
|
ids = append(ids, a.ID)
|
||||||
}
|
}
|
||||||
if strings.Join(ids, ",") != "html,excalidraw,csv,archive,debian-package,eml,pe,json,text,image,audio,video,pdf,download" {
|
if strings.Join(ids, ",") != "html,excalidraw,csv,archive,debian-package,eml,pe,json,text,image,audio,video,pdf,download,reveal" {
|
||||||
t.Fatal("catalog order changed", ids)
|
t.Fatal("catalog order changed", ids)
|
||||||
}
|
}
|
||||||
catalog[0].ID = "corrupt"
|
catalog[0].ID = "corrupt"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -36,6 +37,14 @@ type citySearchCandidate struct {
|
|||||||
// Scope selects a locality's own boundary, not an ancestor of the scope. Every
|
// Scope selects a locality's own boundary, not an ancestor of the scope. Every
|
||||||
// boundary in its parent chain must be readable before the result is exposed.
|
// boundary in its parent chain must be readable before the result is exposed.
|
||||||
func (s *SQLite) SearchCityInDomain(parent context.Context, domainUUID, scope, query string, limit int, allowed func(string) bool, options SearchOptions) (found []CitySearchResult, searchErr error) {
|
func (s *SQLite) SearchCityInDomain(parent context.Context, domainUUID, scope, query string, limit int, allowed func(string) bool, options SearchOptions) (found []CitySearchResult, searchErr error) {
|
||||||
|
return searchCity(s.db, false, parent, domainUUID, scope, query, limit, allowed, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQL) SearchCityInDomain(parent context.Context, domainUUID, scope, query string, limit int, allowed func(string) bool, options SearchOptions) ([]CitySearchResult, error) {
|
||||||
|
return searchCity(s.db, true, parent, domainUUID, scope, query, limit, allowed, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
func searchCity(database *sql.DB, native bool, parent context.Context, domainUUID, scope, query string, limit int, allowed func(string) bool, options SearchOptions) (found []CitySearchResult, searchErr error) {
|
||||||
if err := options.Validate(); err != nil {
|
if err := options.Validate(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -58,7 +67,7 @@ func (s *SQLite) SearchCityInDomain(parent context.Context, domainUUID, scope, q
|
|||||||
searchErr = ctx.Err()
|
searchErr = ctx.Err()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
tx, err := database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -70,22 +79,35 @@ func (s *SQLite) SearchCityInDomain(parent context.Context, domainUUID, scope, q
|
|||||||
sql.Named("prefix", prefix), sql.Named("upper", upper),
|
sql.Named("prefix", prefix), sql.Named("upper", upper),
|
||||||
sql.Named("query", query), sql.Named("limit", CitySearchCandidateLimit),
|
sql.Named("query", query), sql.Named("limit", CitySearchCandidateLimit),
|
||||||
}
|
}
|
||||||
|
if native {
|
||||||
|
args = []any{domainUUID, scope, prefix, upper, query, CitySearchCandidateLimit}
|
||||||
|
}
|
||||||
dateColumn := "n.updated_at_ms"
|
dateColumn := "n.updated_at_ms"
|
||||||
if options.DateField == "created" {
|
if options.DateField == "created" {
|
||||||
dateColumn = "n.created_at_ms"
|
dateColumn = "n.created_at_ms"
|
||||||
}
|
}
|
||||||
dateWhere := ""
|
dateWhere := ""
|
||||||
if options.FromMS != nil {
|
if options.FromMS != nil {
|
||||||
dateWhere += " AND " + dateColumn + ">=:from_ms"
|
if native {
|
||||||
args = append(args, sql.Named("from_ms", *options.FromMS))
|
args = append(args, *options.FromMS)
|
||||||
|
dateWhere += " AND " + dateColumn + ">=" + fmt.Sprintf("$%d", len(args))
|
||||||
|
} else {
|
||||||
|
dateWhere += " AND " + dateColumn + ">=:from_ms"
|
||||||
|
args = append(args, sql.Named("from_ms", *options.FromMS))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if options.BeforeMS != nil {
|
if options.BeforeMS != nil {
|
||||||
dateWhere += " AND " + dateColumn + "<:before_ms"
|
if native {
|
||||||
args = append(args, sql.Named("before_ms", *options.BeforeMS))
|
args = append(args, *options.BeforeMS)
|
||||||
|
dateWhere += " AND " + dateColumn + "<" + fmt.Sprintf("$%d", len(args))
|
||||||
|
} else {
|
||||||
|
dateWhere += " AND " + dateColumn + "<:before_ms"
|
||||||
|
args = append(args, sql.Named("before_ms", *options.BeforeMS))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
candidates := make([]citySearchCandidate, 0)
|
candidates := make([]citySearchCandidate, 0)
|
||||||
for _, kind := range []string{"quartier", "street", "spot"} {
|
for _, kind := range []string{"quartier", "street", "spot"} {
|
||||||
rows, err := tx.QueryContext(ctx, citySearchSQL(kind, dateWhere), args...)
|
rows, err := tx.QueryContext(ctx, citySearchDialectSQL(kind, dateWhere, native), args...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -173,6 +195,18 @@ func citySearchKindOrder(kind string) int {
|
|||||||
// All interpolated SQL fragments are package-owned constants. User input is
|
// All interpolated SQL fragments are package-owned constants. User input is
|
||||||
// bound, so %, _, quotes and backslashes are literal substring characters.
|
// bound, so %, _, quotes and backslashes are literal substring characters.
|
||||||
func citySearchSQL(kind, dateWhere string) string {
|
func citySearchSQL(kind, dateWhere string) string {
|
||||||
|
return citySearchDialectSQL(kind, dateWhere, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func citySearchDialectSQL(kind, dateWhere string, native bool) string {
|
||||||
|
domain, scope, prefix, upper, query, limit := ":domain", ":scope", ":prefix", ":upper", ":query", ":limit"
|
||||||
|
collation, position, greatest := " COLLATE BINARY", "instr", "max"
|
||||||
|
absolute := citySearchAbsolutePathSQL
|
||||||
|
if native {
|
||||||
|
domain, scope, prefix, upper, query, limit = "$1", "$2", "$3", "$4", "$5", "$6"
|
||||||
|
collation, position, greatest = ` COLLATE "C"`, "strpos", "greatest"
|
||||||
|
absolute = func(column string) string { return `(substr(` + column + `,1,1)='/' AND length(` + column + `)<=4096)` }
|
||||||
|
}
|
||||||
from, description := "zones n", "n.description"
|
from, description := "zones n", "n.description"
|
||||||
navigationPath := "n.path_prefix"
|
navigationPath := "n.path_prefix"
|
||||||
parentColumns := "'','','','',''"
|
parentColumns := "'','','','',''"
|
||||||
@@ -181,28 +215,32 @@ func citySearchSQL(kind, dateWhere string) string {
|
|||||||
case "street":
|
case "street":
|
||||||
from += ` JOIN zones q ON q.uuid=n.parent_uuid AND q.domain_uuid=n.domain_uuid AND q.kind='quartier' AND q.state!='archived'`
|
from += ` JOIN zones q ON q.uuid=n.parent_uuid AND q.domain_uuid=n.domain_uuid AND q.kind='quartier' AND q.state!='archived'`
|
||||||
parentColumns = "substr(COALESCE(NULLIF(q.title,''),q.name),1,256),'',q.path_prefix,'',q.name"
|
parentColumns = "substr(COALESCE(NULLIF(q.title,''),q.name),1,256),'',q.path_prefix,'',q.name"
|
||||||
where = "n.kind='street' AND " + citySearchAbsolutePathSQL("q.path_prefix")
|
where = "n.kind='street' AND " + absolute("q.path_prefix")
|
||||||
case "spot":
|
case "spot":
|
||||||
navigationPath = `CASE WHEN substr(n.path_prefix,-11)='/_undefined' THEN st.path_prefix ELSE n.path_prefix END`
|
navigationPath = `CASE WHEN substr(n.path_prefix,-11)='/_undefined' THEN st.path_prefix ELSE n.path_prefix END`
|
||||||
|
if native {
|
||||||
|
navigationPath = `CASE WHEN right(n.path_prefix,11)='/_undefined' THEN st.path_prefix ELSE n.path_prefix END`
|
||||||
|
}
|
||||||
from = `spots n JOIN street_spots ss ON ss.spot_uuid=n.uuid
|
from = `spots n JOIN street_spots ss ON ss.spot_uuid=n.uuid
|
||||||
JOIN zones st ON st.uuid=ss.street_uuid AND st.domain_uuid=n.domain_uuid AND st.kind='street' AND st.state!='archived'
|
JOIN zones st ON st.uuid=ss.street_uuid AND st.domain_uuid=n.domain_uuid AND st.kind='street' AND st.state!='archived'
|
||||||
JOIN zones q ON q.uuid=st.parent_uuid AND q.domain_uuid=st.domain_uuid AND q.kind='quartier' AND q.state!='archived'`
|
JOIN zones q ON q.uuid=st.parent_uuid AND q.domain_uuid=st.domain_uuid AND q.kind='quartier' AND q.state!='archived'`
|
||||||
description = "n.summary"
|
description = "n.summary"
|
||||||
parentColumns = "substr(COALESCE(NULLIF(q.title,''),q.name),1,256),substr(COALESCE(NULLIF(st.title,''),st.name),1,256),q.path_prefix,st.path_prefix,q.name"
|
parentColumns = "substr(COALESCE(NULLIF(q.title,''),q.name),1,256),substr(COALESCE(NULLIF(st.title,''),st.name),1,256),q.path_prefix,st.path_prefix,q.name"
|
||||||
where = citySearchAbsolutePathSQL("q.path_prefix") + " AND " + citySearchAbsolutePathSQL("st.path_prefix")
|
where = absolute("q.path_prefix") + " AND " + absolute("st.path_prefix")
|
||||||
}
|
}
|
||||||
nameMatch := `(:query!='' AND (instr(lower(n.name),lower(:query))>0 OR instr(lower(n.title),lower(:query))>0))`
|
contains := func(column string) string { return position + "(lower(" + column + "),lower(" + query + "))" }
|
||||||
pathMatch := `(:query!='' AND instr(lower(n.path_prefix),lower(:query))>0)`
|
nameMatch := `(` + query + `!='' AND (` + contains("n.name") + `>0 OR ` + contains("n.title") + `>0))`
|
||||||
descriptionMatch := `(:query!='' AND instr(lower(` + description + `),lower(:query))>0)`
|
pathMatch := `(` + query + `!='' AND ` + contains("n.path_prefix") + `>0)`
|
||||||
|
descriptionMatch := `(` + query + `!='' AND ` + contains(description) + `>0)`
|
||||||
return `SELECT n.uuid,substr(n.name,1,256),substr(n.title,1,256),
|
return `SELECT n.uuid,substr(n.name,1,256),substr(n.title,1,256),
|
||||||
substr(` + description + `,max(1,instr(lower(` + description + `),lower(:query))-160),512),
|
substr(` + description + `,` + greatest + `(1,` + contains(description) + `-160),512),
|
||||||
n.path_prefix,n.created_at_ms,n.updated_at_ms,` + nameMatch + `,` + pathMatch + `,` + descriptionMatch + `,` + parentColumns + `,` + navigationPath + `,
|
n.path_prefix,n.created_at_ms,n.updated_at_ms,` + nameMatch + `,` + pathMatch + `,` + descriptionMatch + `,` + parentColumns + `,` + navigationPath + `,
|
||||||
EXISTS(SELECT 1 FROM paths cp WHERE cp.domain_uuid=n.domain_uuid AND cp.path=(` + navigationPath + `))
|
EXISTS(SELECT 1 FROM paths cp WHERE cp.domain_uuid=n.domain_uuid AND cp.path=(` + navigationPath + `))
|
||||||
FROM ` + from + ` WHERE n.domain_uuid=:domain AND n.state!='archived' AND ` + where + `
|
FROM ` + from + ` WHERE n.domain_uuid=` + domain + ` AND n.state!='archived' AND ` + where + `
|
||||||
AND ` + citySearchAbsolutePathSQL("n.path_prefix") + `
|
AND ` + absolute("n.path_prefix") + `
|
||||||
AND (n.path_prefix COLLATE BINARY=:scope OR (n.path_prefix COLLATE BINARY>=:prefix AND n.path_prefix COLLATE BINARY<:upper))
|
AND (n.path_prefix` + collation + `=` + scope + ` OR (n.path_prefix` + collation + `>=` + prefix + ` AND n.path_prefix` + collation + `<` + upper + `))
|
||||||
AND (:query='' OR ` + nameMatch + ` OR ` + pathMatch + ` OR ` + descriptionMatch + `)` + dateWhere + `
|
AND (` + query + `='' OR ` + nameMatch + ` OR ` + pathMatch + ` OR ` + descriptionMatch + `)` + dateWhere + `
|
||||||
ORDER BY ` + nameMatch + ` DESC,` + pathMatch + ` DESC,n.path_prefix COLLATE BINARY,n.uuid LIMIT :limit`
|
ORDER BY ` + nameMatch + ` DESC,` + pathMatch + ` DESC,n.path_prefix` + collation + `,n.uuid LIMIT ` + limit
|
||||||
}
|
}
|
||||||
|
|
||||||
func citySearchAbsolutePathSQL(column string) string {
|
func citySearchAbsolutePathSQL(column string) string {
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package mestionora
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PostgreSQL's initial search profile is metadata-only. It deliberately does
|
||||||
|
// not scan canonical files or the legacy body column to emulate SQLite FTS.
|
||||||
|
// The caller owns the pool and must provision the native metadata schema.
|
||||||
|
type PostgreSQL struct{ db *sql.DB }
|
||||||
|
|
||||||
|
func NewPostgreSQL(db *sql.DB) *PostgreSQL { return &PostgreSQL{db: db} }
|
||||||
|
|
||||||
|
const pgSearchMIME = `lower(trim(split_part(COALESCE(r.content_type,''),';',1)))`
|
||||||
|
|
||||||
|
var pgSearchFileType = buildSearchFileTypeSQL(pgSearchMIME, func(suffixes ...string) string {
|
||||||
|
clauses := make([]string, 0, len(suffixes))
|
||||||
|
for _, suffix := range suffixes {
|
||||||
|
clauses = append(clauses, searchFilenameSQL+fmt.Sprintf(` LIKE '%%.%s'`, suffix))
|
||||||
|
}
|
||||||
|
return "(" + strings.Join(clauses, " OR ") + ")"
|
||||||
|
}, func(pattern string) string {
|
||||||
|
// Only the package-owned MIME glob constants above reach this function.
|
||||||
|
return pgSearchMIME + ` LIKE '` + strings.ReplaceAll(pattern, "*", "%") + `'`
|
||||||
|
})
|
||||||
|
|
||||||
|
func (s *PostgreSQL) SearchPathsInDomainWithOptions(ctx context.Context, domainUUID, scope, query string, limit int, allowed func(string) bool, options SearchOptions) (found []SearchResult, err error) {
|
||||||
|
if err := options.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
scope, query = normalizePath(scope), strings.TrimSpace(query)
|
||||||
|
if allowed == nil || query == "" && !options.HasFilters() {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if len(query) > 512 || len(strings.Fields(query)) > 16 {
|
||||||
|
return nil, errors.New("search query is too long")
|
||||||
|
}
|
||||||
|
if limit <= 0 || limit > 200 {
|
||||||
|
limit = 100
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
defer func() {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
found, err = nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
var args []any
|
||||||
|
bind := func(v any) string { args = append(args, v); return fmt.Sprintf("$%d", len(args)) }
|
||||||
|
prefix := strings.TrimRight(scope, "/") + "/"
|
||||||
|
upper := prefix[:len(prefix)-1] + "0"
|
||||||
|
predicate := "p.domain_uuid=" + bind(domainUUID) + " AND (p.path=" + bind(scope) + " OR (p.path>=" + bind(prefix) + " AND p.path<" + bind(upper) + "))"
|
||||||
|
if query != "" {
|
||||||
|
q := bind(query)
|
||||||
|
predicate += " AND (strpos(lower(p.path),lower(" + q + "))>0 OR strpos(lower(COALESCE(r.filename,'')),lower(" + q + "))>0)"
|
||||||
|
}
|
||||||
|
date := "r.created_at_ms"
|
||||||
|
if options.DateField == "created" {
|
||||||
|
date = "(SELECT o.created_at*1000 FROM objects o WHERE o.uuid=p.object_uuid)"
|
||||||
|
}
|
||||||
|
if options.FromMS != nil {
|
||||||
|
predicate += " AND " + date + ">=" + bind(*options.FromMS)
|
||||||
|
}
|
||||||
|
if options.BeforeMS != nil {
|
||||||
|
predicate += " AND " + date + "<" + bind(*options.BeforeMS)
|
||||||
|
}
|
||||||
|
if options.Extension != "" {
|
||||||
|
ext := bind("." + options.Extension)
|
||||||
|
predicate += " AND right(" + searchFilenameSQL + ",length(" + ext + "))=" + ext
|
||||||
|
}
|
||||||
|
if options.FileType != "" {
|
||||||
|
predicate += " AND (" + pgSearchFileType + ")=" + bind(options.FileType)
|
||||||
|
}
|
||||||
|
rows, err := s.db.QueryContext(ctx, `SELECT p.path,COALESCE(r.content_type,''),COALESCE(r.filename,''),COALESCE(r.document_hash,''),COALESCE(r.uuid,''),COALESCE(r.created_at_ms/1000,0)
|
||||||
|
FROM paths p LEFT JOIN LATERAL (SELECT uuid,content_type,filename,document_hash,created_at_ms FROM revisions WHERE object_uuid=p.object_uuid ORDER BY created_at_ms DESC,uuid DESC LIMIT 1) r ON true
|
||||||
|
WHERE `+predicate+` ORDER BY p.path LIMIT `+bind(SearchCandidateLimit), args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
candidates := make([]SearchResult, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var result SearchResult
|
||||||
|
if err = rows.Scan(&result.Path, &result.ContentType, &result.Filename, &result.DocumentHash, &result.RevisionUUID, &result.UpdatedAt); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
result.PathMatch = query != "" && strings.Contains(strings.ToLower(result.Path), strings.ToLower(query))
|
||||||
|
result.FilenameMatch = query != "" && strings.Contains(strings.ToLower(result.Filename), strings.ToLower(query))
|
||||||
|
candidates = append(candidates, result)
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Release the cursor before policy callbacks: authorization may need the
|
||||||
|
// same single-connection pool. Never return a denied Path or load its body.
|
||||||
|
sort.Slice(candidates, func(i, j int) bool {
|
||||||
|
if len(candidates[i].Path) != len(candidates[j].Path) {
|
||||||
|
return len(candidates[i].Path) < len(candidates[j].Path)
|
||||||
|
}
|
||||||
|
return candidates[i].Path < candidates[j].Path
|
||||||
|
})
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
if err = ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if allowed(candidate.Path) {
|
||||||
|
found = append(found, candidate)
|
||||||
|
if len(found) == limit {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQL) SearchPathSuggestionsInDomain(ctx context.Context, domainUUID, scope, query string, limit int, allowed func(string) bool) ([]PathSuggestion, error) {
|
||||||
|
results, err := s.SearchPathsInDomainWithOptions(ctx, domainUUID, scope, query, limit, allowed, SearchOptions{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make([]PathSuggestion, 0, len(results))
|
||||||
|
for _, result := range results {
|
||||||
|
out = append(out, PathSuggestion{SearchResult: result})
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -71,18 +71,25 @@ func searchSuffixesSQL(suffixes ...string) string {
|
|||||||
// known suffix (e.g. a Python source uploaded as text/plain); unrecognized,
|
// known suffix (e.g. a Python source uploaded as text/plain); unrecognized,
|
||||||
// specific MIME types stay Other instead of pretending to be a different type.
|
// specific MIME types stay Other instead of pretending to be a different type.
|
||||||
// This uses metadata only and never hydrates a Document to sniff its bytes.
|
// This uses metadata only and never hydrates a Document to sniff its bytes.
|
||||||
var searchFileTypeSQL = `CASE
|
var searchFileTypeSQL = buildSearchFileTypeSQL(searchMIMESQL, searchSuffixesSQL, func(pattern string) string {
|
||||||
|
return searchMIMESQL + ` GLOB '` + pattern + `'`
|
||||||
|
})
|
||||||
|
|
||||||
|
// All patterns are package-owned constants. The dialect-specific builders do
|
||||||
|
// not translate incoming SQL or interpolate user input.
|
||||||
|
func buildSearchFileTypeSQL(searchMIMESQL string, searchSuffixesSQL func(...string) string, mimeGlob func(string) string) string {
|
||||||
|
return `CASE
|
||||||
WHEN ` + searchMIMESQL + ` IN ('text/html','application/xhtml+xml') THEN 'html'
|
WHEN ` + searchMIMESQL + ` IN ('text/html','application/xhtml+xml') THEN 'html'
|
||||||
WHEN ` + searchMIMESQL + `='application/pdf' THEN 'pdf'
|
WHEN ` + searchMIMESQL + `='application/pdf' THEN 'pdf'
|
||||||
WHEN ` + searchMIMESQL + ` LIKE 'image/%' THEN 'image'
|
WHEN ` + searchMIMESQL + ` LIKE 'image/%' THEN 'image'
|
||||||
WHEN ` + searchMIMESQL + ` LIKE 'audio/%' THEN 'audio'
|
WHEN ` + searchMIMESQL + ` LIKE 'audio/%' THEN 'audio'
|
||||||
WHEN ` + searchMIMESQL + ` LIKE 'video/%' THEN 'video'
|
WHEN ` + searchMIMESQL + ` LIKE 'video/%' THEN 'video'
|
||||||
WHEN ` + searchMIMESQL + ` IN ('text/csv','application/csv','text/tab-separated-values') THEN 'csv'
|
WHEN ` + searchMIMESQL + ` IN ('text/csv','application/csv','text/tab-separated-values') THEN 'csv'
|
||||||
WHEN ` + searchMIMESQL + ` IN ('application/json','text/json') OR ` + searchMIMESQL + ` GLOB '*+json' THEN 'json'
|
WHEN ` + searchMIMESQL + ` IN ('application/json','text/json') OR ` + mimeGlob("*+json") + ` THEN 'json'
|
||||||
WHEN ` + searchMIMESQL + ` IN ('application/zip','application/x-zip-compressed','application/x-7z-compressed','application/vnd.rar','application/x-rar','application/x-rar-compressed','application/x-tar','application/gzip','application/x-gzip','application/x-xz','application/x-bzip2','application/zstd','application/x-zstd','application/x-compress','application/x-cpio') THEN 'archive'
|
WHEN ` + searchMIMESQL + ` IN ('application/zip','application/x-zip-compressed','application/x-7z-compressed','application/vnd.rar','application/x-rar','application/x-rar-compressed','application/x-tar','application/gzip','application/x-gzip','application/x-xz','application/x-bzip2','application/zstd','application/x-zstd','application/x-compress','application/x-cpio') THEN 'archive'
|
||||||
WHEN ` + searchMIMESQL + ` IN ('application/msword','application/vnd.ms-excel','application/vnd.ms-powerpoint','application/rtf','text/rtf') OR ` + searchMIMESQL + ` GLOB 'application/vnd.openxmlformats-officedocument.*' OR ` + searchMIMESQL + ` GLOB 'application/vnd.oasis.opendocument.*' OR ` + searchMIMESQL + ` GLOB 'application/vnd.ms-*.macroenabled.*' THEN 'office'
|
WHEN ` + searchMIMESQL + ` IN ('application/msword','application/vnd.ms-excel','application/vnd.ms-powerpoint','application/rtf','text/rtf') OR ` + mimeGlob("application/vnd.openxmlformats-officedocument.*") + ` OR ` + mimeGlob("application/vnd.oasis.opendocument.*") + ` OR ` + mimeGlob("application/vnd.ms-*.macroenabled.*") + ` THEN 'office'
|
||||||
WHEN ` + searchMIMESQL + ` IN ('text/markdown','text/x-markdown') THEN 'text'
|
WHEN ` + searchMIMESQL + ` IN ('text/markdown','text/x-markdown') THEN 'text'
|
||||||
WHEN ` + searchMIMESQL + ` IN ('application/javascript','application/x-javascript','text/javascript','application/typescript','text/typescript','application/xml','text/xml','application/yaml','application/x-yaml','text/yaml','application/toml','application/x-sh','application/x-shellscript','application/x-python','application/x-python-code','application/x-httpd-php','application/sql','text/css') OR ` + searchMIMESQL + ` GLOB 'text/x-*' OR ` + searchMIMESQL + ` GLOB '*+xml' THEN 'code'
|
WHEN ` + searchMIMESQL + ` IN ('application/javascript','application/x-javascript','text/javascript','application/typescript','text/typescript','application/xml','text/xml','application/yaml','application/x-yaml','text/yaml','application/toml','application/x-sh','application/x-shellscript','application/x-python','application/x-python-code','application/x-httpd-php','application/sql','text/css') OR ` + mimeGlob("text/x-*") + ` OR ` + mimeGlob("*+xml") + ` THEN 'code'
|
||||||
WHEN ` + searchMIMESQL + ` NOT IN ('','text/plain','application/octet-stream','binary/octet-stream','application/x-empty') THEN CASE WHEN ` + searchMIMESQL + ` LIKE 'text/%' THEN 'text' ELSE 'other' END
|
WHEN ` + searchMIMESQL + ` NOT IN ('','text/plain','application/octet-stream','binary/octet-stream','application/x-empty') THEN CASE WHEN ` + searchMIMESQL + ` LIKE 'text/%' THEN 'text' ELSE 'other' END
|
||||||
WHEN ` + searchSuffixesSQL("html", "htm", "xhtml") + ` THEN 'html'
|
WHEN ` + searchSuffixesSQL("html", "htm", "xhtml") + ` THEN 'html'
|
||||||
WHEN ` + searchSuffixesSQL("pdf") + ` THEN 'pdf'
|
WHEN ` + searchSuffixesSQL("pdf") + ` THEN 'pdf'
|
||||||
@@ -96,6 +103,7 @@ var searchFileTypeSQL = `CASE
|
|||||||
WHEN ` + searchSuffixesSQL("py", "pyw", "sh", "bash", "zsh", "fish", "ps1", "bat", "cmd", "js", "mjs", "cjs", "jsx", "ts", "tsx", "go", "rs", "c", "h", "cpp", "hpp", "cc", "cs", "java", "kt", "kts", "swift", "rb", "php", "pl", "pm", "lua", "r", "sql", "css", "scss", "sass", "less", "xml", "xsl", "yaml", "yml", "toml", "ini", "conf", "vue", "svelte", "dart", "ex", "exs", "erl", "hs", "scala", "clj", "lisp", "el", "vim", "wasm") + ` THEN 'code'
|
WHEN ` + searchSuffixesSQL("py", "pyw", "sh", "bash", "zsh", "fish", "ps1", "bat", "cmd", "js", "mjs", "cjs", "jsx", "ts", "tsx", "go", "rs", "c", "h", "cpp", "hpp", "cc", "cs", "java", "kt", "kts", "swift", "rb", "php", "pl", "pm", "lua", "r", "sql", "css", "scss", "sass", "less", "xml", "xsl", "yaml", "yml", "toml", "ini", "conf", "vue", "svelte", "dart", "ex", "exs", "erl", "hs", "scala", "clj", "lisp", "el", "vim", "wasm") + ` THEN 'code'
|
||||||
WHEN ` + searchMIMESQL + `='text/plain' OR ` + searchSuffixesSQL("txt", "text", "log", "md", "markdown", "rst", "adoc", "org") + ` THEN 'text'
|
WHEN ` + searchMIMESQL + `='text/plain' OR ` + searchSuffixesSQL("txt", "text", "log", "md", "markdown", "rst", "adoc", "org") + ` THEN 'text'
|
||||||
ELSE 'other' END`
|
ELSE 'other' END`
|
||||||
|
}
|
||||||
|
|
||||||
// The returned predicate is inserted before each candidate stream's LIMIT,
|
// The returned predicate is inserted before each candidate stream's LIMIT,
|
||||||
// including FTS-first streams. Filtering after their cap silently loses hits.
|
// including FTS-first streams. Filtering after their cap silently loses hits.
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Asset struct {
|
||||||
|
DomainUUID string
|
||||||
|
Address string
|
||||||
|
ObjectUUID string
|
||||||
|
HeadDocumentHash string
|
||||||
|
ContentType string
|
||||||
|
Filename string
|
||||||
|
SizeBytes int64
|
||||||
|
CreatedAtMS int64
|
||||||
|
UpdatedAtMS int64
|
||||||
|
}
|
||||||
|
|
||||||
|
const assetColumns = `domain_uuid,address,object_uuid,head_document_hash,content_type,filename,size_bytes,created_at_ms,updated_at_ms`
|
||||||
|
|
||||||
|
func scanAsset(row interface{ Scan(...any) error }) (Asset, error) {
|
||||||
|
var a Asset
|
||||||
|
err := row.Scan(&a.DomainUUID, &a.Address, &a.ObjectUUID, &a.HeadDocumentHash, &a.ContentType, &a.Filename, &a.SizeBytes, &a.CreatedAtMS, &a.UpdatedAtMS)
|
||||||
|
return a, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetAsset(ctx context.Context, domain, address string) (Asset, error) {
|
||||||
|
a, err := scanAsset(r.database.QueryRowContext(ctx, `SELECT `+assetColumns+` FROM assets WHERE domain_uuid=`+r.p(1)+` AND address=`+r.p(2), domain, address))
|
||||||
|
return a, r.failure(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PutAsset publishes an already-durable Document hash and appends its audit
|
||||||
|
// history in the same transaction. Empty expected is create-only; overwrites
|
||||||
|
// compare the previous hash and keep the asset's object UUID stable.
|
||||||
|
func (r *Repository) PutAsset(ctx context.Context, a Asset, expected, actor string) (Asset, error) {
|
||||||
|
a.Address = strings.TrimSpace(a.Address)
|
||||||
|
parts := strings.SplitN(a.Address, ":", 3)
|
||||||
|
if a.DomainUUID == "" || len(parts) != 3 || parts[0] != "asset" || strings.TrimSpace(parts[1]) == "" || strings.TrimSpace(parts[2]) == "" || strings.ContainsAny(a.Address, "\x00\r\n") || !validHash(a.HeadDocumentHash) || strings.TrimSpace(a.ContentType) == "" || a.SizeBytes < 0 {
|
||||||
|
return Asset{}, ErrInvalid
|
||||||
|
}
|
||||||
|
err := r.write(ctx, "domain/"+a.DomainUUID, func(tx *sql.Tx) error {
|
||||||
|
old, err := scanAsset(tx.QueryRowContext(ctx, `SELECT `+assetColumns+` FROM assets WHERE domain_uuid=`+r.p(1)+` AND address=`+r.p(2), a.DomainUUID, a.Address))
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if old.HeadDocumentHash != expected {
|
||||||
|
return ErrConflict
|
||||||
|
}
|
||||||
|
if r.applicationNamespace && err == nil && old.HeadDocumentHash == a.HeadDocumentHash && old.ContentType == a.ContentType && old.Filename == a.Filename && old.SizeBytes == a.SizeBytes {
|
||||||
|
a = old
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
a.UpdatedAtMS = time.Now().UnixMilli()
|
||||||
|
if err == nil {
|
||||||
|
a.ObjectUUID = old.ObjectUUID
|
||||||
|
a.CreatedAtMS = old.CreatedAtMS
|
||||||
|
if a.UpdatedAtMS <= old.UpdatedAtMS {
|
||||||
|
a.UpdatedAtMS = old.UpdatedAtMS + 1
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE assets SET head_document_hash=`+r.p(1)+`,content_type=`+r.p(2)+`,filename=`+r.p(3)+`,size_bytes=`+r.p(4)+`,updated_at_ms=`+r.p(5)+` WHERE domain_uuid=`+r.p(6)+` AND address=`+r.p(7), a.HeadDocumentHash, a.ContentType, a.Filename, a.SizeBytes, a.UpdatedAtMS, a.DomainUUID, a.Address)
|
||||||
|
} else {
|
||||||
|
a.ObjectUUID = uuid.NewString()
|
||||||
|
a.CreatedAtMS = a.UpdatedAtMS
|
||||||
|
if _, err = tx.ExecContext(ctx, `INSERT INTO objects(uuid,kind,created_at) VALUES (`+r.p(1)+`,'asset',`+r.p(2)+`)`, a.ObjectUUID, a.CreatedAtMS/1000); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if _, err = tx.ExecContext(ctx, `INSERT INTO object_origins(object_uuid,domain_uuid,created_at) VALUES (`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`)`, a.ObjectUUID, a.DomainUUID, a.CreatedAtMS/1000); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO assets (`+assetColumns+`) VALUES (`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`,`+r.p(5)+`,`+r.p(6)+`,`+r.p(7)+`,`+r.p(8)+`,`+r.p(9)+`)`, a.DomainUUID, a.Address, a.ObjectUUID, a.HeadDocumentHash, a.ContentType, a.Filename, a.SizeBytes, a.CreatedAtMS, a.UpdatedAtMS)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO asset_head_history(domain_uuid,address,action,document_hash,content_type,filename,size_bytes,actor_uuid,created_at_ms) VALUES (`+r.p(1)+`,`+r.p(2)+`,'put',`+r.p(3)+`,`+r.p(4)+`,`+r.p(5)+`,`+r.p(6)+`,`+r.p(7)+`,`+r.p(8)+`)`, a.DomainUUID, a.Address, a.HeadDocumentHash, a.ContentType, a.Filename, a.SizeBytes, actor, a.UpdatedAtMS)
|
||||||
|
return r.failure(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return Asset{}, err
|
||||||
|
}
|
||||||
|
return a, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"mime"
|
||||||
|
|
||||||
|
"pageswiki/internal/documentrefs"
|
||||||
|
"pageswiki/internal/geduldh"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SavedDocument struct {
|
||||||
|
Revision Revision
|
||||||
|
Payload []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// RestoreDocument preserves the historical immutable embedded references; it
|
||||||
|
// must not parse Asset provenance and rebind it to today's mutable Asset HEAD.
|
||||||
|
func (r *Repository) RestoreDocument(ctx context.Context, documents geduldh.Store, domain, revision, expected, message, actor string) (Revision, error) {
|
||||||
|
if documents == nil {
|
||||||
|
return Revision{}, ErrInvalid
|
||||||
|
}
|
||||||
|
v, err := r.GetRevision(ctx, domain, revision)
|
||||||
|
if err != nil {
|
||||||
|
return Revision{}, err
|
||||||
|
}
|
||||||
|
refs, err := r.revisionReferences(ctx, domain, revision)
|
||||||
|
if err != nil {
|
||||||
|
return Revision{}, err
|
||||||
|
}
|
||||||
|
for _, hash := range append([]string{v.DocumentHash}, refs...) {
|
||||||
|
if err := documents.Verify(ctx, hash); err != nil {
|
||||||
|
return Revision{}, fmt.Errorf("verify restored Document: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v.Message = message
|
||||||
|
return r.appendRevision(ctx, domain, v, expected, refs, actor)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveDocument freezes Domain-local Asset HEADs, verifies embedded payloads,
|
||||||
|
// persists the immutable Document, then atomically publishes Revision, refs and
|
||||||
|
// outbox. No SQL transaction/lock is held during filesystem or remote I/O.
|
||||||
|
// A failed metadata commit may leave an unreferenced immutable blob; it must
|
||||||
|
// never delete that blob (another writer may already reference the same hash).
|
||||||
|
// Concurrent GC needs a separate pin protocol before this pipeline is enabled
|
||||||
|
// in a deployment with background deletion. This is not an authorization API.
|
||||||
|
func (r *Repository) SaveDocument(ctx context.Context, documents geduldh.Store, domain string, v Revision, payload []byte, expected, actor string) (SavedDocument, error) {
|
||||||
|
return r.saveDocument(ctx, documents, domain, v, payload, &expected, actor)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveDocumentUnconditionally preserves append-without-CAS semantics for import
|
||||||
|
// and legacy clients. Concurrent saves still append immutable revisions with
|
||||||
|
// monotonic timestamps; it must not be used to silently retry a failed CAS.
|
||||||
|
func (r *Repository) SaveDocumentUnconditionally(ctx context.Context, documents geduldh.Store, domain string, v Revision, payload []byte, actor string) (SavedDocument, error) {
|
||||||
|
return r.saveDocument(ctx, documents, domain, v, payload, nil, actor)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) saveDocument(ctx context.Context, documents geduldh.Store, domain string, v Revision, payload []byte, expected *string, actor string) (SavedDocument, error) {
|
||||||
|
if documents == nil {
|
||||||
|
return SavedDocument{}, ErrInvalid
|
||||||
|
}
|
||||||
|
lang, err := normalizedLanguage(v.Language)
|
||||||
|
if err != nil {
|
||||||
|
return SavedDocument{}, err
|
||||||
|
}
|
||||||
|
v.Language = lang
|
||||||
|
if _, _, err := mime.ParseMediaType(v.ContentType); err != nil {
|
||||||
|
return SavedDocument{}, ErrInvalid
|
||||||
|
}
|
||||||
|
var bound bool
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM objects o WHERE o.uuid=`+r.p(1)+` AND (`+r.objectDomainScope("o.uuid", r.p(2))+`))`, v.ObjectUUID, domain).Scan(&bound); err != nil {
|
||||||
|
return SavedDocument{}, r.failure(err)
|
||||||
|
}
|
||||||
|
if !bound {
|
||||||
|
return SavedDocument{}, ErrNotFound
|
||||||
|
}
|
||||||
|
// Fail stale saves before expensive payload work; repeat CAS in the commit
|
||||||
|
// transaction because a different writer may commit after this preflight.
|
||||||
|
head, err := r.Head(ctx, domain, v.ObjectUUID, v.Language)
|
||||||
|
if err != nil && !errors.Is(err, ErrNotFound) {
|
||||||
|
return SavedDocument{}, err
|
||||||
|
}
|
||||||
|
if expected != nil && head.UUID != *expected {
|
||||||
|
return SavedDocument{}, ErrConflict
|
||||||
|
}
|
||||||
|
frozen, refs, err := documentrefs.Freeze(ctx, payload, v.ContentType, func(ctx context.Context, address string) (string, error) {
|
||||||
|
a, err := r.GetAsset(ctx, domain, address)
|
||||||
|
if errors.Is(err, ErrNotFound) {
|
||||||
|
return "", documentrefs.ErrUnavailable
|
||||||
|
}
|
||||||
|
return a.HeadDocumentHash, err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return SavedDocument{}, err
|
||||||
|
}
|
||||||
|
for _, hash := range refs {
|
||||||
|
if err := documents.Verify(ctx, hash); err != nil {
|
||||||
|
return SavedDocument{}, fmt.Errorf("verify embedded Document: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256(frozen)
|
||||||
|
v.DocumentHash = hex.EncodeToString(sum[:])
|
||||||
|
if err := documents.PutIfAbsent(ctx, v.DocumentHash, int64(len(frozen)), bytes.NewReader(frozen)); err != nil {
|
||||||
|
return SavedDocument{}, fmt.Errorf("persist Document: %w", err)
|
||||||
|
}
|
||||||
|
created, err := r.appendRevisionExpected(ctx, domain, v, expected, refs, actor)
|
||||||
|
if err != nil {
|
||||||
|
return SavedDocument{}, err
|
||||||
|
}
|
||||||
|
return SavedDocument{Revision: created, Payload: frozen}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/documentrefs"
|
||||||
|
"pageswiki/internal/geduldh"
|
||||||
|
)
|
||||||
|
|
||||||
|
type faultDocuments struct {
|
||||||
|
geduldh.Store
|
||||||
|
putErr error
|
||||||
|
verifyErr error
|
||||||
|
afterPut func()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f faultDocuments) PutIfAbsent(ctx context.Context, h string, n int64, reader io.Reader) error {
|
||||||
|
if f.putErr != nil {
|
||||||
|
return f.putErr
|
||||||
|
}
|
||||||
|
if err := f.Store.PutIfAbsent(ctx, h, n, reader); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if f.afterPut != nil {
|
||||||
|
f.afterPut()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (f faultDocuments) Verify(ctx context.Context, h string) error {
|
||||||
|
if f.verifyErr != nil {
|
||||||
|
return f.verifyErr
|
||||||
|
}
|
||||||
|
return f.Store.Verify(ctx, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
func documentFixture(t *testing.T, r *Repository) (geduldh.Store, string, Revision) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
documents, err := geduldh.NewLocal(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
content := []byte("synthetic image")
|
||||||
|
h := hash(string(content))
|
||||||
|
if err := documents.PutIfAbsent(ctx, h, int64(len(content)), bytes.NewReader(content)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.PutAsset(ctx, Asset{DomainUUID: "test", Address: "asset:image:cover", HeadDocumentHash: h, ContentType: "image/png", SizeBytes: int64(len(content))}, "", "actor"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
object, err := r.CreatePage(ctx, "test", "/guide")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return documents, h, Revision{ObjectUUID: object, Language: "ja", ContentType: "text/html; charset=utf-8", Message: "synthetic save"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDocumentSaveReferencesOutboxAndRestore(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
docs, assetHash, v := documentFixture(t, r)
|
||||||
|
body := []byte(`<h1>Guide</h1><img src="asset:image:cover"><img src="asset:image:cover">`)
|
||||||
|
if _, err := r.PutAsset(ctx, Asset{DomainUUID: "private-domain", Address: "asset:image:private", HeadDocumentHash: assetHash, ContentType: "image/png", SizeBytes: 15}, "", "actor"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.SaveDocument(ctx, docs, "test", v, []byte(`<img src="asset:image:private">`), "", "actor"); !errors.Is(err, documentrefs.ErrUnavailable) {
|
||||||
|
t.Fatal("foreign Asset resolved", err)
|
||||||
|
}
|
||||||
|
first, err := r.SaveDocument(ctx, docs, "test", v, body, "", "actor")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(first.Payload), "/_/obj/sha256:"+assetHash) {
|
||||||
|
t.Fatal("mutable URL not frozen")
|
||||||
|
}
|
||||||
|
if err := docs.Verify(ctx, first.Revision.DocumentHash); err != nil {
|
||||||
|
t.Fatal("metadata published without durable Document", err)
|
||||||
|
}
|
||||||
|
refs, err := r.revisionReferences(ctx, "test", first.Revision.UUID)
|
||||||
|
if err != nil || len(refs) != 1 || refs[0] != assetHash {
|
||||||
|
t.Fatal("embedded reference", err, refs)
|
||||||
|
}
|
||||||
|
var eventDomain, target, payload, actor string
|
||||||
|
var sequence int64
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT domain_uuid,target_uuid,payload,actor_uuid,sequence FROM activity_outbox`).Scan(&eventDomain, &target, &payload, &actor, &sequence); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var envelope map[string]string
|
||||||
|
if err := json.Unmarshal([]byte(payload), &envelope); err != nil || eventDomain != "test" || actor != "actor" || sequence != 1 || target != first.Revision.UUID || envelope["document_hash"] != first.Revision.DocumentHash {
|
||||||
|
t.Fatal("outbox envelope mismatch", err)
|
||||||
|
}
|
||||||
|
newContent := []byte("next synthetic image")
|
||||||
|
newHash := hash(string(newContent))
|
||||||
|
if err := docs.PutIfAbsent(ctx, newHash, int64(len(newContent)), bytes.NewReader(newContent)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.PutAsset(ctx, Asset{DomainUUID: "test", Address: "asset:image:cover", HeadDocumentHash: newHash, ContentType: "image/png", SizeBytes: int64(len(newContent))}, assetHash, "actor"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
second, err := r.SaveDocument(ctx, docs, "test", v, first.Payload, first.Revision.UUID, "actor")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(second.Payload), newHash) {
|
||||||
|
t.Fatal("provenance not refreshed")
|
||||||
|
}
|
||||||
|
restored, err := r.RestoreRevision(ctx, "test", first.Revision.UUID, second.Revision.UUID, "restore")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
refs, err = r.revisionReferences(ctx, "test", restored.UUID)
|
||||||
|
if err != nil || len(refs) != 1 || refs[0] != assetHash || restored.DocumentHash != first.Revision.DocumentHash {
|
||||||
|
t.Fatal("restore followed new Asset HEAD instead of historical refs", err)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM activity_outbox`).Scan(&count); err != nil || count != 3 {
|
||||||
|
t.Fatal("save/restore event count", count, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDocumentSaveFailureIsAtomic(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
for _, stage := range []string{"references", "outbox"} {
|
||||||
|
t.Run(string(backend)+"/"+stage, func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
docs, _, v := documentFixture(t, r)
|
||||||
|
body := []byte(`<img src="asset:image:cover">`)
|
||||||
|
first, err := r.SaveDocument(ctx, docs, "test", v, body, "", "actor")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ddl := `CREATE UNIQUE INDEX synthetic_save_failure ON revision_document_refs(document_hash)`
|
||||||
|
if stage == "outbox" {
|
||||||
|
ddl = `CREATE UNIQUE INDEX synthetic_save_failure ON activity_outbox(domain_uuid)`
|
||||||
|
}
|
||||||
|
if _, err := r.database.ExecContext(ctx, ddl); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.SaveDocument(ctx, docs, "test", v, append([]byte(`<p>change</p>`), body...), first.Revision.UUID, "actor"); !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("injected error ignored", err)
|
||||||
|
}
|
||||||
|
for _, table := range []string{"revisions", "revision_document_refs", "activity_outbox"} {
|
||||||
|
var n int
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM `+table).Scan(&n); err != nil || n != 1 {
|
||||||
|
t.Fatal("partial commit", table, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var last int64
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT last_sequence FROM activity_outbox_heads WHERE domain_uuid='test'`).Scan(&last); err != nil || last != 1 {
|
||||||
|
t.Fatal("sequence advanced on failure", err)
|
||||||
|
}
|
||||||
|
if _, err := r.database.ExecContext(ctx, `DROP INDEX synthetic_save_failure`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.SaveDocument(ctx, docs, "test", v, body, first.Revision.UUID, "actor"); err != nil {
|
||||||
|
t.Fatal("retry after rollback", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDocumentSavePersistenceFailureAndConcurrentEdit(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
docs, _, v := documentFixture(t, r)
|
||||||
|
body := []byte(`<img src="asset:image:cover">`)
|
||||||
|
for _, failing := range []faultDocuments{{Store: docs, putErr: io.ErrClosedPipe}, {Store: docs, verifyErr: geduldh.ErrHashMismatch}} {
|
||||||
|
if _, err := r.SaveDocument(ctx, failing, "test", v, body, "", "actor"); err == nil {
|
||||||
|
t.Fatal("Document failure ignored")
|
||||||
|
}
|
||||||
|
var n int
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM revisions`).Scan(&n); err != nil || n != 0 {
|
||||||
|
t.Fatal("failed persistence published revision", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
first, err := r.SaveDocument(ctx, docs, "test", v, body, "", "actor")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// The callback writes using a different transaction during Document I/O.
|
||||||
|
// It would deadlock if SaveDocument held SQL locks over the payload write.
|
||||||
|
race := faultDocuments{Store: docs, afterPut: func() {
|
||||||
|
peer, _ := New(r.database, backend)
|
||||||
|
competing := v
|
||||||
|
competing.DocumentHash = first.Revision.DocumentHash
|
||||||
|
if _, err := peer.AppendRevision(ctx, "test", competing, first.Revision.UUID); err != nil {
|
||||||
|
t.Fatal("I/O held metadata lock", err)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
if _, err := r.SaveDocument(ctx, race, "test", v, []byte("<p>stale</p>"), first.Revision.UUID, "actor"); !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("CAS not repeated after payload I/O", err)
|
||||||
|
}
|
||||||
|
var n int
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM activity_outbox`).Scan(&n); err != nil || n != 2 {
|
||||||
|
t.Fatal("conflicting write emitted event", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOutboxSequenceForConcurrentObjects(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
objects := make([]string, 6)
|
||||||
|
for i := range objects {
|
||||||
|
var err error
|
||||||
|
objects[i], err = r.CreatePage(ctx, "test", "/"+strings.Repeat("a", i+1))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errs := make(chan error, len(objects))
|
||||||
|
for _, id := range objects {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(id string) {
|
||||||
|
defer wg.Done()
|
||||||
|
peer, _ := New(r.database, backend)
|
||||||
|
_, err := peer.AppendRevision(ctx, "test", Revision{ObjectUUID: id, DocumentHash: hash(id), ContentType: "text/html"}, "")
|
||||||
|
errs <- err
|
||||||
|
}(id)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(errs)
|
||||||
|
for err := range errs {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
var min, max int64
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*),min(sequence),max(sequence) FROM activity_outbox`).Scan(&count, &min, &max); err != nil || count != 6 || min != 1 || max != 6 {
|
||||||
|
t.Fatal("invalid concurrent sequence", count, min, max, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A core-compatible schema is a rehearsal scope, not an application readiness
|
||||||
|
// claim. New application tables and security triggers always block core-only
|
||||||
|
// copying; unknown data must never be silently dropped as a "cache".
|
||||||
|
type PortabilityReport struct {
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
ApplicationReady bool `json:"application_ready"`
|
||||||
|
CoreCompatible bool `json:"core_compatible"`
|
||||||
|
Tables []TablePortability `json:"tables"`
|
||||||
|
Blockers []string `json:"blockers"`
|
||||||
|
}
|
||||||
|
type TablePortability struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Component string `json:"component"`
|
||||||
|
State string `json:"state"`
|
||||||
|
}
|
||||||
|
type tableSpec struct {
|
||||||
|
name string
|
||||||
|
columns []string
|
||||||
|
keys []string
|
||||||
|
identity bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explicit columns and primary-key order define an unambiguous streaming
|
||||||
|
// fingerprint and an FK-safe copy order. Migration ledgers stay backend-local.
|
||||||
|
var coreTables = []tableSpec{
|
||||||
|
{"objects", strings.Split("uuid,kind,created_at", ","), []string{"uuid"}, false},
|
||||||
|
{"object_origins", strings.Split("object_uuid,domain_uuid,created_at", ","), []string{"object_uuid"}, false},
|
||||||
|
{"paths", strings.Split("domain_uuid,path,object_uuid,created_at,is_primary", ","), []string{"domain_uuid", "path"}, false},
|
||||||
|
{"revisions", strings.Split(revisionColumns+",created_at,body", ","), []string{"uuid"}, false},
|
||||||
|
{"assets", strings.Split(assetColumns, ","), []string{"domain_uuid", "address"}, false},
|
||||||
|
{"asset_head_history", strings.Split("id,domain_uuid,address,action,document_hash,content_type,filename,size_bytes,actor_uuid,created_at_ms", ","), []string{"id"}, true},
|
||||||
|
{"revision_document_refs", []string{"revision_uuid", "document_hash"}, []string{"revision_uuid", "document_hash"}, false},
|
||||||
|
{"activity_outbox", strings.Split("uuid,domain_uuid,sequence,event_type,actor_uuid,target_kind,target_uuid,payload,idempotency_key,status,attempts,next_attempt_ms,last_error,created_at_ms,claimed_at_ms", ","), []string{"uuid"}, false},
|
||||||
|
{"activity_outbox_heads", []string{"domain_uuid", "event_type", "last_sequence"}, []string{"domain_uuid", "event_type"}, false},
|
||||||
|
}
|
||||||
|
|
||||||
|
func componentForTable(name string) string {
|
||||||
|
for _, prefix := range []string{"auth", "principal", "group", "membership", "task", "calendar", "event", "notification", "activity", "federation", "domain", "campus", "config", "import", "resource", "adapter", "user", "profile", "contact", "feed", "periodical", "search", "locality", "city"} {
|
||||||
|
if strings.HasPrefix(name, prefix) {
|
||||||
|
return prefix
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if name == "zones" || name == "spots" || strings.HasPrefix(name, "spot_") || strings.HasPrefix(name, "street_") || name == "topology_events" {
|
||||||
|
return "city"
|
||||||
|
}
|
||||||
|
return "unclassified"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) InspectPortability(ctx context.Context) (PortabilityReport, error) {
|
||||||
|
tx, err := r.database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead})
|
||||||
|
if err != nil {
|
||||||
|
return PortabilityReport{}, r.failure(err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
return r.inspectPortability(ctx, tx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) inspectPortability(ctx context.Context, tx *sql.Tx) (PortabilityReport, error) {
|
||||||
|
report := PortabilityReport{Scope: "portable-core-rehearsal-only", Tables: []TablePortability{}, Blockers: []string{}}
|
||||||
|
known := map[string]tableSpec{}
|
||||||
|
for _, s := range coreTables {
|
||||||
|
known[s.name] = s
|
||||||
|
}
|
||||||
|
query := `SELECT name,type FROM sqlite_master WHERE type IN ('table','view','trigger') AND substr(name,1,7)!='sqlite_' ORDER BY name`
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
query = `SELECT c.relname,CASE WHEN c.relkind IN ('r','p') THEN 'table' ELSE 'view' END FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() AND c.relkind IN ('r','p','v','m','f')
|
||||||
|
UNION ALL SELECT t.tgname,'trigger' FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() AND NOT t.tgisinternal
|
||||||
|
UNION ALL SELECT p.proname,'routine' FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname=current_schema()
|
||||||
|
UNION ALL SELECT r.rulename,'rule' FROM pg_rewrite r JOIN pg_class c ON c.oid=r.ev_class JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() AND r.rulename!='_RETURN'
|
||||||
|
UNION ALL SELECT c.relname,'sequence' FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() AND c.relkind='S' AND NOT EXISTS(SELECT 1 FROM pg_depend d JOIN pg_class t ON t.oid=d.refobjid JOIN pg_namespace tn ON tn.oid=t.relnamespace WHERE d.objid=c.oid AND d.classid='pg_class'::regclass AND d.refclassid='pg_class'::regclass AND tn.nspname=current_schema() AND t.relname='asset_head_history' AND d.deptype='i') ORDER BY 1`
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, query)
|
||||||
|
if err != nil {
|
||||||
|
return report, r.failure(err)
|
||||||
|
}
|
||||||
|
types := map[string]string{}
|
||||||
|
for rows.Next() {
|
||||||
|
var name, kind string
|
||||||
|
if err := rows.Scan(&name, &kind); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return report, r.failure(err)
|
||||||
|
}
|
||||||
|
if kind != "table" {
|
||||||
|
report.Blockers = append(report.Blockers, fmt.Sprintf("unported %s: %s", kind, name))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
types[name] = kind
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return report, r.failure(err)
|
||||||
|
}
|
||||||
|
names := make([]string, 0, len(types))
|
||||||
|
for name := range types {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
for _, name := range names {
|
||||||
|
kind := types[name]
|
||||||
|
if kind != "table" {
|
||||||
|
report.Blockers = append(report.Blockers, fmt.Sprintf("unported %s: %s", kind, name))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if name == "schema_migration_steps" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
item := TablePortability{Name: name, Component: componentForTable(name), State: "unported"}
|
||||||
|
if _, ok := known[name]; ok {
|
||||||
|
item.Component = "core-metadata"
|
||||||
|
item.State = "shape-pending"
|
||||||
|
} else {
|
||||||
|
report.Blockers = append(report.Blockers, "unported table: "+name)
|
||||||
|
}
|
||||||
|
report.Tables = append(report.Tables, item)
|
||||||
|
}
|
||||||
|
for _, spec := range coreTables {
|
||||||
|
if types[spec.name] != "table" {
|
||||||
|
report.Blockers = append(report.Blockers, "missing core table: "+spec.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if types["schema_migration_steps"] != "table" {
|
||||||
|
report.Blockers = append(report.Blockers, "missing portable migration ledger")
|
||||||
|
} else {
|
||||||
|
if err := r.inspectCoreHistory(ctx, tx, &report); err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range report.Tables {
|
||||||
|
item := &report.Tables[i]
|
||||||
|
spec, ok := known[item.Name]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
columns, err := r.tableColumns(ctx, tx, item.Name)
|
||||||
|
if err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
actual := map[string]bool{}
|
||||||
|
for _, c := range columns {
|
||||||
|
actual[c] = true
|
||||||
|
}
|
||||||
|
matches := len(actual) == len(spec.columns)
|
||||||
|
for _, c := range spec.columns {
|
||||||
|
matches = matches && actual[c]
|
||||||
|
}
|
||||||
|
if !matches {
|
||||||
|
item.State = "schema-drift"
|
||||||
|
report.Blockers = append(report.Blockers, "column mismatch: "+item.Name)
|
||||||
|
} else {
|
||||||
|
item.State = "core-shape-compatible"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := r.inspectCatalog(ctx, tx, &report); err != nil {
|
||||||
|
return report, err
|
||||||
|
}
|
||||||
|
sort.Strings(report.Blockers)
|
||||||
|
report.CoreCompatible = len(report.Blockers) == 0
|
||||||
|
// This core-only report does not certify full-application readiness. Use
|
||||||
|
// the Store application importer for the production migration inventory.
|
||||||
|
// ApplicationReady intentionally remains false here because non-core
|
||||||
|
// repositories, canonical files and worker state are outside this check.
|
||||||
|
return report, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) tableColumns(ctx context.Context, tx *sql.Tx, table string) ([]string, error) {
|
||||||
|
query := `SELECT name FROM pragma_table_info(` + r.p(1) + `) ORDER BY cid`
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
query = `SELECT column_name FROM information_schema.columns WHERE table_schema=current_schema() AND table_name=$1 ORDER BY ordinal_position`
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, query, table)
|
||||||
|
if err != nil {
|
||||||
|
return nil, r.failure(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []string
|
||||||
|
for rows.Next() {
|
||||||
|
var name string
|
||||||
|
if err := rows.Scan(&name); err != nil {
|
||||||
|
return nil, r.failure(err)
|
||||||
|
}
|
||||||
|
out = append(out, name)
|
||||||
|
}
|
||||||
|
return out, r.failure(rows.Err())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) inspectCoreHistory(ctx context.Context, tx *sql.Tx, report *PortabilityReport) error {
|
||||||
|
sqliteSteps, pgSteps := r.migrationDefinitions()
|
||||||
|
checksums := map[int]string{}
|
||||||
|
names := map[int]string{}
|
||||||
|
add := func(version int, name string, step any) {
|
||||||
|
data, _ := json.Marshal(step)
|
||||||
|
sum := sha256.Sum256(data)
|
||||||
|
checksums[version] = hex.EncodeToString(sum[:])
|
||||||
|
names[version] = name
|
||||||
|
}
|
||||||
|
for _, s := range sqliteSteps {
|
||||||
|
add(s.Version, s.Name, s)
|
||||||
|
}
|
||||||
|
for _, s := range pgSteps {
|
||||||
|
add(s.Version, s.Name, s)
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT component,version,name,checksum FROM schema_migration_steps ORDER BY component,version`)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
applied := 0
|
||||||
|
for rows.Next() {
|
||||||
|
var component, name, checksum string
|
||||||
|
var version int
|
||||||
|
if err := rows.Scan(&component, &version, &name, &checksum); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if component != "core-metadata" {
|
||||||
|
report.Blockers = append(report.Blockers, "unported migration component: "+component)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if version != applied+1 || names[version] != name || checksums[version] != checksum {
|
||||||
|
report.Blockers = append(report.Blockers, "portable migration history mismatch")
|
||||||
|
}
|
||||||
|
applied++
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if applied != len(checksums) {
|
||||||
|
report.Blockers = append(report.Blockers, "portable migrations are not current")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Only the owned portable-core schema is certified here. Existing application
|
||||||
|
// tables are NOT adopted by translating arbitrary SQLite DDL to PostgreSQL.
|
||||||
|
func (r *Repository) inspectCatalog(ctx context.Context, tx *sql.Tx, report *PortabilityReport) error {
|
||||||
|
if r.backend == SQLite {
|
||||||
|
return r.inspectSQLiteCatalog(ctx, tx, report)
|
||||||
|
}
|
||||||
|
return r.inspectPostgreSQLCatalog(ctx, tx, report)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) inspectSQLiteCatalog(ctx context.Context, tx *sql.Tx, report *PortabilityReport) error {
|
||||||
|
steps, _ := r.migrationDefinitions()
|
||||||
|
expected := map[string]string{}
|
||||||
|
for _, step := range steps {
|
||||||
|
for _, statement := range step.Statements {
|
||||||
|
fields := strings.Fields(statement)
|
||||||
|
if len(fields) > 2 && fields[0] == "CREATE" && (fields[1] == "TABLE" || fields[1] == "INDEX") {
|
||||||
|
name := strings.SplitN(fields[2], "(", 2)[0]
|
||||||
|
expected[name] = strings.TrimSpace(statement)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT name,type,sql FROM sqlite_master WHERE type IN ('table','index') AND sql IS NOT NULL AND name!='schema_migration_steps' AND substr(name,1,7)!='sqlite_' ORDER BY name`)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for rows.Next() {
|
||||||
|
var name, kind, ddl string
|
||||||
|
if err := rows.Scan(&name, &kind, &ddl); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if wanted, ok := expected[name]; ok {
|
||||||
|
seen[name] = true
|
||||||
|
if wanted != strings.TrimSpace(ddl) {
|
||||||
|
report.Blockers = append(report.Blockers, "catalog mismatch: "+name)
|
||||||
|
}
|
||||||
|
} else if kind == "index" {
|
||||||
|
report.Blockers = append(report.Blockers, "unported index: "+name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
for name := range expected {
|
||||||
|
if !seen[name] {
|
||||||
|
report.Blockers = append(report.Blockers, "missing catalog object: "+name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func numericColumn(column string) bool {
|
||||||
|
switch column {
|
||||||
|
case "created_at", "created_at_ms", "updated_at_ms", "is_primary", "size_bytes", "id", "sequence", "attempts", "next_attempt_ms", "claimed_at_ms", "last_sequence":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) inspectPostgreSQLCatalog(ctx context.Context, tx *sql.Tx, report *PortabilityReport) error {
|
||||||
|
var ledgerPolicy bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT COALESCE(bool_or(c.relrowsecurity OR c.relforcerowsecurity OR EXISTS(SELECT 1 FROM pg_policy p WHERE p.polrelid=c.oid)),false) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() AND c.relname='schema_migration_steps'`).Scan(&ledgerPolicy); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if ledgerPolicy {
|
||||||
|
report.Blockers = append(report.Blockers, "unported policy: schema_migration_steps")
|
||||||
|
}
|
||||||
|
defaults := map[string]string{
|
||||||
|
"paths.is_primary": "0", "revisions.filename": "''::text", "revisions.message": "''::text", "revisions.body": "''::text", "assets.filename": "''::text",
|
||||||
|
"activity_outbox.actor_uuid": "''::text", "activity_outbox.target_kind": "''::text", "activity_outbox.target_uuid": "''::text", "activity_outbox.payload": "''::text", "activity_outbox.status": "'pending'::text", "activity_outbox.attempts": "0", "activity_outbox.last_error": "''::text", "activity_outbox.claimed_at_ms": "0",
|
||||||
|
}
|
||||||
|
constraints := map[string][]string{
|
||||||
|
"objects": {"PRIMARY KEY (uuid)"},
|
||||||
|
"object_origins": {"PRIMARY KEY (object_uuid)", "FOREIGN KEY (object_uuid) REFERENCES objects(uuid)"},
|
||||||
|
"paths": {"PRIMARY KEY (domain_uuid, path)", "FOREIGN KEY (object_uuid) REFERENCES objects(uuid)"},
|
||||||
|
"revisions": {"PRIMARY KEY (uuid)", "FOREIGN KEY (object_uuid) REFERENCES objects(uuid)"},
|
||||||
|
"assets": {"PRIMARY KEY (domain_uuid, address)", "UNIQUE (object_uuid)", "FOREIGN KEY (object_uuid) REFERENCES objects(uuid)", "CHECK ((size_bytes >= 0))"},
|
||||||
|
"asset_head_history": {"PRIMARY KEY (id)", "CHECK ((size_bytes >= 0))"},
|
||||||
|
"revision_document_refs": {"PRIMARY KEY (revision_uuid, document_hash)", "FOREIGN KEY (revision_uuid) REFERENCES revisions(uuid)"},
|
||||||
|
"activity_outbox": {"PRIMARY KEY (uuid)", "UNIQUE (domain_uuid, sequence)", "UNIQUE (domain_uuid, idempotency_key)"},
|
||||||
|
"activity_outbox_heads": {"PRIMARY KEY (domain_uuid, event_type)"},
|
||||||
|
}
|
||||||
|
identityTablePresent := false
|
||||||
|
for _, spec := range coreTables {
|
||||||
|
var ordinary bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT c.relkind='r' AND c.relpersistence='p' AND NOT c.relrowsecurity AND NOT c.relforcerowsecurity AND NOT EXISTS(SELECT 1 FROM pg_policy p WHERE p.polrelid=c.oid) AND NOT EXISTS(SELECT 1 FROM pg_inherits x WHERE x.inhrelid=c.oid OR x.inhparent=c.oid) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() AND c.relname=$1`, spec.name).Scan(&ordinary); err != nil {
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
report.Blockers = append(report.Blockers, "missing table: "+spec.name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if !ordinary {
|
||||||
|
report.Blockers = append(report.Blockers, "unported policy or table mode: "+spec.name)
|
||||||
|
}
|
||||||
|
if spec.identity {
|
||||||
|
identityTablePresent = true
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT a.attname,format_type(a.atttypid,a.atttypmod),a.attnotnull,COALESCE(pg_get_expr(d.adbin,d.adrelid),''),a.attidentity,a.attgenerated,COALESCE(col.collname,'') FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace LEFT JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum LEFT JOIN pg_collation col ON col.oid=a.attcollation WHERE n.nspname=current_schema() AND c.relname=$1 AND a.attnum>0 AND NOT a.attisdropped`, spec.name)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
for rows.Next() {
|
||||||
|
var name, kind, def, identity, generated, collation string
|
||||||
|
var required bool
|
||||||
|
if err := rows.Scan(&name, &kind, &required, &def, &identity, &generated, &collation); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
wantType := "text"
|
||||||
|
if numericColumn(name) {
|
||||||
|
wantType = "bigint"
|
||||||
|
}
|
||||||
|
if name == "is_primary" || name == "attempts" {
|
||||||
|
wantType = "integer"
|
||||||
|
}
|
||||||
|
wantIdentity := ""
|
||||||
|
if spec.identity && name == "id" {
|
||||||
|
wantIdentity = "a"
|
||||||
|
}
|
||||||
|
wantCollation := ""
|
||||||
|
if wantType == "text" {
|
||||||
|
wantCollation = "default"
|
||||||
|
}
|
||||||
|
if spec.name == "paths" && name == "path" || spec.name == "assets" && name == "address" {
|
||||||
|
wantCollation = "C"
|
||||||
|
}
|
||||||
|
if kind != wantType || !required || def != defaults[spec.name+"."+name] || identity != wantIdentity || generated != "" || collation != wantCollation {
|
||||||
|
report.Blockers = append(report.Blockers, fmt.Sprintf("column contract mismatch: %s.%s", spec.name, name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
rows, err = tx.QueryContext(ctx, `SELECT pg_get_constraintdef(c.oid),c.convalidated,c.condeferrable,c.condeferred FROM pg_constraint c JOIN pg_class t ON t.oid=c.conrelid JOIN pg_namespace n ON n.oid=t.relnamespace WHERE n.nspname=current_schema() AND t.relname=$1`, spec.name)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
wanted := map[string]bool{}
|
||||||
|
for _, s := range constraints[spec.name] {
|
||||||
|
wanted[s] = true
|
||||||
|
}
|
||||||
|
actual := map[string]bool{}
|
||||||
|
matches := true
|
||||||
|
constraintCount := 0
|
||||||
|
for rows.Next() {
|
||||||
|
constraintCount++
|
||||||
|
var def string
|
||||||
|
var valid, deferable, deferred bool
|
||||||
|
if err := rows.Scan(&def, &valid, &deferable, &deferred); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
actual[def] = true
|
||||||
|
matches = matches && valid && !deferable && !deferred && wanted[def]
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if !matches || len(actual) != len(wanted) || constraintCount != len(wanted) {
|
||||||
|
report.Blockers = append(report.Blockers, "constraint contract mismatch: "+spec.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var schema string
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT quote_ident(current_schema())`).Scan(&schema); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
indexes := map[string]string{
|
||||||
|
"idx_paths_domain_object": "paths USING btree (domain_uuid, object_uuid)",
|
||||||
|
"idx_revisions_metadata_head": "revisions USING btree (object_uuid, lang, created_at_ms DESC, uuid DESC)",
|
||||||
|
"idx_asset_metadata_history": "asset_head_history USING btree (domain_uuid, address, id)",
|
||||||
|
"idx_metadata_document_refs": "revision_document_refs USING btree (document_hash, revision_uuid)",
|
||||||
|
"idx_metadata_outbox_pending": "activity_outbox USING btree (status, next_attempt_ms, domain_uuid, sequence)",
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT i.relname,pg_get_indexdef(i.oid),x.indisvalid,x.indisready FROM pg_index x JOIN pg_class i ON i.oid=x.indexrelid JOIN pg_class t ON t.oid=x.indrelid JOIN pg_namespace n ON n.oid=t.relnamespace WHERE n.nspname=current_schema() AND t.relname!='schema_migration_steps' AND NOT EXISTS(SELECT 1 FROM pg_constraint con WHERE con.conindid=i.oid)`)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for rows.Next() {
|
||||||
|
var name, def string
|
||||||
|
var valid, ready bool
|
||||||
|
if err := rows.Scan(&name, &def, &valid, &ready); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
suffix, ok := indexes[name]
|
||||||
|
if !ok {
|
||||||
|
report.Blockers = append(report.Blockers, "unported index: "+name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[name] = true
|
||||||
|
if def != "CREATE INDEX "+name+" ON "+schema+"."+suffix || !valid || !ready {
|
||||||
|
report.Blockers = append(report.Blockers, "index contract mismatch: "+name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
for name := range indexes {
|
||||||
|
if !seen[name] {
|
||||||
|
report.Blockers = append(report.Blockers, "missing index: "+name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var sequenceMatches bool
|
||||||
|
if identityTablePresent {
|
||||||
|
err = tx.QueryRowContext(ctx, `SELECT seqstart=1 AND seqincrement=1 AND seqmin=1 AND seqmax=9223372036854775807 AND seqcache=1 AND NOT seqcycle FROM pg_sequence WHERE seqrelid=pg_get_serial_sequence('asset_head_history','id')::regclass`).Scan(&sequenceMatches)
|
||||||
|
}
|
||||||
|
if err != nil && err != sql.ErrNoRows {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if !sequenceMatches {
|
||||||
|
report.Blockers = append(report.Blockers, "identity sequence contract mismatch: asset_head_history.id")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPortabilityRejectsIndexDrift(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
for _, change := range []string{"missing", "wrong", "extra"} {
|
||||||
|
t.Run(string(backend)+"/"+change, func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
if change != "extra" {
|
||||||
|
if _, err := r.database.ExecContext(ctx, `DROP INDEX idx_paths_domain_object`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if change == "wrong" {
|
||||||
|
if _, err := r.database.ExecContext(ctx, `CREATE INDEX idx_paths_domain_object ON paths(object_uuid)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if change == "extra" {
|
||||||
|
if _, err := r.database.ExecContext(ctx, `CREATE UNIQUE INDEX unported_unique_rule ON paths(object_uuid)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report, err := r.InspectPortability(ctx)
|
||||||
|
if err != nil || report.CoreCompatible {
|
||||||
|
t.Fatal("index drift accepted", err, report)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostgreSQLPortabilityRejectsContractDrift(t *testing.T) {
|
||||||
|
changes := map[string]string{
|
||||||
|
"type": `ALTER TABLE assets ALTER COLUMN size_bytes TYPE INTEGER`,
|
||||||
|
"default": `ALTER TABLE revisions ALTER COLUMN message SET DEFAULT 'different'`,
|
||||||
|
"nullable": `ALTER TABLE revisions ALTER COLUMN content_type DROP NOT NULL`,
|
||||||
|
"foreign-key": `ALTER TABLE paths DROP CONSTRAINT paths_object_uuid_fkey`,
|
||||||
|
"collation": `ALTER TABLE paths ALTER COLUMN path TYPE TEXT COLLATE "default"`,
|
||||||
|
"identity-mode": `ALTER TABLE asset_head_history ALTER COLUMN id SET GENERATED BY DEFAULT`,
|
||||||
|
"identity-drop": `ALTER TABLE asset_head_history ALTER COLUMN id DROP IDENTITY`,
|
||||||
|
"missing-table": `DROP TABLE asset_head_history`,
|
||||||
|
"identity-step": `ALTER TABLE asset_head_history ALTER COLUMN id SET INCREMENT BY 7`,
|
||||||
|
"rls": `ALTER TABLE objects ENABLE ROW LEVEL SECURITY`,
|
||||||
|
"ledger-rls": `ALTER TABLE schema_migration_steps ENABLE ROW LEVEL SECURITY`,
|
||||||
|
"routine": `CREATE FUNCTION unported_routine() RETURNS INTEGER LANGUAGE SQL AS 'SELECT 1'`,
|
||||||
|
"sequence": `CREATE SEQUENCE unported_counter`,
|
||||||
|
"rule": `CREATE RULE unported_rule AS ON DELETE TO paths DO INSTEAD NOTHING`,
|
||||||
|
"duplicate-fk": `ALTER TABLE paths ADD CONSTRAINT duplicate_fk FOREIGN KEY (object_uuid) REFERENCES objects(uuid)`,
|
||||||
|
}
|
||||||
|
for name, q := range changes {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
r := testRepository(t, PostgreSQL)
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := r.database.ExecContext(ctx, q); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
report, err := r.InspectPortability(ctx)
|
||||||
|
if err != nil || report.CoreCompatible {
|
||||||
|
t.Fatal("contract drift accepted", err, report)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,471 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/binary"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
hashpkg "hash"
|
||||||
|
"math"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"pageswiki/internal/geduldh"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrMigrationBlocked = errors.New("metadata migration blocked; inspect portability report")
|
||||||
|
ErrDestinationNotEmpty = errors.New("metadata migration destination is not empty")
|
||||||
|
ErrIntegrity = errors.New("metadata integrity check failed")
|
||||||
|
)
|
||||||
|
|
||||||
|
type TableFingerprint struct {
|
||||||
|
Table string `json:"table"`
|
||||||
|
Rows int64 `json:"rows"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
}
|
||||||
|
type CoreSnapshot struct {
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
Tables []TableFingerprint `json:"tables"`
|
||||||
|
IdentityNext int64 `json:"asset_history_identity_next"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
}
|
||||||
|
type RehearsalOptions struct {
|
||||||
|
// Caller asserts that all writers and GC are stopped for both instances.
|
||||||
|
// A SQL snapshot alone is not a cross-store or online migration protocol.
|
||||||
|
Offline bool
|
||||||
|
Documents geduldh.Store
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloneCoreForRehearsal copies only a compatible portable core into an already
|
||||||
|
// initialized, empty staging schema. It is deliberately not a production
|
||||||
|
// migration entry point. Unknown tables/triggers/views/columns/ledger entries
|
||||||
|
// block copying rather than silently losing application data or permissions.
|
||||||
|
// Canonical payloads are verified in the caller's retained Document store;
|
||||||
|
// calendar files, secrets, application configuration and blobs are NOT copied.
|
||||||
|
func CloneCoreForRehearsal(ctx context.Context, source, destination *Repository, options RehearsalOptions) (CoreSnapshot, error) {
|
||||||
|
if !options.Offline || options.Documents == nil || source == nil || destination == nil || source.database == destination.database {
|
||||||
|
return CoreSnapshot{}, ErrMigrationBlocked
|
||||||
|
}
|
||||||
|
if same, err := sameDatabase(ctx, source, destination); err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
} else if same {
|
||||||
|
return CoreSnapshot{}, ErrMigrationBlocked
|
||||||
|
}
|
||||||
|
src, err := source.database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead})
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, source.failure(err)
|
||||||
|
}
|
||||||
|
defer src.Rollback()
|
||||||
|
report, err := source.inspectPortability(ctx, src)
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
if !report.CoreCompatible {
|
||||||
|
return CoreSnapshot{}, ErrMigrationBlocked
|
||||||
|
}
|
||||||
|
if err := source.verifyCoreRelations(ctx, src); err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
// Reject an occupied/incompatible destination before verifying a large
|
||||||
|
// Document store. Recheck while holding destination locks before copying.
|
||||||
|
preflight, err := destination.database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead})
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, destination.failure(err)
|
||||||
|
}
|
||||||
|
err = destination.checkEmpty(ctx, preflight)
|
||||||
|
_ = preflight.Rollback()
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
if err := source.verifyDocuments(ctx, src, options.Documents); err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
var result CoreSnapshot
|
||||||
|
err = destination.write(ctx, "migration/portable-core-rehearsal", func(dst *sql.Tx) error {
|
||||||
|
if destination.backend == PostgreSQL {
|
||||||
|
// Lock all tables, not just a cooperative advisory key: an accidental
|
||||||
|
// concurrent writer must not race the empty-destination check.
|
||||||
|
names := []string{`"schema_migration_steps"`}
|
||||||
|
for _, s := range coreTables {
|
||||||
|
names = append(names, quote(s.name))
|
||||||
|
}
|
||||||
|
if _, err := dst.ExecContext(ctx, `LOCK TABLE `+strings.Join(names, ",")+` IN ACCESS EXCLUSIVE MODE`); err != nil {
|
||||||
|
return destination.failure(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := destination.checkEmpty(ctx, dst); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var expected []TableFingerprint
|
||||||
|
for _, spec := range coreTables {
|
||||||
|
fingerprint, err := source.streamTable(ctx, src, spec, func(values []any) error {
|
||||||
|
marks := make([]string, len(values))
|
||||||
|
for i := range values {
|
||||||
|
marks[i] = destination.p(i + 1)
|
||||||
|
}
|
||||||
|
q := `INSERT INTO ` + quote(spec.name) + ` (` + quoted(spec.columns) + `)`
|
||||||
|
if spec.identity && destination.backend == PostgreSQL {
|
||||||
|
q += ` OVERRIDING SYSTEM VALUE`
|
||||||
|
}
|
||||||
|
_, err := dst.ExecContext(ctx, q+` VALUES (`+strings.Join(marks, ",")+`)`, values...)
|
||||||
|
return destination.failure(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
expected = append(expected, fingerprint)
|
||||||
|
}
|
||||||
|
if err := destination.verifyCoreRelations(ctx, dst); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
next, err := source.identityNext(ctx, src)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := destination.restoreIdentity(ctx, dst, next); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
actual, err := destination.fingerprint(ctx, dst)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
want := snapshot(expected, next)
|
||||||
|
if want.SHA256 != actual.SHA256 {
|
||||||
|
return ErrIntegrity
|
||||||
|
}
|
||||||
|
result = actual
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FingerprintCore reads a single snapshot and never mutates the database. It
|
||||||
|
// identifies metadata content, not a backup of canonical payloads or secrets.
|
||||||
|
func (r *Repository) FingerprintCore(ctx context.Context) (CoreSnapshot, error) {
|
||||||
|
tx, err := r.database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead})
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, r.failure(err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
report, err := r.inspectPortability(ctx, tx)
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
if !report.CoreCompatible {
|
||||||
|
return CoreSnapshot{}, ErrMigrationBlocked
|
||||||
|
}
|
||||||
|
if err := r.verifyCoreRelations(ctx, tx); err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
return r.fingerprint(ctx, tx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) fingerprint(ctx context.Context, tx *sql.Tx) (CoreSnapshot, error) {
|
||||||
|
var tables []TableFingerprint
|
||||||
|
for _, spec := range coreTables {
|
||||||
|
f, err := r.streamTable(ctx, tx, spec, nil)
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
tables = append(tables, f)
|
||||||
|
}
|
||||||
|
next, err := r.identityNext(ctx, tx)
|
||||||
|
if err != nil {
|
||||||
|
return CoreSnapshot{}, err
|
||||||
|
}
|
||||||
|
return snapshot(tables, next), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func snapshot(tables []TableFingerprint, next int64) CoreSnapshot {
|
||||||
|
data, _ := json.Marshal(struct {
|
||||||
|
Tables []TableFingerprint
|
||||||
|
IdentityNext int64
|
||||||
|
}{tables, next})
|
||||||
|
sum := sha256.Sum256(data)
|
||||||
|
return CoreSnapshot{Scope: "portable-core-rehearsal-only", Tables: tables, IdentityNext: next, SHA256: hex.EncodeToString(sum[:])}
|
||||||
|
}
|
||||||
|
|
||||||
|
func quote(s string) string { return `"` + strings.ReplaceAll(s, `"`, `""`) + `"` }
|
||||||
|
func quoted(names []string) string {
|
||||||
|
parts := make([]string, len(names))
|
||||||
|
for i, n := range names {
|
||||||
|
parts[i] = quote(n)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ",")
|
||||||
|
}
|
||||||
|
func frame(h hashpkg.Hash, data []byte) {
|
||||||
|
var size [8]byte
|
||||||
|
binary.BigEndian.PutUint64(size[:], uint64(len(data)))
|
||||||
|
h.Write(size[:])
|
||||||
|
h.Write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) streamTable(ctx context.Context, tx *sql.Tx, spec tableSpec, consume func([]any) error) (TableFingerprint, error) {
|
||||||
|
order := make([]string, len(spec.keys))
|
||||||
|
for i, k := range spec.keys {
|
||||||
|
order[i] = quote(k)
|
||||||
|
if !spec.identity {
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
order[i] += ` COLLATE "C"`
|
||||||
|
} else {
|
||||||
|
order[i] += ` COLLATE BINARY`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT `+quoted(spec.columns)+` FROM `+quote(spec.name)+` ORDER BY `+strings.Join(order, ","))
|
||||||
|
if err != nil {
|
||||||
|
return TableFingerprint{}, r.failure(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
h := sha256.New()
|
||||||
|
frame(h, []byte(spec.name))
|
||||||
|
data, _ := json.Marshal(spec.columns)
|
||||||
|
frame(h, data)
|
||||||
|
var count int64
|
||||||
|
for rows.Next() {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return TableFingerprint{}, err
|
||||||
|
}
|
||||||
|
values := make([]any, len(spec.columns))
|
||||||
|
pointers := make([]any, len(values))
|
||||||
|
for i := range values {
|
||||||
|
pointers[i] = &values[i]
|
||||||
|
}
|
||||||
|
if err := rows.Scan(pointers...); err != nil {
|
||||||
|
return TableFingerprint{}, r.failure(err)
|
||||||
|
}
|
||||||
|
for i, v := range values {
|
||||||
|
numeric := numericColumn(spec.columns[i])
|
||||||
|
switch value := v.(type) {
|
||||||
|
case string:
|
||||||
|
if numeric {
|
||||||
|
return TableFingerprint{}, fmt.Errorf("%w: noninteger in %s.%s", ErrIntegrity, spec.name, spec.columns[i])
|
||||||
|
}
|
||||||
|
if !utf8.ValidString(value) || strings.ContainsRune(value, 0) {
|
||||||
|
return TableFingerprint{}, fmt.Errorf("%w: nonportable text in %s.%s", ErrIntegrity, spec.name, spec.columns[i])
|
||||||
|
}
|
||||||
|
if (spec.columns[i] == "document_hash" || spec.columns[i] == "head_document_hash") && !validHash(value) {
|
||||||
|
return TableFingerprint{}, fmt.Errorf("%w: invalid hash in %s", ErrIntegrity, spec.name)
|
||||||
|
}
|
||||||
|
case int64:
|
||||||
|
if !numeric {
|
||||||
|
return TableFingerprint{}, fmt.Errorf("%w: nontext in %s.%s", ErrIntegrity, spec.name, spec.columns[i])
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return TableFingerprint{}, fmt.Errorf("%w: unsupported value type in %s.%s", ErrIntegrity, spec.name, spec.columns[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(values)
|
||||||
|
if err != nil {
|
||||||
|
return TableFingerprint{}, ErrIntegrity
|
||||||
|
}
|
||||||
|
frame(h, data)
|
||||||
|
if consume != nil {
|
||||||
|
if err := consume(values); err != nil {
|
||||||
|
return TableFingerprint{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return TableFingerprint{}, r.failure(err)
|
||||||
|
}
|
||||||
|
return TableFingerprint{Table: spec.name, Rows: count, SHA256: hex.EncodeToString(h.Sum(nil))}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) verifyCoreRelations(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
checks := []struct{ name, query string }{
|
||||||
|
{"object origin", `SELECT 1 FROM objects o WHERE NOT EXISTS(SELECT 1 FROM object_origins x WHERE x.object_uuid=o.uuid) LIMIT 1`},
|
||||||
|
{"origin object", `SELECT 1 FROM object_origins x WHERE NOT EXISTS(SELECT 1 FROM objects o WHERE o.uuid=x.object_uuid) LIMIT 1`},
|
||||||
|
{"path object", `SELECT 1 FROM paths p WHERE NOT EXISTS(SELECT 1 FROM objects o WHERE o.uuid=p.object_uuid) LIMIT 1`},
|
||||||
|
{"revision object", `SELECT 1 FROM revisions r WHERE NOT EXISTS(SELECT 1 FROM objects o WHERE o.uuid=r.object_uuid) LIMIT 1`},
|
||||||
|
{"asset object", `SELECT 1 FROM assets a WHERE NOT EXISTS(SELECT 1 FROM objects o WHERE o.uuid=a.object_uuid) LIMIT 1`},
|
||||||
|
{"revision reference", `SELECT 1 FROM revision_document_refs x WHERE NOT EXISTS(SELECT 1 FROM revisions r WHERE r.uuid=x.revision_uuid) LIMIT 1`},
|
||||||
|
{"outbox watermark", `SELECT 1 FROM activity_outbox o WHERE o.sequence<1 OR NOT EXISTS(SELECT 1 FROM activity_outbox_heads h WHERE h.domain_uuid=o.domain_uuid AND h.event_type=o.event_type AND h.last_sequence>=o.sequence) LIMIT 1`},
|
||||||
|
{"revision event", `SELECT 1 FROM activity_outbox o WHERE o.event_type='revision.created' AND NOT EXISTS(SELECT 1 FROM revisions r WHERE r.uuid=o.target_uuid) LIMIT 1`},
|
||||||
|
{"asset history id", `SELECT 1 FROM asset_head_history WHERE id<1 LIMIT 1`},
|
||||||
|
}
|
||||||
|
for _, check := range checks {
|
||||||
|
var found int
|
||||||
|
err := tx.QueryRowContext(ctx, check.query).Scan(&found)
|
||||||
|
if err == nil {
|
||||||
|
return fmt.Errorf("%w: %s", ErrIntegrity, check.name)
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) verifyDocuments(ctx context.Context, tx *sql.Tx, documents geduldh.Store) error {
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT document_hash FROM revisions UNION SELECT head_document_hash FROM assets UNION SELECT document_hash FROM asset_head_history UNION SELECT document_hash FROM revision_document_refs ORDER BY 1`)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var hash string
|
||||||
|
if err := rows.Scan(&hash); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if !validHash(hash) {
|
||||||
|
return ErrIntegrity
|
||||||
|
}
|
||||||
|
if err := documents.Verify(ctx, hash); err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%w: Document verification failed", ErrIntegrity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r.failure(rows.Err())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) checkEmpty(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
report, err := r.inspectPortability(ctx, tx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !report.CoreCompatible {
|
||||||
|
return ErrMigrationBlocked
|
||||||
|
}
|
||||||
|
for _, s := range coreTables {
|
||||||
|
var occupied bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM `+quote(s.name)+`)`).Scan(&occupied); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if occupied {
|
||||||
|
return ErrDestinationNotEmpty
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) identityNext(ctx context.Context, tx *sql.Tx) (int64, error) {
|
||||||
|
var max sql.NullInt64
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT max(id) FROM asset_head_history`).Scan(&max); err != nil {
|
||||||
|
return 0, r.failure(err)
|
||||||
|
}
|
||||||
|
if max.Int64 < 0 || max.Int64 == math.MaxInt64 {
|
||||||
|
return 0, ErrIntegrity
|
||||||
|
}
|
||||||
|
next := max.Int64 + 1
|
||||||
|
if r.backend == SQLite {
|
||||||
|
var seq sql.NullInt64
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT max(seq) FROM sqlite_sequence WHERE name='asset_head_history'`).Scan(&seq); err != nil {
|
||||||
|
return 0, r.failure(err)
|
||||||
|
}
|
||||||
|
if seq.Int64 < 0 || seq.Int64 == math.MaxInt64 {
|
||||||
|
return 0, ErrIntegrity
|
||||||
|
}
|
||||||
|
if seq.Int64+1 > next {
|
||||||
|
next = seq.Int64 + 1
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var schema, name string
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT n.nspname,c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE c.oid=pg_get_serial_sequence('asset_head_history','id')::regclass`).Scan(&schema, &name); err != nil {
|
||||||
|
return 0, r.failure(err)
|
||||||
|
}
|
||||||
|
var last int64
|
||||||
|
var called bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT last_value,is_called FROM `+quote(schema)+`.`+quote(name)).Scan(&last, &called); err != nil {
|
||||||
|
return 0, r.failure(err)
|
||||||
|
}
|
||||||
|
if last < 1 || last == math.MaxInt64 {
|
||||||
|
return 0, ErrIntegrity
|
||||||
|
}
|
||||||
|
if called {
|
||||||
|
last++
|
||||||
|
}
|
||||||
|
if last > next {
|
||||||
|
next = last
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) restoreIdentity(ctx context.Context, tx *sql.Tx, next int64) error {
|
||||||
|
if next < 1 {
|
||||||
|
return ErrIntegrity
|
||||||
|
}
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
// RESTART rolls back with the transaction; setval would not.
|
||||||
|
_, err := tx.ExecContext(ctx, `ALTER TABLE asset_head_history ALTER COLUMN id RESTART WITH `+strconv.FormatInt(next, 10))
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
result, err := tx.ExecContext(ctx, `UPDATE sqlite_sequence SET seq=? WHERE name='asset_head_history'`, next-1)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
n, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO sqlite_sequence(name,seq) VALUES ('asset_head_history',?)`, next-1)
|
||||||
|
}
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameDatabase(ctx context.Context, a, b *Repository) (bool, error) {
|
||||||
|
if a.backend != b.backend {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if a.backend == SQLite {
|
||||||
|
path := func(r *Repository) (string, error) {
|
||||||
|
var seq int
|
||||||
|
var name, file string
|
||||||
|
err := r.database.QueryRowContext(ctx, `SELECT seq,name,file FROM pragma_database_list WHERE name='main'`).Scan(&seq, &name, &file)
|
||||||
|
if err != nil {
|
||||||
|
return "", r.failure(err)
|
||||||
|
}
|
||||||
|
if file == "" {
|
||||||
|
return "", ErrMigrationBlocked
|
||||||
|
}
|
||||||
|
return file, nil
|
||||||
|
}
|
||||||
|
x, err := path(a)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
y, err := path(b)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
xInfo, err := os.Stat(x)
|
||||||
|
if err != nil {
|
||||||
|
return false, ErrMigrationBlocked
|
||||||
|
}
|
||||||
|
yInfo, err := os.Stat(y)
|
||||||
|
if err != nil {
|
||||||
|
return false, ErrMigrationBlocked
|
||||||
|
}
|
||||||
|
return os.SameFile(xInfo, yInfo), nil
|
||||||
|
}
|
||||||
|
type identity struct{ database, schema, start string }
|
||||||
|
read := func(r *Repository) (identity, error) {
|
||||||
|
var i identity
|
||||||
|
err := r.database.QueryRowContext(ctx, `SELECT current_database(),current_schema(),extract(epoch from pg_postmaster_start_time())::text`).Scan(&i.database, &i.schema, &i.start)
|
||||||
|
return i, r.failure(err)
|
||||||
|
}
|
||||||
|
x, err := read(a)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
y, err := read(b)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return x == y, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
"pageswiki/internal/geduldh"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPortabilityIsFailClosed(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
for _, change := range []string{"table", "view", "column", "history", "component"} {
|
||||||
|
t.Run(string(backend)+"/"+change, func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
report, err := r.InspectPortability(ctx)
|
||||||
|
if err != nil || !report.CoreCompatible || report.ApplicationReady {
|
||||||
|
t.Fatal("fresh core readiness", err, report)
|
||||||
|
}
|
||||||
|
q := map[string]string{
|
||||||
|
"table": `CREATE TABLE auth_private_users(secret TEXT)`,
|
||||||
|
"view": `CREATE VIEW private_view AS SELECT uuid FROM objects`,
|
||||||
|
"column": `ALTER TABLE objects ADD COLUMN unexpected TEXT`,
|
||||||
|
"history": `UPDATE schema_migration_steps SET checksum='tampered' WHERE version=1`,
|
||||||
|
"component": `INSERT INTO schema_migration_steps(component,version,name,checksum,applied_at_ms) VALUES ('future',1,'other','unknown',1)`,
|
||||||
|
}[change]
|
||||||
|
if _, err := r.database.ExecContext(ctx, q); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
report, err = r.InspectPortability(ctx)
|
||||||
|
if err != nil || report.CoreCompatible || len(report.Blockers) == 0 {
|
||||||
|
t.Fatal("unsupported state accepted", err, report)
|
||||||
|
}
|
||||||
|
if _, err := r.FingerprintCore(ctx); !errors.Is(err, ErrMigrationBlocked) {
|
||||||
|
t.Fatal("unsupported state fingerprinted as portable", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPortabilityDoesNotHideSameNamedTrigger(t *testing.T) {
|
||||||
|
r := testRepository(t, SQLite)
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := r.database.ExecContext(ctx, `CREATE TRIGGER objects AFTER UPDATE ON objects BEGIN SELECT 1; END`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
report, err := r.InspectPortability(ctx)
|
||||||
|
if err != nil || report.CoreCompatible {
|
||||||
|
t.Fatal("security trigger hidden by table name", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(strings.Join(report.Blockers, " "), "trigger: objects") {
|
||||||
|
t.Fatal("trigger not identified", report)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func seedRehearsal(t *testing.T, r *Repository) (geduldh.Store, Revision) {
|
||||||
|
t.Helper()
|
||||||
|
ctx := context.Background()
|
||||||
|
docs, _, v := documentFixture(t, r)
|
||||||
|
first, err := r.SaveDocument(ctx, docs, "test", v, []byte(`<h1>移行</h1><img src="asset:image:cover">`), "", "actor")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.BindPath(ctx, "test", "/alias", v.ObjectUUID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, path := range []string{"/日本語%_", "/Case", "/case", "/é", "/e\u0301"} {
|
||||||
|
if err := r.BindPath(ctx, "test", path, v.ObjectUUID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Values above JavaScript's safe-integer range must never pass through
|
||||||
|
// float64 on the migration path. Also exercise identity/sequence recovery.
|
||||||
|
const large = int64(9007199254741011)
|
||||||
|
if _, err := r.database.ExecContext(ctx, `UPDATE asset_head_history SET id=`+r.p(1), large); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.database.ExecContext(ctx, `UPDATE activity_outbox SET sequence=`+r.p(1)+`,status='failed',attempts=3,last_error='synthetic'`, large); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.database.ExecContext(ctx, `UPDATE activity_outbox_heads SET last_sequence=`+r.p(1), large); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return docs, first.Revision
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCoreFingerprintIncludesContentAndPurgedIdentity(t *testing.T) {
|
||||||
|
source := testRepository(t, SQLite)
|
||||||
|
target := testRepository(t, SQLite)
|
||||||
|
ctx := context.Background()
|
||||||
|
docs, v := seedRehearsal(t, source)
|
||||||
|
before, err := source.FingerprintCore(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := source.database.ExecContext(ctx, `UPDATE objects SET kind='changed' WHERE uuid=?`, v.ObjectUUID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
after, err := source.FingerprintCore(ctx)
|
||||||
|
if err != nil || after.SHA256 == before.SHA256 {
|
||||||
|
t.Fatal("same row counts hid content change", err)
|
||||||
|
}
|
||||||
|
// A retained generator high-water mark must survive even if the highest
|
||||||
|
// history rows have been purged. Reusing an old history URL is not safe.
|
||||||
|
if _, err := source.database.ExecContext(ctx, `UPDATE sqlite_sequence SET seq=9007199254741999 WHERE name='asset_head_history'`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := CloneCoreForRehearsal(ctx, source, target, RehearsalOptions{Offline: true, Documents: docs})
|
||||||
|
if err != nil || result.IdentityNext != 9007199254742000 {
|
||||||
|
t.Fatal("purged sequence lost", err, result.IdentityNext)
|
||||||
|
}
|
||||||
|
a, err := target.GetAsset(ctx, "test", "asset:image:cover")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := target.PutAsset(ctx, a, a.HeadDocumentHash, "actor"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var id int64
|
||||||
|
if err := target.database.QueryRowContext(ctx, `SELECT max(id) FROM asset_head_history`).Scan(&id); err != nil || id != result.IdentityNext {
|
||||||
|
t.Fatal("old history ID reused", err, id)
|
||||||
|
}
|
||||||
|
if _, err := source.database.ExecContext(ctx, `UPDATE objects SET created_at='not-an-integer'`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := source.FingerprintCore(ctx); !errors.Is(err, ErrIntegrity) {
|
||||||
|
t.Fatal("invalid integer type accepted", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCoreRoundTripSQLitePostgreSQLSQLite(t *testing.T) {
|
||||||
|
source := testRepository(t, SQLite)
|
||||||
|
target := testRepository(t, PostgreSQL)
|
||||||
|
restored := testRepository(t, SQLite)
|
||||||
|
ctx := context.Background()
|
||||||
|
docs, first := seedRehearsal(t, source)
|
||||||
|
before, err := source.FingerprintCore(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err := CloneCoreForRehearsal(ctx, source, target, RehearsalOptions{Offline: true, Documents: docs})
|
||||||
|
if err != nil || result.SHA256 != before.SHA256 {
|
||||||
|
t.Fatal("SQLite to PostgreSQL", err, result)
|
||||||
|
}
|
||||||
|
got, err := target.Head(ctx, "test", first.ObjectUUID, first.Language)
|
||||||
|
if err != nil || got != first {
|
||||||
|
t.Fatal("revision identity/content changed", err)
|
||||||
|
}
|
||||||
|
asset, err := target.GetAsset(ctx, "test", "asset:image:cover")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
asset.Filename = "new.png"
|
||||||
|
if _, err := target.PutAsset(ctx, asset, asset.HeadDocumentHash, "actor"); err != nil {
|
||||||
|
t.Fatal("identity sequence not repaired", err)
|
||||||
|
}
|
||||||
|
var id int64
|
||||||
|
if err := target.database.QueryRowContext(ctx, `SELECT max(id) FROM asset_head_history`).Scan(&id); err != nil || id != 9007199254741012 {
|
||||||
|
t.Fatal("identity precision/restart", id, err)
|
||||||
|
}
|
||||||
|
if _, err := target.database.ExecContext(ctx, `ALTER TABLE asset_head_history ALTER COLUMN id RESTART WITH 9007199254743000`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
next, err := target.SaveDocument(ctx, docs, "test", first, []byte(`<h1>PostgreSQLで更新</h1>`), first.UUID, "actor")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
targetState, err := target.FingerprintCore(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
back, err := CloneCoreForRehearsal(ctx, target, restored, RehearsalOptions{Offline: true, Documents: docs})
|
||||||
|
if err != nil || back.SHA256 != targetState.SHA256 {
|
||||||
|
t.Fatal("PostgreSQL to SQLite", err)
|
||||||
|
}
|
||||||
|
if got, err := restored.Head(ctx, "test", first.ObjectUUID, first.Language); err != nil || got.UUID != next.Revision.UUID {
|
||||||
|
t.Fatal("post-cutover update lost on rollback", err)
|
||||||
|
}
|
||||||
|
if got, err := source.FingerprintCore(ctx); err != nil || got.SHA256 != before.SHA256 {
|
||||||
|
t.Fatal("source was modified", err)
|
||||||
|
}
|
||||||
|
if _, err := restored.PutAsset(ctx, asset, asset.HeadDocumentHash, "actor"); err != nil {
|
||||||
|
t.Fatal("SQLite sequence not recovered", err)
|
||||||
|
}
|
||||||
|
if err := restored.database.QueryRowContext(ctx, `SELECT max(id) FROM asset_head_history`).Scan(&id); err != nil || id != 9007199254743000 {
|
||||||
|
t.Fatal("PostgreSQL retained generator state lost", id, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCoreCloneRejectsSameDatabaseThroughDifferentPools(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
var alias *Repository
|
||||||
|
if backend == SQLite {
|
||||||
|
var file string
|
||||||
|
if err := r.database.QueryRow(`SELECT file FROM pragma_database_list WHERE name='main'`).Scan(&file); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
database, err := db.Open(file)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
alias, _ = New(database, backend)
|
||||||
|
} else {
|
||||||
|
var schema string
|
||||||
|
if err := r.database.QueryRow(`SELECT current_schema()`).Scan(&schema); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
u, err := url.Parse(os.Getenv("PAGESWIKI_TEST_POSTGRES_DSN"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("invalid test DSN")
|
||||||
|
}
|
||||||
|
q := u.Query()
|
||||||
|
q.Set("search_path", schema)
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
database, err := db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: u.String(), AllowInsecure: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
alias, _ = New(database, backend)
|
||||||
|
}
|
||||||
|
documents, _ := geduldh.NewLocal(t.TempDir())
|
||||||
|
if _, err := CloneCoreForRehearsal(ctx, r, alias, RehearsalOptions{Offline: true, Documents: documents}); !errors.Is(err, ErrMigrationBlocked) {
|
||||||
|
t.Fatal("self-copy not rejected before locking", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCoreCloneRejectsUnsafeConditionsAndRollsBack(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
source := testRepository(t, SQLite)
|
||||||
|
target := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
docs, _ := seedRehearsal(t, source)
|
||||||
|
if _, err := CloneCoreForRehearsal(ctx, source, target, RehearsalOptions{Documents: docs}); !errors.Is(err, ErrMigrationBlocked) {
|
||||||
|
t.Fatal("online migration permitted", err)
|
||||||
|
}
|
||||||
|
if _, err := CloneCoreForRehearsal(ctx, source, target, RehearsalOptions{Offline: true}); !errors.Is(err, ErrMigrationBlocked) {
|
||||||
|
t.Fatal("unverified Documents permitted", err)
|
||||||
|
}
|
||||||
|
empty, err := target.FingerprintCore(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Extra uniqueness rules must block the plan before any copying.
|
||||||
|
if _, err := target.database.ExecContext(ctx, `CREATE UNIQUE INDEX synthetic_rehearsal_failure ON paths(object_uuid)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := CloneCoreForRehearsal(ctx, source, target, RehearsalOptions{Offline: true, Documents: docs}); !errors.Is(err, ErrMigrationBlocked) {
|
||||||
|
t.Fatal("unexpected unique index accepted", err)
|
||||||
|
}
|
||||||
|
if _, err := target.database.ExecContext(ctx, `DROP INDEX synthetic_rehearsal_failure`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got, err := target.FingerprintCore(ctx); err != nil || got.SHA256 != empty.SHA256 {
|
||||||
|
t.Fatal("partial destination rows survived", err)
|
||||||
|
}
|
||||||
|
// SQLite can contain a BLOB despite a TEXT declaration. Detect it
|
||||||
|
// while streaming, after earlier tables have been inserted, and roll
|
||||||
|
// back every destination row instead of coercing or truncating it.
|
||||||
|
if _, err := source.database.ExecContext(ctx, `UPDATE paths SET path=CAST(path AS BLOB)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := CloneCoreForRehearsal(ctx, source, target, RehearsalOptions{Offline: true, Documents: docs}); !errors.Is(err, ErrIntegrity) {
|
||||||
|
t.Fatal("nonportable row accepted", err)
|
||||||
|
}
|
||||||
|
if got, err := target.FingerprintCore(ctx); err != nil || got.SHA256 != empty.SHA256 {
|
||||||
|
t.Fatal("mid-copy failure left rows", err)
|
||||||
|
}
|
||||||
|
if _, err := source.database.ExecContext(ctx, `UPDATE paths SET path=CAST(path AS TEXT)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := target.CreatePage(ctx, "test", "/do-not-overwrite"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
occupied, err := target.FingerprintCore(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := CloneCoreForRehearsal(ctx, source, target, RehearsalOptions{Offline: true, Documents: docs}); !errors.Is(err, ErrDestinationNotEmpty) {
|
||||||
|
t.Fatal("occupied destination overwritten", err)
|
||||||
|
}
|
||||||
|
if got, err := target.FingerprintCore(ctx); err != nil || got.SHA256 != occupied.SHA256 {
|
||||||
|
t.Fatal("occupied target changed", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCoreCloneRejectsMissingDocumentsAndBrokenRelations(t *testing.T) {
|
||||||
|
r := testRepository(t, SQLite)
|
||||||
|
target := testRepository(t, SQLite)
|
||||||
|
ctx := context.Background()
|
||||||
|
docs, _ := seedRehearsal(t, r)
|
||||||
|
if _, err := r.database.ExecContext(ctx, `UPDATE paths SET object_uuid='missing'`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := CloneCoreForRehearsal(ctx, r, target, RehearsalOptions{Offline: true, Documents: docs}); !errors.Is(err, ErrIntegrity) {
|
||||||
|
t.Fatal("broken references copied", err)
|
||||||
|
}
|
||||||
|
r = testRepository(t, SQLite)
|
||||||
|
docs, _ = seedRehearsal(t, r)
|
||||||
|
missing, _ := geduldh.NewLocal(t.TempDir())
|
||||||
|
if _, err := CloneCoreForRehearsal(ctx, r, target, RehearsalOptions{Offline: true, Documents: missing}); !errors.Is(err, ErrIntegrity) {
|
||||||
|
t.Fatal("missing Document accepted", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,445 @@
|
|||||||
|
// Package metadata contains the portable metadata persistence contract. It does
|
||||||
|
// not authorize requests, store payloads, run legacy Store initialization, or
|
||||||
|
// constitute a PostgreSQL-capable application. Payloads must be persisted and
|
||||||
|
// verified in Geduldh before publishing their hash here.
|
||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"golang.org/x/text/language"
|
||||||
|
"modernc.org/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Backend string
|
||||||
|
|
||||||
|
const (
|
||||||
|
SQLite Backend = "sqlite"
|
||||||
|
PostgreSQL Backend = "postgres"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrNotFound = errors.New("metadata not found")
|
||||||
|
ErrConflict = errors.New("metadata conflict")
|
||||||
|
ErrInvalid = errors.New("invalid metadata")
|
||||||
|
)
|
||||||
|
|
||||||
|
type Repository struct {
|
||||||
|
database *sql.DB
|
||||||
|
backend Backend
|
||||||
|
applicationNamespace bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// New never migrates a schema or creates keys. Ownership of database stays with
|
||||||
|
// the caller. Backend must match the actual connection; no fallback is allowed.
|
||||||
|
func New(database *sql.DB, backend Backend) (*Repository, error) {
|
||||||
|
if database == nil || (backend != SQLite && backend != PostgreSQL) {
|
||||||
|
return nil, ErrInvalid
|
||||||
|
}
|
||||||
|
return &Repository{database: database, backend: backend}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewApplication uses the application's namespace/administration lock before
|
||||||
|
// the metadata Domain/Object locks. Namespace validation is repeated inside
|
||||||
|
// the commit transaction. This does not replace request authorization, perform
|
||||||
|
// migrations, or make an incomplete application Store ready to serve traffic.
|
||||||
|
func NewApplication(database *sql.DB, backend Backend) (*Repository, error) {
|
||||||
|
r, err := New(database, backend)
|
||||||
|
if err == nil {
|
||||||
|
r.applicationNamespace = true
|
||||||
|
}
|
||||||
|
return r, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// p generates a placeholder, rather than rewriting arbitrary SQL (which can
|
||||||
|
// contain JSON operators, strings or comments with literal question marks).
|
||||||
|
func (r *Repository) p(n int) string {
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
return fmt.Sprintf("$%d", n)
|
||||||
|
}
|
||||||
|
return "?"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) failure(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.Canceled) {
|
||||||
|
return context.Canceled
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
return context.DeadlineExceeded
|
||||||
|
}
|
||||||
|
var pg *pgconn.PgError
|
||||||
|
if errors.As(err, &pg) {
|
||||||
|
if pg.Code == "23505" || pg.Code == "40001" || pg.Code == "40P01" {
|
||||||
|
return ErrConflict
|
||||||
|
}
|
||||||
|
return fmt.Errorf("PostgreSQL metadata operation failed (SQLSTATE %s)", pg.Code)
|
||||||
|
}
|
||||||
|
var se *sqlite.Error
|
||||||
|
if errors.As(err, &se) {
|
||||||
|
switch se.Code() {
|
||||||
|
case 1555, 2067:
|
||||||
|
return ErrConflict
|
||||||
|
}
|
||||||
|
return fmt.Errorf("SQLite metadata operation failed (code %d)", se.Code())
|
||||||
|
}
|
||||||
|
// Network errors may include a credential-bearing DSN or server addresses.
|
||||||
|
return errors.New("metadata database operation failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func canonicalPath(raw string) (string, error) {
|
||||||
|
p := strings.TrimSpace(raw)
|
||||||
|
if !strings.HasPrefix(p, "/") {
|
||||||
|
return "", ErrInvalid
|
||||||
|
}
|
||||||
|
if p != "/" {
|
||||||
|
p = strings.TrimRight(p, "/")
|
||||||
|
}
|
||||||
|
if p == "" || !utf8.ValidString(p) || strings.ContainsAny(p, "\x00\r\n") {
|
||||||
|
return "", ErrInvalid
|
||||||
|
}
|
||||||
|
if p != "/" {
|
||||||
|
for _, part := range strings.Split(p[1:], "/") {
|
||||||
|
if part == "" || part == "." || part == ".." {
|
||||||
|
return "", ErrInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validHash(hash string) bool {
|
||||||
|
if len(hash) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range hash {
|
||||||
|
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// write locks before any read. SQLite acquires its single-writer reservation;
|
||||||
|
// PostgreSQL locks a stable, namespaced key for the whole transaction. Path
|
||||||
|
// writers share a domain key; revisions additionally take an object key after
|
||||||
|
// the domain key, even when an object is bound in more than one domain.
|
||||||
|
func (r *Repository) write(ctx context.Context, key string, fn func(*sql.Tx) error) error {
|
||||||
|
tx, err := r.database.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
if r.applicationNamespace {
|
||||||
|
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653,1853058931)`); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = r.lock(ctx, tx, key)
|
||||||
|
} else {
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE paths SET created_at=created_at WHERE 0`)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if r.applicationNamespace {
|
||||||
|
if !strings.HasPrefix(key, "domain/") {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
var local bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains d JOIN campuses c ON c.uuid=d.campus_uuid WHERE d.uuid=`+r.p(1)+` AND d.enabled=1 AND c.enabled=1 AND d.placement='local')`, strings.TrimPrefix(key, "domain/")).Scan(&local); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if !local {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err = fn(tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.failure(tx.Commit())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) lock(ctx context.Context, tx *sql.Tx, key string) error {
|
||||||
|
if r.backend != PostgreSQL {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
h := sha256.Sum256([]byte("pageswiki/metadata/" + key))
|
||||||
|
_, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, int64(binary.BigEndian.Uint64(h[:8])))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) CreatePage(ctx context.Context, domain, path string) (string, error) {
|
||||||
|
p, err := canonicalPath(path)
|
||||||
|
if err != nil || strings.TrimSpace(domain) == "" {
|
||||||
|
return "", ErrInvalid
|
||||||
|
}
|
||||||
|
id := uuid.NewString()
|
||||||
|
err = r.write(ctx, "domain/"+domain, func(tx *sql.Tx) error {
|
||||||
|
now := time.Now().Unix()
|
||||||
|
for _, q := range []struct {
|
||||||
|
sql string
|
||||||
|
args []any
|
||||||
|
}{
|
||||||
|
{`INSERT INTO objects(uuid,kind,created_at) VALUES (` + r.p(1) + `,'page',` + r.p(2) + `)`, []any{id, now}},
|
||||||
|
{`INSERT INTO object_origins(object_uuid,domain_uuid,created_at) VALUES (` + r.p(1) + `,` + r.p(2) + `,` + r.p(3) + `)`, []any{id, domain, now}},
|
||||||
|
{`INSERT INTO paths(domain_uuid,path,object_uuid,created_at,is_primary) VALUES (` + r.p(1) + `,` + r.p(2) + `,` + r.p(3) + `,` + r.p(4) + `,1)`, []any{domain, p, id, now}},
|
||||||
|
} {
|
||||||
|
if _, err := tx.ExecContext(ctx, q.sql, q.args...); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r.applicationNamespace {
|
||||||
|
return r.appendPageOutbox(ctx, tx, domain, p, id)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateObject records provenance for the explicit create/save/bind API.
|
||||||
|
// It does not grant authority over an arbitrary unbound legacy Object.
|
||||||
|
func (r *Repository) CreateObject(ctx context.Context, domain, kind string) (string, error) {
|
||||||
|
if domain == "" || strings.TrimSpace(kind) == "" {
|
||||||
|
return "", ErrInvalid
|
||||||
|
}
|
||||||
|
id := uuid.NewString()
|
||||||
|
err := r.write(ctx, "domain/"+domain, func(tx *sql.Tx) error {
|
||||||
|
now := time.Now().Unix()
|
||||||
|
if _, err := tx.ExecContext(ctx, `INSERT INTO objects(uuid,kind,created_at) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`)`, id, kind, now); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
_, err := tx.ExecContext(ctx, `INSERT INTO object_origins(object_uuid,domain_uuid,created_at) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`)`, id, domain, now)
|
||||||
|
return r.failure(err)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) ResolvePath(ctx context.Context, domain, path string) (string, error) {
|
||||||
|
var id string
|
||||||
|
err := r.database.QueryRowContext(ctx, `SELECT object_uuid FROM paths WHERE domain_uuid=`+r.p(1)+` AND path=`+r.p(2), domain, path).Scan(&id)
|
||||||
|
return id, r.failure(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BindPath creates an alias without replacing an existing binding. Cross-domain
|
||||||
|
// sharing requires a separate explicit authorization/import contract.
|
||||||
|
func (r *Repository) BindPath(ctx context.Context, domain, path, object string) error {
|
||||||
|
p, err := canonicalPath(path)
|
||||||
|
if err != nil || domain == "" || object == "" {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
return r.write(ctx, "domain/"+domain, func(tx *sql.Tx) error {
|
||||||
|
var count int
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM object_origins WHERE object_uuid=`+r.p(1)+` AND domain_uuid=`+r.p(2), object, domain).Scan(&count); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
_, err := tx.ExecContext(ctx, `INSERT INTO paths(domain_uuid,path,object_uuid,created_at,is_primary) VALUES (`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`,0)`, domain, p, object, time.Now().Unix())
|
||||||
|
return r.failure(err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// RenameTree moves both real and virtual folders without LIKE wildcard or
|
||||||
|
// case-folding semantics. It does not merge into occupied destinations. City,
|
||||||
|
// ACL, activity outbox and cache invalidation must be coordinated by the future
|
||||||
|
// application-level transaction; do not substitute this for legacy UI rename yet.
|
||||||
|
func (r *Repository) RenameTree(ctx context.Context, domain, source, destination string) error {
|
||||||
|
from, e1 := canonicalPath(source)
|
||||||
|
to, e2 := canonicalPath(destination)
|
||||||
|
if e1 != nil || e2 != nil || domain == "" || from == "/" || to == "/" || from == to || strings.HasPrefix(to, from+"/") || strings.HasPrefix(from, to+"/") {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
return r.write(ctx, "domain/"+domain, func(tx *sql.Tx) error {
|
||||||
|
var occupied int
|
||||||
|
// Binary/C collation makes [prefix+'/', prefix+'0') an exact,
|
||||||
|
// indexable descendant range, including Unicode and literal %/_ names.
|
||||||
|
err := tx.QueryRowContext(ctx, `SELECT 1 FROM paths WHERE domain_uuid=`+r.p(1)+` AND (path=`+r.p(2)+` OR (path>=`+r.p(3)+` AND path<`+r.p(4)+`)) LIMIT 1`, domain, to, to+"/", to+"0").Scan(&occupied)
|
||||||
|
if err == nil {
|
||||||
|
return ErrConflict
|
||||||
|
}
|
||||||
|
if !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
// A single SQL update avoids loading the subtree or issuing one query
|
||||||
|
// per path. substr counts characters (not UTF-8 bytes) on both DBs.
|
||||||
|
result, err := tx.ExecContext(ctx, `UPDATE paths SET path=`+r.p(1)+` || substr(path,`+r.p(2)+`) WHERE domain_uuid=`+r.p(3)+` AND (path=`+r.p(4)+` OR (path>=`+r.p(5)+` AND path<`+r.p(6)+`))`, to, len([]rune(from))+1, domain, from, from+"/", from+"0")
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
count, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type Revision struct {
|
||||||
|
UUID string
|
||||||
|
ObjectUUID string
|
||||||
|
DocumentHash string
|
||||||
|
Language string
|
||||||
|
ContentType string
|
||||||
|
Filename string
|
||||||
|
Message string
|
||||||
|
CreatedAtMS int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizedLanguage(raw string) (string, error) {
|
||||||
|
if strings.TrimSpace(raw) == "" {
|
||||||
|
return "und", nil
|
||||||
|
}
|
||||||
|
tag, err := language.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
return "", ErrInvalid
|
||||||
|
}
|
||||||
|
return tag.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const revisionColumns = `uuid,object_uuid,document_hash,lang,content_type,filename,message,created_at_ms`
|
||||||
|
|
||||||
|
// Application create/save/bind records creation provenance before any Path.
|
||||||
|
// Provenance ceases to grant scope as soon as any live binding exists.
|
||||||
|
// Expressions are owned SQL identifiers/placeholders, never request strings.
|
||||||
|
func (r *Repository) objectDomainScope(object, domain string) string {
|
||||||
|
scope := `SELECT domain_uuid FROM paths WHERE object_uuid=` + object
|
||||||
|
if r.applicationNamespace {
|
||||||
|
scope += ` UNION ALL SELECT domain_uuid FROM object_origins WHERE object_uuid=` + object + ` AND NOT EXISTS(SELECT 1 FROM paths WHERE object_uuid=` + object + `)`
|
||||||
|
}
|
||||||
|
return domain + ` IN (` + scope + `)`
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanRevision(row interface{ Scan(...any) error }) (Revision, error) {
|
||||||
|
var v Revision
|
||||||
|
err := row.Scan(&v.UUID, &v.ObjectUUID, &v.DocumentHash, &v.Language, &v.ContentType, &v.Filename, &v.Message, &v.CreatedAtMS)
|
||||||
|
return v, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) Head(ctx context.Context, domain, object, lang string) (Revision, error) {
|
||||||
|
l, err := normalizedLanguage(lang)
|
||||||
|
if err != nil {
|
||||||
|
return Revision{}, err
|
||||||
|
}
|
||||||
|
v, err := scanRevision(r.database.QueryRowContext(ctx, `SELECT `+revisionColumns+` FROM revisions r WHERE object_uuid=`+r.p(1)+` AND lang=`+r.p(2)+` AND (`+r.objectDomainScope("r.object_uuid", r.p(3))+`) ORDER BY created_at_ms DESC,uuid DESC LIMIT 1`, object, l, domain))
|
||||||
|
return v, r.failure(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) GetRevision(ctx context.Context, domain, revisionUUID string) (Revision, error) {
|
||||||
|
v, err := scanRevision(r.database.QueryRowContext(ctx, `SELECT `+revisionColumns+` FROM revisions r WHERE uuid=`+r.p(1)+` AND (`+r.objectDomainScope("r.object_uuid", r.p(2))+`)`, revisionUUID, domain))
|
||||||
|
return v, r.failure(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RestoreRevision appends a new revision pointing to the historical Document;
|
||||||
|
// it never rewrites old revision metadata or bypasses the exact-language CAS.
|
||||||
|
func (r *Repository) RestoreRevision(ctx context.Context, domain, revisionUUID, expected, message string) (Revision, error) {
|
||||||
|
v, err := r.GetRevision(ctx, domain, revisionUUID)
|
||||||
|
if err != nil {
|
||||||
|
return Revision{}, err
|
||||||
|
}
|
||||||
|
v.Message = message
|
||||||
|
refs, err := r.revisionReferences(ctx, domain, revisionUUID)
|
||||||
|
if err != nil {
|
||||||
|
return Revision{}, err
|
||||||
|
}
|
||||||
|
return r.appendRevision(ctx, domain, v, expected, refs, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendRevision uses exact-language compare-and-swap. Empty expected means
|
||||||
|
// there is no previous revision in this language. All writes use this contract;
|
||||||
|
// monotonic timestamps remove dependence on SQLite's hidden rowid ordering.
|
||||||
|
func (r *Repository) AppendRevision(ctx context.Context, domain string, v Revision, expected string) (Revision, error) {
|
||||||
|
return r.appendRevision(ctx, domain, v, expected, nil, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) appendRevision(ctx context.Context, domain string, v Revision, expected string, refs []string, actor string) (Revision, error) {
|
||||||
|
return r.appendRevisionExpected(ctx, domain, v, &expected, refs, actor)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) appendRevisionExpected(ctx context.Context, domain string, v Revision, expected *string, refs []string, actor string) (Revision, error) {
|
||||||
|
lang, err := normalizedLanguage(v.Language)
|
||||||
|
if err != nil || !validHash(v.DocumentHash) || v.ObjectUUID == "" || strings.TrimSpace(v.ContentType) == "" {
|
||||||
|
return Revision{}, ErrInvalid
|
||||||
|
}
|
||||||
|
v.UUID = uuid.NewString()
|
||||||
|
v.Language = lang
|
||||||
|
err = r.write(ctx, "domain/"+domain, func(tx *sql.Tx) error {
|
||||||
|
// Always acquire Domain before Object. This also protects per-Domain
|
||||||
|
// outbox sequence allocation for different objects and languages.
|
||||||
|
if err := r.lock(ctx, tx, "object/"+v.ObjectUUID); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
var bound bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM objects o WHERE o.uuid=`+r.p(1)+` AND (`+r.objectDomainScope("o.uuid", r.p(2))+`))`, v.ObjectUUID, domain).Scan(&bound); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if !bound {
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
var current string
|
||||||
|
var previous int64
|
||||||
|
err := tx.QueryRowContext(ctx, `SELECT uuid,created_at_ms FROM revisions WHERE object_uuid=`+r.p(1)+` AND lang=`+r.p(2)+` ORDER BY created_at_ms DESC,uuid DESC LIMIT 1`, v.ObjectUUID, lang).Scan(¤t, &previous)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if expected != nil && current != *expected {
|
||||||
|
return ErrConflict
|
||||||
|
}
|
||||||
|
if previous == math.MaxInt64 {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
v.CreatedAtMS = time.Now().UnixMilli()
|
||||||
|
if v.CreatedAtMS <= previous {
|
||||||
|
v.CreatedAtMS = previous + 1
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO revisions(uuid,object_uuid,document_hash,lang,content_type,filename,message,created_at_ms,created_at,body) VALUES (`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`,`+r.p(5)+`,`+r.p(6)+`,`+r.p(7)+`,`+r.p(8)+`,`+r.p(9)+`,'')`, v.UUID, v.ObjectUUID, v.DocumentHash, v.Language, v.ContentType, v.Filename, v.Message, v.CreatedAtMS, v.CreatedAtMS/1000)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, hash := range refs {
|
||||||
|
if !validHash(hash) {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
if seen[hash] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[hash] = true
|
||||||
|
if _, err := tx.ExecContext(ctx, `INSERT INTO revision_document_refs(revision_uuid,document_hash) VALUES (`+r.p(1)+`,`+r.p(2)+`)`, v.UUID, hash); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r.appendRevisionOutbox(ctx, tx, domain, actor, v)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return Revision{}, err
|
||||||
|
}
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testRepository(t *testing.T, backend Backend) *Repository {
|
||||||
|
t.Helper()
|
||||||
|
var database *sql.DB
|
||||||
|
var err error
|
||||||
|
if backend == SQLite {
|
||||||
|
database, err = db.Open(filepath.Join(t.TempDir(), "metadata.db"))
|
||||||
|
} else {
|
||||||
|
dsn := os.Getenv("PAGESWIKI_TEST_POSTGRES_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("set PAGESWIKI_TEST_POSTGRES_DSN to a disposable PostgreSQL URL")
|
||||||
|
}
|
||||||
|
u, e := url.Parse(dsn)
|
||||||
|
if e != nil || (u.Scheme != "postgres" && u.Scheme != "postgresql") {
|
||||||
|
t.Fatal("test DSN must be PostgreSQL URL")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
root, e := db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: dsn, AllowInsecure: true})
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
schema := "pageswiki_metadata_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||||
|
if _, e = root.ExecContext(ctx, `CREATE SCHEMA "`+schema+`"`); e != nil {
|
||||||
|
root.Close()
|
||||||
|
t.Fatal("create synthetic test schema failed")
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if _, e := root.ExecContext(ctx, `DROP SCHEMA "`+schema+`" CASCADE`); e != nil {
|
||||||
|
t.Error("drop synthetic test schema failed")
|
||||||
|
}
|
||||||
|
root.Close()
|
||||||
|
})
|
||||||
|
query := u.Query()
|
||||||
|
query.Set("search_path", schema)
|
||||||
|
u.RawQuery = query.Encode()
|
||||||
|
database, err = db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: u.String(), AllowInsecure: true})
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { database.Close() })
|
||||||
|
r, err := New(database, backend)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.InitializeFresh(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.InitializeFresh(context.Background()); err != nil {
|
||||||
|
t.Fatal("repeated initialization", err)
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func hash(s string) string { v := sha256.Sum256([]byte(s)); return hex.EncodeToString(v[:]) }
|
||||||
|
|
||||||
|
func TestMetadataContract(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
mustPage := func(domain, path string) string {
|
||||||
|
t.Helper()
|
||||||
|
id, err := r.CreatePage(ctx, domain, path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
id := mustPage("domain-a", "/学区%_/通り/本")
|
||||||
|
other := mustPage("domain-b", "/学区%_/通り/本")
|
||||||
|
if id == other {
|
||||||
|
t.Fatal("object UUID reused")
|
||||||
|
}
|
||||||
|
if got, err := r.ResolvePath(ctx, "domain-a", "/学区%_/通り/本"); err != nil || got != id {
|
||||||
|
t.Fatal("path resolution", err)
|
||||||
|
}
|
||||||
|
if _, err := r.ResolvePath(ctx, "unknown", "/学区%_/通り/本"); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatal("domain isolation", err)
|
||||||
|
}
|
||||||
|
if _, err := r.CreatePage(ctx, "domain-a", "/学区%_/通り/本"); !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("duplicate path accepted", err)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM objects`).Scan(&count); err != nil || count != 2 {
|
||||||
|
t.Fatal("failed create left orphan object", err, count)
|
||||||
|
}
|
||||||
|
if err := r.BindPath(ctx, "domain-a", "/alias", id); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.BindPath(ctx, "domain-b", "/stolen", id); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatal("foreign alias accepted", err)
|
||||||
|
}
|
||||||
|
mustPage("domain-a", "/学区XX/通り/本")
|
||||||
|
mustPage("domain-a", "/学区%_suffix/本")
|
||||||
|
if err := r.RenameTree(ctx, "domain-a", "/学区%_", "/新しい学区"); err != nil {
|
||||||
|
t.Fatal("virtual folder rename", err)
|
||||||
|
}
|
||||||
|
if got, err := r.ResolvePath(ctx, "domain-a", "/新しい学区/通り/本"); err != nil || got != id {
|
||||||
|
t.Fatal("UUID not preserved", err)
|
||||||
|
}
|
||||||
|
for _, path := range []string{"/学区XX/通り/本", "/学区%_suffix/本"} {
|
||||||
|
if _, err := r.ResolvePath(ctx, "domain-a", path); err != nil {
|
||||||
|
t.Fatal("wildcard/boundary changed unrelated path", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, err := r.ResolvePath(ctx, "domain-b", "/学区%_/通り/本"); err != nil || got != other {
|
||||||
|
t.Fatal("rename crossed domain", err)
|
||||||
|
}
|
||||||
|
mustPage("domain-a", "/occupied/something")
|
||||||
|
if err := r.RenameTree(ctx, "domain-a", "/新しい学区", "/occupied"); !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("destination merged", err)
|
||||||
|
}
|
||||||
|
if _, err := r.ResolvePath(ctx, "domain-a", "/新しい学区/通り/本"); err != nil {
|
||||||
|
t.Fatal("failed move changed source", err)
|
||||||
|
}
|
||||||
|
if err := r.RenameTree(ctx, "domain-a", "/新しい学区", "/新しい学区/inside"); !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Fatal("recursive destination accepted")
|
||||||
|
}
|
||||||
|
mustPage("domain-a", "/Case")
|
||||||
|
mustPage("domain-a", "/case")
|
||||||
|
real := mustPage("domain-a", "/real")
|
||||||
|
child := mustPage("domain-a", "/real/child")
|
||||||
|
if err := r.RenameTree(ctx, "domain-a", "/real", "/moved-real"); err != nil {
|
||||||
|
t.Fatal("real folder move", err)
|
||||||
|
}
|
||||||
|
for path, id := range map[string]string{"/moved-real": real, "/moved-real/child": child} {
|
||||||
|
if got, err := r.ResolvePath(ctx, "domain-a", path); err != nil || got != id {
|
||||||
|
t.Fatal("real subtree identity", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v := Revision{ObjectUUID: id, DocumentHash: hash("first"), Language: "ja", ContentType: "text/html", Message: "first"}
|
||||||
|
first, err := r.AppendRevision(ctx, "domain-a", v, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.Head(ctx, "domain-b", id, "ja"); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatal("foreign revision readable", err)
|
||||||
|
}
|
||||||
|
if _, err := r.Head(ctx, "domain-a", id, "en"); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatal("language fallback leaked into exact head", err)
|
||||||
|
}
|
||||||
|
if _, err := r.AppendRevision(ctx, "domain-a", v, ""); !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("stale revision accepted", err)
|
||||||
|
}
|
||||||
|
v.Language = "en"
|
||||||
|
if _, err := r.AppendRevision(ctx, "domain-a", v, ""); err != nil {
|
||||||
|
t.Fatal("translation creation", err)
|
||||||
|
}
|
||||||
|
v.Language = "ja"
|
||||||
|
v.DocumentHash = hash("updated")
|
||||||
|
// Independent Repository objects simulate writers that cannot share a Go mutex.
|
||||||
|
wins := concurrent(t, 6, func() error {
|
||||||
|
peer, _ := New(r.database, backend)
|
||||||
|
_, err := peer.AppendRevision(ctx, "domain-a", v, first.UUID)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if wins != 1 {
|
||||||
|
t.Fatal("CAS winners", wins)
|
||||||
|
}
|
||||||
|
head, err := r.Head(ctx, "domain-a", id, "ja")
|
||||||
|
if err != nil || head.UUID == first.UUID || head.CreatedAtMS <= first.CreatedAtMS {
|
||||||
|
t.Fatal("head ordering", err)
|
||||||
|
}
|
||||||
|
var originalHash string
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT document_hash FROM revisions WHERE uuid=`+r.p(1), first.UUID).Scan(&originalHash); err != nil || originalHash != first.DocumentHash {
|
||||||
|
t.Fatal("immutable revision changed", err)
|
||||||
|
}
|
||||||
|
if _, err := r.GetRevision(ctx, "domain-b", first.UUID); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatal("foreign revision UUID readable", err)
|
||||||
|
}
|
||||||
|
restored, err := r.RestoreRevision(ctx, "domain-a", first.UUID, head.UUID, "restore old document")
|
||||||
|
if err != nil || restored.UUID == first.UUID || restored.DocumentHash != first.DocumentHash || restored.CreatedAtMS <= head.CreatedAtMS {
|
||||||
|
t.Fatal("restore did not append immutable revision", err)
|
||||||
|
}
|
||||||
|
if _, err := r.RestoreRevision(ctx, "domain-a", first.UUID, head.UUID, "stale restore"); !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("restore ignored head conflict", err)
|
||||||
|
}
|
||||||
|
a := Asset{DomainUUID: "domain-a", Address: "asset:images:cover.png", HeadDocumentHash: hash("image1"), ContentType: "image/png", SizeBytes: 10}
|
||||||
|
initial, err := r.PutAsset(ctx, a, "", "actor")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.GetAsset(ctx, "domain-b", a.Address); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatal("foreign asset readable", err)
|
||||||
|
}
|
||||||
|
a.HeadDocumentHash = hash("image2")
|
||||||
|
if wins := concurrent(t, 6, func() error {
|
||||||
|
peer, _ := New(r.database, backend)
|
||||||
|
_, err := peer.PutAsset(ctx, a, initial.HeadDocumentHash, "actor")
|
||||||
|
return err
|
||||||
|
}); wins != 1 {
|
||||||
|
t.Fatal("asset CAS winners", wins)
|
||||||
|
}
|
||||||
|
current, err := r.GetAsset(ctx, "domain-a", a.Address)
|
||||||
|
if err != nil || current.ObjectUUID != initial.ObjectUUID || current.UpdatedAtMS <= initial.UpdatedAtMS {
|
||||||
|
t.Fatal("asset identity/order", err)
|
||||||
|
}
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM asset_head_history`).Scan(&count); err != nil || count != 2 {
|
||||||
|
t.Fatal("history not atomic", err, count)
|
||||||
|
}
|
||||||
|
a.DomainUUID = "domain-b"
|
||||||
|
if _, err := r.PutAsset(ctx, a, "", "actor"); err != nil {
|
||||||
|
t.Fatal("asset namespace not domain-scoped", err)
|
||||||
|
}
|
||||||
|
if _, err := r.AppendRevision(ctx, "domain-a", Revision{ObjectUUID: id, DocumentHash: "bad", ContentType: "text/html"}, head.UUID); !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Fatal("invalid hash accepted", err)
|
||||||
|
}
|
||||||
|
canceled, stop := context.WithCancel(ctx)
|
||||||
|
stop()
|
||||||
|
if _, err := r.CreatePage(canceled, "domain-a", "/canceled"); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatal("cancellation lost", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMetadataInputValidation(t *testing.T) {
|
||||||
|
for _, path := range []string{"", "relative", "//", "///", "/a//b", "/a/../b", "/a/./b", "/a\x00b", "/a\nb", "/a\xffb"} {
|
||||||
|
if _, err := canonicalPath(path); !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Fatalf("invalid path accepted: %q", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, path := range []string{"/", "/日本語/📚", "/name%_", "/a/b/"} {
|
||||||
|
if _, err := canonicalPath(path); err != nil {
|
||||||
|
t.Fatalf("valid path rejected: %q", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := New(nil, SQLite); !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Fatal("nil database accepted")
|
||||||
|
}
|
||||||
|
// Do not expose data carried by a wrapped cancellation error.
|
||||||
|
r := Repository{}
|
||||||
|
err := r.failure(errors.Join(errors.New("secret"), context.Canceled))
|
||||||
|
if !errors.Is(err, context.Canceled) || strings.Contains(err.Error(), "secret") {
|
||||||
|
t.Fatal("unsafe cancellation error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrent(t *testing.T, n int, fn func() error) int {
|
||||||
|
t.Helper()
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
results := make(chan error, n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() { defer wg.Done(); results <- fn() }()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(results)
|
||||||
|
wins := 0
|
||||||
|
for err := range results {
|
||||||
|
if err == nil {
|
||||||
|
wins++
|
||||||
|
} else if !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("unexpected concurrent write error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return wins
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMetadataRefusesLegacyAdoption(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := r.database.ExecContext(ctx, `DELETE FROM schema_migration_steps WHERE component='core-metadata'`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.CreatePage(ctx, "test", "/preserved"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.InitializeFresh(ctx); err == nil {
|
||||||
|
t.Fatal("unversioned schema silently adopted")
|
||||||
|
}
|
||||||
|
if _, err := r.ResolvePath(ctx, "test", "/preserved"); err != nil {
|
||||||
|
t.Fatal("existing data changed", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMetadataAssetHistoryFailureIsAtomic(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
a := Asset{DomainUUID: "test", Address: "asset:images:original.png", HeadDocumentHash: hash("original"), ContentType: "image/png", SizeBytes: 8}
|
||||||
|
original, err := r.PutAsset(ctx, a, "", "actor")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Force a history write failure after the asset HEAD write. The
|
||||||
|
// synthetic unique index is solely fault injection, not the real schema.
|
||||||
|
if _, err := r.database.ExecContext(ctx, `CREATE UNIQUE INDEX synthetic_history_failure ON asset_head_history(domain_uuid)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
a.HeadDocumentHash = hash("changed")
|
||||||
|
if _, err := r.PutAsset(ctx, a, original.HeadDocumentHash, "actor"); !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("injected history failure ignored", err)
|
||||||
|
}
|
||||||
|
got, err := r.GetAsset(ctx, "test", a.Address)
|
||||||
|
if err != nil || got.HeadDocumentHash != original.HeadDocumentHash || got.UpdatedAtMS != original.UpdatedAtMS {
|
||||||
|
t.Fatal("partial HEAD update", err)
|
||||||
|
}
|
||||||
|
a.Address = "asset:images:new.png"
|
||||||
|
if _, err := r.PutAsset(ctx, a, "", "actor"); !errors.Is(err, ErrConflict) {
|
||||||
|
t.Fatal("injected creation failure ignored", err)
|
||||||
|
}
|
||||||
|
if _, err := r.GetAsset(ctx, "test", a.Address); !errors.Is(err, ErrNotFound) {
|
||||||
|
t.Fatal("partial asset created", err)
|
||||||
|
}
|
||||||
|
for _, table := range []string{"objects", "object_origins", "assets", "asset_head_history"} {
|
||||||
|
var count int
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM `+table).Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatal("rollback failed", table, count, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMetadataDetectsMissingColumnWithoutRepair(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := r.database.ExecContext(ctx, `ALTER TABLE revisions RENAME COLUMN filename TO misplaced_filename`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.InitializeFresh(ctx); err == nil {
|
||||||
|
t.Fatal("missing column ignored")
|
||||||
|
}
|
||||||
|
var value string
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT misplaced_filename FROM revisions LIMIT 1`).Scan(&value); !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
t.Fatal("drift silently repaired", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"math"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// appendRevisionOutbox requires the Domain write lock. Sequence allocation uses
|
||||||
|
// small per-type watermarks, not MAX over the ever-growing event journal.
|
||||||
|
// This writes pending events only; delivery/leases remain a separate port.
|
||||||
|
func (r *Repository) appendRevisionOutbox(ctx context.Context, tx *sql.Tx, domain, actor string, v Revision) error {
|
||||||
|
payload, err := json.Marshal(map[string]string{"revision_uuid": v.UUID, "object_uuid": v.ObjectUUID, "document_hash": v.DocumentHash, "content_type": v.ContentType, "filename": v.Filename})
|
||||||
|
if err != nil {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
return r.appendOutbox(ctx, tx, domain, actor, "revision.created", "revision", v.UUID, string(payload))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) appendPageOutbox(ctx context.Context, tx *sql.Tx, domain, path, object string) error {
|
||||||
|
payload, err := json.Marshal(map[string]string{"path": path, "object_uuid": object})
|
||||||
|
if err != nil {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
return r.appendOutbox(ctx, tx, domain, "", "page.created", "page", object, string(payload))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Caller holds the Domain lock; metadata and the pending event commit together.
|
||||||
|
func (r *Repository) appendOutbox(ctx context.Context, tx *sql.Tx, domain, actor, eventType, targetKind, targetUUID, payload string) error {
|
||||||
|
var last int64
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(last_sequence),0) FROM activity_outbox_heads WHERE domain_uuid=`+r.p(1), domain).Scan(&last); err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
if last == math.MaxInt64 {
|
||||||
|
return ErrInvalid
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
_, err := tx.ExecContext(ctx, `INSERT INTO activity_outbox(uuid,domain_uuid,sequence,event_type,actor_uuid,target_kind,target_uuid,payload,idempotency_key,next_attempt_ms,created_at_ms) VALUES (`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`,`+r.p(5)+`,`+r.p(6)+`,`+r.p(7)+`,`+r.p(8)+`,`+r.p(9)+`,`+r.p(10)+`,`+r.p(11)+`)`, uuid.NewString(), domain, last+1, eventType, actor, targetKind, targetUUID, payload, eventType+":"+targetUUID, now, now)
|
||||||
|
if err != nil {
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO activity_outbox_heads(domain_uuid,event_type,last_sequence) VALUES (`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`) ON CONFLICT(domain_uuid,event_type) DO UPDATE SET last_sequence=excluded.last_sequence`, domain, eventType, last+1)
|
||||||
|
return r.failure(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) revisionReferences(ctx context.Context, domain, revisionUUID string) ([]string, error) {
|
||||||
|
rows, err := r.database.QueryContext(ctx, `SELECT document_hash FROM revision_document_refs WHERE revision_uuid=`+r.p(1)+` AND EXISTS (SELECT 1 FROM revisions r WHERE r.uuid=`+r.p(2)+` AND (`+r.objectDomainScope("r.object_uuid", r.p(3))+`)) ORDER BY document_hash`, revisionUUID, revisionUUID, domain)
|
||||||
|
if err != nil {
|
||||||
|
return nil, r.failure(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var hashes []string
|
||||||
|
for rows.Next() {
|
||||||
|
var h string
|
||||||
|
if err := rows.Scan(&h); err != nil {
|
||||||
|
return nil, r.failure(err)
|
||||||
|
}
|
||||||
|
hashes = append(hashes, h)
|
||||||
|
}
|
||||||
|
return hashes, r.failure(rows.Err())
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// InitializeFresh bootstraps an empty database/schema and is idempotent after
|
||||||
|
// its first successful migration. Existing unversioned application tables are
|
||||||
|
// deliberately rejected, not adopted or converted. Production import and
|
||||||
|
// legacy schema reconciliation require a separate, verified migration plan.
|
||||||
|
func (r *Repository) InitializeFresh(ctx context.Context) error {
|
||||||
|
sqliteSteps, postgresSteps := r.migrationDefinitions()
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
return db.ApplyPostgreSQLMigrations(ctx, r.database, "core-metadata", postgresSteps)
|
||||||
|
}
|
||||||
|
return db.ApplySQLiteMigrations(ctx, r.database, "core-metadata", sqliteSteps)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the exact released definitions shared by initialization and offline
|
||||||
|
// compatibility inspection. Neither inspection nor copying runs migrations.
|
||||||
|
func (r *Repository) migrationDefinitions() ([]db.SQLMigration, []db.PostgreSQLMigration) {
|
||||||
|
identity := "INTEGER PRIMARY KEY AUTOINCREMENT"
|
||||||
|
addressType := "TEXT"
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
identity = "BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY"
|
||||||
|
// Path/asset identity must not depend on database locale or an ICU
|
||||||
|
// nondeterministic collation chosen by the database administrator.
|
||||||
|
addressType = `TEXT COLLATE "C"`
|
||||||
|
}
|
||||||
|
statements := []string{
|
||||||
|
`CREATE TABLE objects(uuid TEXT PRIMARY KEY,kind TEXT NOT NULL,created_at BIGINT NOT NULL)`,
|
||||||
|
`CREATE TABLE object_origins(object_uuid TEXT PRIMARY KEY REFERENCES objects(uuid),domain_uuid TEXT NOT NULL,created_at BIGINT NOT NULL)`,
|
||||||
|
`CREATE TABLE paths(domain_uuid TEXT NOT NULL,path ` + addressType + ` NOT NULL,object_uuid TEXT NOT NULL REFERENCES objects(uuid),created_at BIGINT NOT NULL,is_primary INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(domain_uuid,path))`,
|
||||||
|
`CREATE INDEX idx_paths_domain_object ON paths(domain_uuid,object_uuid)`,
|
||||||
|
`CREATE TABLE revisions(uuid TEXT PRIMARY KEY,object_uuid TEXT NOT NULL REFERENCES objects(uuid),document_hash TEXT NOT NULL,lang TEXT NOT NULL,content_type TEXT NOT NULL,filename TEXT NOT NULL DEFAULT '',message TEXT NOT NULL DEFAULT '',created_at_ms BIGINT NOT NULL,created_at BIGINT NOT NULL,body TEXT NOT NULL DEFAULT '')`,
|
||||||
|
`CREATE INDEX idx_revisions_metadata_head ON revisions(object_uuid,lang,created_at_ms DESC,uuid DESC)`,
|
||||||
|
`CREATE TABLE assets(domain_uuid TEXT NOT NULL,address ` + addressType + ` NOT NULL,object_uuid TEXT NOT NULL UNIQUE REFERENCES objects(uuid),head_document_hash TEXT NOT NULL,content_type TEXT NOT NULL,filename TEXT NOT NULL DEFAULT '',size_bytes BIGINT NOT NULL CHECK(size_bytes>=0),created_at_ms BIGINT NOT NULL,updated_at_ms BIGINT NOT NULL,PRIMARY KEY(domain_uuid,address))`,
|
||||||
|
`CREATE TABLE asset_head_history(id ` + identity + `,domain_uuid TEXT NOT NULL,address TEXT NOT NULL,action TEXT NOT NULL,document_hash TEXT NOT NULL,content_type TEXT NOT NULL,filename TEXT NOT NULL,size_bytes BIGINT NOT NULL CHECK(size_bytes>=0),actor_uuid TEXT NOT NULL,created_at_ms BIGINT NOT NULL)`,
|
||||||
|
`CREATE INDEX idx_asset_metadata_history ON asset_head_history(domain_uuid,address,id)`,
|
||||||
|
}
|
||||||
|
// Minimal shape checks also run on subsequent initialization. Full catalog
|
||||||
|
// assertions for types, collation, constraints and indexes are a separate
|
||||||
|
// adoption gate before this schema can replace a legacy production store.
|
||||||
|
assertions := []string{
|
||||||
|
`SELECT uuid,kind,created_at FROM objects WHERE 1=0`,
|
||||||
|
`SELECT object_uuid,domain_uuid,created_at FROM object_origins WHERE 1=0`,
|
||||||
|
`SELECT domain_uuid,path,object_uuid,created_at,is_primary FROM paths WHERE 1=0`,
|
||||||
|
`SELECT ` + revisionColumns + `,created_at,body FROM revisions WHERE 1=0`,
|
||||||
|
`SELECT ` + assetColumns + ` FROM assets WHERE 1=0`,
|
||||||
|
`SELECT id,domain_uuid,address,action,document_hash,content_type,filename,size_bytes,actor_uuid,created_at_ms FROM asset_head_history WHERE 1=0`,
|
||||||
|
}
|
||||||
|
referenceStatements := []string{
|
||||||
|
`CREATE TABLE revision_document_refs(revision_uuid TEXT NOT NULL REFERENCES revisions(uuid),document_hash TEXT NOT NULL,PRIMARY KEY(revision_uuid,document_hash))`,
|
||||||
|
`CREATE INDEX idx_metadata_document_refs ON revision_document_refs(document_hash,revision_uuid)`,
|
||||||
|
`CREATE TABLE activity_outbox(uuid TEXT PRIMARY KEY,domain_uuid TEXT NOT NULL,sequence BIGINT NOT NULL,event_type TEXT NOT NULL,actor_uuid TEXT NOT NULL DEFAULT '',target_kind TEXT NOT NULL DEFAULT '',target_uuid TEXT NOT NULL DEFAULT '',payload TEXT NOT NULL DEFAULT '',idempotency_key TEXT NOT NULL,status TEXT NOT NULL DEFAULT 'pending',attempts INTEGER NOT NULL DEFAULT 0,next_attempt_ms BIGINT NOT NULL,last_error TEXT NOT NULL DEFAULT '',created_at_ms BIGINT NOT NULL,claimed_at_ms BIGINT NOT NULL DEFAULT 0,UNIQUE(domain_uuid,sequence),UNIQUE(domain_uuid,idempotency_key))`,
|
||||||
|
`CREATE TABLE activity_outbox_heads(domain_uuid TEXT NOT NULL,event_type TEXT NOT NULL,last_sequence BIGINT NOT NULL,PRIMARY KEY(domain_uuid,event_type))`,
|
||||||
|
`CREATE INDEX idx_metadata_outbox_pending ON activity_outbox(status,next_attempt_ms,domain_uuid,sequence)`,
|
||||||
|
}
|
||||||
|
currentAssertions := append(append([]string(nil), assertions...),
|
||||||
|
`SELECT revision_uuid,document_hash FROM revision_document_refs WHERE 1=0`,
|
||||||
|
`SELECT uuid,domain_uuid,sequence,event_type,actor_uuid,target_kind,target_uuid,payload,idempotency_key,status,attempts,next_attempt_ms,last_error,created_at_ms,claimed_at_ms FROM activity_outbox WHERE 1=0`,
|
||||||
|
`SELECT domain_uuid,event_type,last_sequence FROM activity_outbox_heads WHERE 1=0`)
|
||||||
|
if r.backend == PostgreSQL {
|
||||||
|
return nil, []db.PostgreSQLMigration{
|
||||||
|
{Version: 1, Name: "initial portable core", Statements: statements, Assertions: assertions},
|
||||||
|
{Version: 2, Name: "revision references and outbox", Statements: referenceStatements, Assertions: currentAssertions},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return []db.SQLMigration{
|
||||||
|
{Version: 1, Name: "initial portable core", Statements: statements, Assertions: assertions},
|
||||||
|
{Version: 2, Name: "revision references and outbox", Statements: referenceStatements, Assertions: currentAssertions},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReferenceMigrationPreservesV1AndRetriesAtomically(t *testing.T) {
|
||||||
|
for _, backend := range []Backend{SQLite, PostgreSQL} {
|
||||||
|
t.Run(string(backend), func(t *testing.T) {
|
||||||
|
r := testRepository(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
id, err := r.CreatePage(ctx, "test", "/existing")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Reconstruct the preceding portable schema using its unchanged v1
|
||||||
|
// ledger. None of this targets legacy or production application data.
|
||||||
|
for _, q := range []string{`DROP TABLE revision_document_refs`, `DROP TABLE activity_outbox`, `DROP TABLE activity_outbox_heads`, `DELETE FROM schema_migration_steps WHERE component='core-metadata' AND version=2`} {
|
||||||
|
if _, err := r.database.ExecContext(ctx, q); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, err = r.database.ExecContext(ctx, `INSERT INTO revisions(uuid,object_uuid,document_hash,lang,content_type,created_at_ms,created_at) VALUES ('existing-revision',`+r.p(1)+`,`+r.p(2)+`,'und','text/plain',1000,1)`, id, hash("old"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// An unrelated existing table must stop adoption. The earlier DDL in
|
||||||
|
// the same migration must roll back and permit an explicit retry.
|
||||||
|
if _, err := r.database.ExecContext(ctx, `CREATE TABLE activity_outbox(unrelated INTEGER)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.InitializeFresh(ctx); err == nil {
|
||||||
|
t.Fatal("unmanaged outbox table adopted")
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM revision_document_refs`).Scan(&count); err == nil {
|
||||||
|
t.Fatal("partial v2 DDL remained")
|
||||||
|
}
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM schema_migration_steps WHERE component='core-metadata' AND version=2`).Scan(&count); err != nil || count != 0 {
|
||||||
|
t.Fatal("failed migration recorded", err)
|
||||||
|
}
|
||||||
|
if _, err := r.database.ExecContext(ctx, `DROP TABLE activity_outbox`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.InitializeFresh(ctx); err != nil {
|
||||||
|
t.Fatal("migration retry failed", err)
|
||||||
|
}
|
||||||
|
old, err := r.Head(ctx, "test", id, "und")
|
||||||
|
if err != nil || old.UUID != "existing-revision" || old.DocumentHash != hash("old") {
|
||||||
|
t.Fatal("v1 revision altered", err)
|
||||||
|
}
|
||||||
|
if got, err := r.ResolvePath(ctx, "test", "/existing"); err != nil || got != id {
|
||||||
|
t.Fatal("v1 binding altered", err)
|
||||||
|
}
|
||||||
|
if _, err := r.AppendRevision(ctx, "test", Revision{ObjectUUID: id, DocumentHash: hash("new"), ContentType: "text/plain"}, old.UUID); err != nil {
|
||||||
|
t.Fatal("post-migration save failed", err)
|
||||||
|
}
|
||||||
|
if err := r.database.QueryRowContext(ctx, `SELECT count(*) FROM activity_outbox`).Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatal("historical revisions spuriously notified", err, count)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -185,6 +185,9 @@ func (s *Server) adapterActionsForPath(r *http.Request, semanticPath string) ([]
|
|||||||
{ID: "download", Name: "download", Mode: "viewer", Builtin: true,
|
{ID: "download", Name: "download", Mode: "viewer", Builtin: true,
|
||||||
OpenURL: rawProjectionURL("rev:" + revision.UUID)},
|
OpenURL: rawProjectionURL("rev:" + revision.UUID)},
|
||||||
}
|
}
|
||||||
|
if (mediaType == "text/html" || mediaType == "text/markdown" || mediaType == "text/x-markdown") && s.systemExtensionEnabled(domainUUID, "viewer.slides") {
|
||||||
|
actions = append(actions, adapterAction{ID: "reveal", Name: "Reveal.js", Mode: "viewer", Builtin: true, OpenURL: "/v/slides" + semanticPath})
|
||||||
|
}
|
||||||
if selected.NeedsText || selected.ID == "html" || selected.ID == "excalidraw" {
|
if selected.NeedsText || selected.ID == "html" || selected.ID == "excalidraw" {
|
||||||
actions = append(actions, adapterAction{
|
actions = append(actions, adapterAction{
|
||||||
ID: "editor", Name: "Pages Wiki Editor", Mode: "editor",
|
ID: "editor", Name: "Pages Wiki Editor", Mode: "editor",
|
||||||
@@ -199,6 +202,9 @@ func (s *Server) adapterActionsForPath(r *http.Request, semanticPath string) ([]
|
|||||||
return plugins[i].DefaultEditor && !plugins[j].DefaultEditor
|
return plugins[i].DefaultEditor && !plugins[j].DefaultEditor
|
||||||
})
|
})
|
||||||
for _, plugin := range plugins {
|
for _, plugin := range plugins {
|
||||||
|
if plugin.Mode == "editor" && !s.store.SupportsHostedEditors() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
if pluginMatches(plugin, strings.ToLower(mediaType), filename) {
|
if pluginMatches(plugin, strings.ToLower(mediaType), filename) {
|
||||||
actions = append(actions, adapterAction{
|
actions = append(actions, adapterAction{
|
||||||
ID: plugin.ID, Name: plugin.Name, Mode: plugin.Mode,
|
ID: plugin.ID, Name: plugin.Name, Mode: plugin.Mode,
|
||||||
@@ -338,6 +344,10 @@ func (s *Server) handleOpenWith(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if selected.Mode == "editor" && !s.store.SupportsHostedEditors() {
|
||||||
|
http.Error(w, "hosted editors are unavailable on this database backend; use the built-in editor", http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
actions, err := s.adapterActionsForPath(r, semanticPath)
|
actions, err := s.adapterActionsForPath(r, semanticPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), 404)
|
http.Error(w, err.Error(), 404)
|
||||||
|
|||||||
@@ -100,6 +100,10 @@ func (s *Server) authorizeAdapterSession(r *http.Request, session *store.Adapter
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleAdapterSessionAPI(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleAdapterSessionAPI(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !s.store.SupportsHostedEditors() {
|
||||||
|
writeEventJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "hosted editors disabled for this database backend; use the built-in editor"})
|
||||||
|
return
|
||||||
|
}
|
||||||
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/api/v1/adapter/session"), "/")
|
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/api/v1/adapter/session"), "/")
|
||||||
if action == "exchange" && r.Method == http.MethodPost {
|
if action == "exchange" && r.Method == http.MethodPost {
|
||||||
var input struct {
|
var input struct {
|
||||||
|
|||||||
@@ -89,6 +89,7 @@ func (s *Server) handleSaveRevisionAPI(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
domainUUID := s.domainUUIDForRequest(r)
|
domainUUID := s.domainUUIDForRequest(r)
|
||||||
|
actorUUID := ""
|
||||||
if req.EditorPrincipal != nil {
|
if req.EditorPrincipal != nil {
|
||||||
principal, e := s.store.PrincipalForSession(domainUUID, s.authTokenFromRequest(r))
|
principal, e := s.store.PrincipalForSession(domainUUID, s.authTokenFromRequest(r))
|
||||||
id := ""
|
id := ""
|
||||||
@@ -106,10 +107,14 @@ func (s *Server) handleSaveRevisionAPI(
|
|||||||
api.WriteError(w, http.StatusUnauthorized, "authentication_required", "authentication required")
|
api.WriteError(w, http.StatusUnauthorized, "authentication_required", "authentication required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var revisionCount int
|
actorUUID = principal.UUID
|
||||||
_ = s.store.DB.QueryRow(`SELECT COUNT(*) FROM revisions WHERE object_uuid=?`, req.ObjectUUID).Scan(&revisionCount)
|
hasRevision, revisionErr := s.store.ObjectHasRevision(r.Context(), req.ObjectUUID)
|
||||||
|
if revisionErr != nil {
|
||||||
|
api.WriteError(w, 500, "storage_unavailable", "revision state unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
capability := "write"
|
capability := "write"
|
||||||
if revisionCount == 0 {
|
if !hasRevision {
|
||||||
capability = "create"
|
capability = "create"
|
||||||
}
|
}
|
||||||
allowed := false
|
allowed := false
|
||||||
@@ -129,12 +134,7 @@ func (s *Server) handleSaveRevisionAPI(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var revision *store.Revision
|
revision, err := s.store.SaveRevisionContentInDomain(r.Context(), domainUUID, actorUUID, req.ObjectUUID, []byte(req.Body), req.Message, req.Language, req.ContentType, req.Filename, req.BaseRevision)
|
||||||
if req.BaseRevision != nil {
|
|
||||||
revision, err = s.store.SaveRevisionContentIfHead(req.ObjectUUID, []byte(req.Body), req.Message, req.Language, req.ContentType, req.Filename, *req.BaseRevision)
|
|
||||||
} else {
|
|
||||||
revision, err = s.store.SaveRevisionContent(req.ObjectUUID, []byte(req.Body), req.Message, req.Language, req.ContentType, req.Filename)
|
|
||||||
}
|
|
||||||
if errors.Is(err, store.ErrRevisionConflict) {
|
if errors.Is(err, store.ErrRevisionConflict) {
|
||||||
api.WriteError(w, http.StatusConflict, "revision_conflict", "document changed; reload the language head before saving")
|
api.WriteError(w, http.StatusConflict, "revision_conflict", "document changed; reload the language head before saving")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -35,6 +35,17 @@ func (s *Server) handleAuthAdmin(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
panel := "auth"
|
panel := "auth"
|
||||||
switch r.FormValue("action") {
|
switch r.FormValue("action") {
|
||||||
|
case "save_trusted_session_policy":
|
||||||
|
panel = "auth-sessions"
|
||||||
|
days, err := strconv.Atoi(r.PostForm.Get("trusted_session_days"))
|
||||||
|
if err != nil || days < 0 || days > 30 {
|
||||||
|
http.Error(w, "trusted session lifetime must be between 0 and 30 days", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.store.SetConfigInDomain(domainUUID, "auth_trusted_session_days", strconv.Itoa(days)); err != nil {
|
||||||
|
http.Error(w, "could not save session policy", 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
case "save_session_policy":
|
case "save_session_policy":
|
||||||
panel = "auth-sessions"
|
panel = "auth-sessions"
|
||||||
minutes, err := strconv.Atoi(r.FormValue("session_minutes"))
|
minutes, err := strconv.Atoi(r.FormValue("session_minutes"))
|
||||||
|
|||||||
@@ -51,4 +51,8 @@ func TestBrowserCookieLoginLogoutChromium(t *testing.T) {
|
|||||||
if err := s.store.DB.QueryRow(`SELECT count(*) FROM auth_sessions WHERE revoked_at_ms>0`).Scan(&revoked); err != nil || revoked != 1 {
|
if err := s.store.DB.QueryRow(`SELECT count(*) FROM auth_sessions WHERE revoked_at_ms>0`).Scan(&revoked); err != nil || revoked != 1 {
|
||||||
t.Fatalf("browser revocations=%d %v", revoked, err)
|
t.Fatalf("browser revocations=%d %v", revoked, err)
|
||||||
}
|
}
|
||||||
|
var lifetime int64
|
||||||
|
if err := s.store.DB.QueryRow(`SELECT expires_at_ms-auth_time_ms FROM auth_sessions WHERE revoked_at_ms>0`).Scan(&lifetime); err != nil || lifetime != (30*24*time.Hour).Milliseconds() {
|
||||||
|
t.Fatalf("trusted browser lifetime=%d %v", lifetime, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -74,7 +74,7 @@ func (s *Server) handleCLIAuth(w http.ResponseWriter, r *http.Request, action st
|
|||||||
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
writeEventJSON(w, 400, map[string]string{"error": "invalid_request"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
id, device, code, err := s.store.StartCLIAuth(ctx, domain, cliOrigin(r), challenge)
|
id, device, code, err := s.store.StartCLIAuthForLogin(ctx, domain, cliOrigin(r), challenge, r.PostForm.Get("remember") == "1")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
cliAuthError(w, err)
|
cliAuthError(w, err)
|
||||||
return
|
return
|
||||||
@@ -140,6 +140,9 @@ func (s *Server) verifyCLIAuth(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
data := map[string]any{"CLIAuth": true, "CLIOrigin": grant.Origin, "CLIRequest": id}
|
data := map[string]any{"CLIAuth": true, "CLIOrigin": grant.Origin, "CLIRequest": id}
|
||||||
|
if grant.Remember {
|
||||||
|
data["CLIRememberDays"] = s.store.TrustedSessionDays(domain)
|
||||||
|
}
|
||||||
if grant.State != "pending" {
|
if grant.State != "pending" {
|
||||||
data["CLIDone"] = true
|
data["CLIDone"] = true
|
||||||
s.renderAuthPage(w, r, data)
|
s.renderAuthPage(w, r, data)
|
||||||
|
|||||||
@@ -28,6 +28,14 @@ func cliForm(s *Server, path string, form url.Values, cookie, origin string) *ht
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestCLIAuthOIDCFlow(t *testing.T) {
|
func TestCLIAuthOIDCFlow(t *testing.T) {
|
||||||
|
for _, remember := range []bool{false, true} {
|
||||||
|
t.Run(map[bool]string{false: "normal", true: "trusted"}[remember], func(t *testing.T) {
|
||||||
|
testCLIAuthOIDCFlow(t, remember)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCLIAuthOIDCFlow(t *testing.T, remember bool) {
|
||||||
s, api, domain := configFixture(t)
|
s, api, domain := configFixture(t)
|
||||||
principal := s.mustCLIPrincipal(t, domain, api)
|
principal := s.mustCLIPrincipal(t, domain, api)
|
||||||
// An enrolled local factor must not add a second challenge to OIDC consent.
|
// An enrolled local factor must not add a second challenge to OIDC consent.
|
||||||
@@ -43,7 +51,13 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
|||||||
}
|
}
|
||||||
verifier := strings.Repeat("x", 43)
|
verifier := strings.Repeat("x", 43)
|
||||||
sum := sha256.Sum256([]byte(verifier))
|
sum := sha256.Sum256([]byte(verifier))
|
||||||
start := cliForm(s, "/_/auth/cli/start", url.Values{"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}}, "", "")
|
startForm := url.Values{"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])}, "code_challenge_method": {"S256"}}
|
||||||
|
expectedSeconds := 24 * 60 * 60
|
||||||
|
if remember {
|
||||||
|
startForm.Set("remember", "1")
|
||||||
|
expectedSeconds *= 30
|
||||||
|
}
|
||||||
|
start := cliForm(s, "/_/auth/cli/start", startForm, "", "")
|
||||||
if start.Code != 200 {
|
if start.Code != 200 {
|
||||||
t.Fatalf("start %d %s", start.Code, start.Body.String())
|
t.Fatalf("start %d %s", start.Code, start.Body.String())
|
||||||
}
|
}
|
||||||
@@ -63,7 +77,12 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
|||||||
t.Fatalf("verify landing: %d %s", verify.Code, verify.Body.String())
|
t.Fatalf("verify landing: %d %s", verify.Code, verify.Body.String())
|
||||||
}
|
}
|
||||||
begin := httptest.NewRecorder()
|
begin := httptest.NewRecorder()
|
||||||
s.beginOIDC(begin, httptest.NewRequest("GET", "https://localhost/_/auth/oidc?cli="+id, nil))
|
// The browser query must not override the CLI's persisted choice.
|
||||||
|
tamperedRemember := "1"
|
||||||
|
if remember {
|
||||||
|
tamperedRemember = "0"
|
||||||
|
}
|
||||||
|
s.beginOIDC(begin, httptest.NewRequest("GET", "https://localhost/_/auth/oidc?cli="+id+"&remember="+tamperedRemember, nil))
|
||||||
if begin.Code != 302 {
|
if begin.Code != 302 {
|
||||||
t.Fatalf("oidc begin %d %s", begin.Code, begin.Body.String())
|
t.Fatalf("oidc begin %d %s", begin.Code, begin.Body.String())
|
||||||
}
|
}
|
||||||
@@ -86,6 +105,9 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
|||||||
for _, cookie := range complete.Result().Cookies() {
|
for _, cookie := range complete.Result().Cookies() {
|
||||||
if cookie.Name == authCookieName {
|
if cookie.Name == authCookieName {
|
||||||
browser = cookie.Value
|
browser = cookie.Value
|
||||||
|
if cookie.MaxAge != expectedSeconds {
|
||||||
|
t.Fatalf("cookie lifetime %d, want %d", cookie.MaxAge, expectedSeconds)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if browser == "" {
|
if browser == "" {
|
||||||
@@ -128,6 +150,7 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
|||||||
var result struct {
|
var result struct {
|
||||||
Token string `json:"access_token"`
|
Token string `json:"access_token"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
|
Expires int `json:"expires_in"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(exchange.Body.Bytes(), &result); err != nil {
|
if err := json.Unmarshal(exchange.Body.Bytes(), &result); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -135,6 +158,9 @@ func TestCLIAuthOIDCFlow(t *testing.T) {
|
|||||||
if !strings.HasPrefix(result.Token, "pw_api_") || result.Username != "admin" || result.Token == browser {
|
if !strings.HasPrefix(result.Token, "pw_api_") || result.Username != "admin" || result.Token == browser {
|
||||||
t.Fatal("invalid delegated credential")
|
t.Fatal("invalid delegated credential")
|
||||||
}
|
}
|
||||||
|
if result.Expires > expectedSeconds || result.Expires < expectedSeconds-10 {
|
||||||
|
t.Fatalf("CLI lifetime %d, want approximately %d", result.Expires, expectedSeconds)
|
||||||
|
}
|
||||||
if _, err := s.store.PrincipalForSession(domain, result.Token); err != nil {
|
if _, err := s.store.PrincipalForSession(domain, result.Token); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,12 +9,14 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type oidcChallenge struct{ Verifier, Nonce, Return, Issuer, ClientID, BrowserHash, CLIRequest string }
|
type oidcChallenge struct {
|
||||||
|
Verifier, Nonce, Return, Issuer, ClientID, BrowserHash, CLIRequest string
|
||||||
|
Remember bool
|
||||||
|
}
|
||||||
|
|
||||||
func logOIDCFailure(stage, domainUUID, issuer string, err error) {
|
func logOIDCFailure(stage, domainUUID, issuer string, err error) {
|
||||||
host := "invalid"
|
host := "invalid"
|
||||||
@@ -57,6 +59,7 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
|||||||
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
cliRequest := r.URL.Query().Get("cli")
|
cliRequest := r.URL.Query().Get("cli")
|
||||||
|
remember := r.URL.Query().Get("remember") == "1"
|
||||||
returnPath := safeReturnPath(r.URL.Query().Get("return"))
|
returnPath := safeReturnPath(r.URL.Query().Get("return"))
|
||||||
if cliRequest != "" {
|
if cliRequest != "" {
|
||||||
if !cliSecureTransport(r) || !cliProofPattern.MatchString(cliRequest) {
|
if !cliSecureTransport(r) || !cliProofPattern.MatchString(cliRequest) {
|
||||||
@@ -68,6 +71,12 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
returnPath = cliVerifyPath(cliRequest)
|
returnPath = cliVerifyPath(cliRequest)
|
||||||
|
grant, err := s.store.CLIAuthRequest(ctx, domainUUID, cliOrigin(r), cliRequest)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "invalid CLI request", 400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
remember = grant.Remember
|
||||||
}
|
}
|
||||||
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
|
metadata, err := fetchOIDCMetadata(ctx, config.Issuer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -77,7 +86,7 @@ func (s *Server) beginOIDC(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
verifier, nonce, browser := randomURLToken(32), randomURLToken(24), randomURLToken(32)
|
verifier, nonce, browser := randomURLToken(32), randomURLToken(24), randomURLToken(32)
|
||||||
browserDigest := sha256.Sum256([]byte(browser))
|
browserDigest := sha256.Sum256([]byte(browser))
|
||||||
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: returnPath, Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:]), CLIRequest: cliRequest}, 5*time.Minute)
|
state, err := s.store.CreateAuthChallenge(domainUUID, "", "oidc", oidcChallenge{Verifier: verifier, Nonce: nonce, Return: returnPath, Issuer: config.Issuer, ClientID: config.ClientID, BrowserHash: base64.RawURLEncoding.EncodeToString(browserDigest[:]), CLIRequest: cliRequest, Remember: remember}, 5*time.Minute)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), 500)
|
http.Error(w, err.Error(), 500)
|
||||||
return
|
return
|
||||||
@@ -205,7 +214,7 @@ func (s *Server) completeOIDC(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, "No local account matches the configured OIDC identity field", http.StatusForbidden)
|
http.Error(w, "No local account matches the configured OIDC identity field", http.StatusForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
token, err := s.store.CreateBrowserAuthSession(domainUUID, principal.UUID, 0)
|
token, lifetime, err := s.store.CreateLoginSession(domainUUID, principal.UUID, 0, true, challenge.Remember)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), 500)
|
http.Error(w, err.Error(), 500)
|
||||||
return
|
return
|
||||||
@@ -217,7 +226,7 @@ func (s *Server) completeOIDC(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
s.setAuthCookie(w, r, token)
|
s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds()))
|
||||||
http.Redirect(w, r, challenge.Return, http.StatusSeeOther)
|
http.Redirect(w, r, challenge.Return, http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -244,7 +253,7 @@ func (s *Server) requestMagicLink(w http.ResponseWriter, r *http.Request) {
|
|||||||
if principalErr == nil {
|
if principalErr == nil {
|
||||||
select {
|
select {
|
||||||
case s.smtpSlots <- struct{}{}:
|
case s.smtpSlots <- struct{}{}:
|
||||||
token, err := s.store.CreateAuthChallenge(domainUUID, principal.UUID, "magic-link", magicLinkChallenge{Return: safeReturnPath(r.FormValue("return")), Email: principal.Email}, 15*time.Minute)
|
token, err := s.store.CreateAuthChallenge(domainUUID, principal.UUID, "magic-link", magicLinkChallenge{Return: safeReturnPath(r.FormValue("return")), Email: principal.Email, Remember: r.PostForm.Get("remember") == "1"}, 15*time.Minute)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
<-s.smtpSlots
|
<-s.smtpSlots
|
||||||
break
|
break
|
||||||
@@ -276,18 +285,17 @@ func (s *Server) verifyMagicLink(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
config, configErr := s.store.AuthProviderConfig(domainUUID, "smtp")
|
config, configErr := s.store.AuthProviderConfig(domainUUID, "smtp")
|
||||||
var valid bool
|
valid, stateErr := s.store.ValidateMagicLinkIdentity(r.Context(), domainUUID, principalUUID, payload.Email)
|
||||||
stateErr := s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=? WHERE p.uuid=? AND p.state IN ('active','readonly') AND m.state='active' AND p.email=?)`, domainUUID, principalUUID, payload.Email).Scan(&valid)
|
|
||||||
if configErr != nil || !config.Enabled || stateErr != nil || !valid || payload.Email == "" {
|
if configErr != nil || !config.Enabled || stateErr != nil || !valid || payload.Email == "" {
|
||||||
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
|
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
token, err := s.store.CreateBrowserAuthSession(domainUUID, principalUUID, 0)
|
token, lifetime, err := s.store.CreateLoginSession(domainUUID, principalUUID, 0, true, payload.Remember)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
|
http.Error(w, "This sign-in link is invalid or expired", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.setAuthCookie(w, r, token)
|
s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds()))
|
||||||
http.Redirect(w, r, safeReturnPath(payload.Return), http.StatusSeeOther)
|
http.Redirect(w, r, safeReturnPath(payload.Return), http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -306,16 +314,11 @@ func (s *Server) renderAuthPage(w http.ResponseWriter, r *http.Request, data map
|
|||||||
data["LDAPEnabled"] = config.Enabled
|
data["LDAPEnabled"] = config.Enabled
|
||||||
}
|
}
|
||||||
data["Locale"] = s.getLocale(domainUUID)
|
data["Locale"] = s.getLocale(domainUUID)
|
||||||
|
data["TrustedSessionDays"] = s.store.TrustedSessionDays(domainUUID)
|
||||||
|
data["RememberRequested"] = r.PostForm.Get("remember") == "1"
|
||||||
transparency := s.homeGlassTransparency(domainUUID)
|
transparency := s.homeGlassTransparency(domainUUID)
|
||||||
data["HomeGlassTransparency"] = transparency
|
data["HomeGlassTransparency"] = transparency
|
||||||
data["HomeGlassOpacity"] = 100 - transparency
|
data["HomeGlassOpacity"] = 100 - transparency
|
||||||
configured, opacity := s.homeWallpaperConfig(domainUUID)
|
// Login has no wallpaper: private home images must not become public.
|
||||||
data["HomeWallpaperOpacity"] = strconv.FormatFloat(float64(opacity)/100, 'f', 2, 64)
|
|
||||||
if configured != "" {
|
|
||||||
// Only the administrator-selected login wallpaper is exposed; the
|
|
||||||
// request cannot choose an arbitrary document address.
|
|
||||||
data["HomeWallpaperURL"] = "/_/auth/wallpaper"
|
|
||||||
w.Header().Set("Cache-Control", "private, no-store")
|
|
||||||
}
|
|
||||||
s.renderWithContext(w, r, "auth.gohtml", data)
|
s.renderWithContext(w, r, "auth.gohtml", data)
|
||||||
}
|
}
|
||||||
@@ -62,7 +62,11 @@ func requestIsHTTPS(r *http.Request) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) setAuthCookie(w http.ResponseWriter, r *http.Request, token string) {
|
func (s *Server) setAuthCookie(w http.ResponseWriter, r *http.Request, token string) {
|
||||||
http.SetCookie(w, &http.Cookie{Name: authCookieName, Value: token, Path: "/", HttpOnly: true, Secure: requestIsHTTPS(r), SameSite: http.SameSiteLaxMode, MaxAge: s.store.AuthSessionLifetimeMinutes(s.domainUUIDForRequest(r)) * 60})
|
s.setAuthCookieForSeconds(w, r, token, s.store.AuthSessionLifetimeMinutes(s.domainUUIDForRequest(r))*60)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) setAuthCookieForSeconds(w http.ResponseWriter, r *http.Request, token string, seconds int) {
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: authCookieName, Value: token, Path: "/", HttpOnly: true, Secure: requestIsHTTPS(r), SameSite: http.SameSiteLaxMode, MaxAge: seconds})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) authTokenFromRequest(r *http.Request) string {
|
func (s *Server) authTokenFromRequest(r *http.Request) string {
|
||||||
@@ -160,6 +164,7 @@ func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
var principal *store.Principal
|
var principal *store.Principal
|
||||||
mfaLevel := 0
|
mfaLevel := 0
|
||||||
|
remember := r.PostForm.Get("remember") == "1"
|
||||||
if action == "setup" && setup && s.validBootstrapToken(domainUUID, r.FormValue("bootstrap_token")) {
|
if action == "setup" && setup && s.validBootstrapToken(domainUUID, r.FormValue("bootstrap_token")) {
|
||||||
principal, err = s.store.BootstrapOwner(domainUUID, r.FormValue("username"), r.FormValue("password"), r.FormValue("display_name"), r.FormValue("email"))
|
principal, err = s.store.BootstrapOwner(domainUUID, r.FormValue("username"), r.FormValue("password"), r.FormValue("display_name"), r.FormValue("email"))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -171,7 +176,7 @@ func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
|||||||
} else if action == "login" && !setup {
|
} else if action == "login" && !setup {
|
||||||
principal, err = s.store.AuthenticatePassword(r.FormValue("username"), r.FormValue("password"))
|
principal, err = s.store.AuthenticatePassword(r.FormValue("username"), r.FormValue("password"))
|
||||||
if err == nil && s.store.HasTOTP(principal.UUID) {
|
if err == nil && s.store.HasTOTP(principal.UUID) {
|
||||||
challenge, challengeErr := s.store.CreateTOTPLoginChallenge(domainUUID, principal.UUID)
|
challenge, challengeErr := s.store.CreateTOTPLoginChallengeForLogin(domainUUID, principal.UUID, remember)
|
||||||
if challengeErr != nil {
|
if challengeErr != nil {
|
||||||
err = challengeErr
|
err = challengeErr
|
||||||
} else if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
} else if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||||
@@ -191,7 +196,7 @@ func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
var principalUUID string
|
var principalUUID string
|
||||||
principalUUID, err = s.store.CompleteTOTPLoginChallenge(domainUUID, challenge, r.FormValue("code"))
|
principalUUID, remember, err = s.store.CompleteTOTPLoginChallengeForLogin(domainUUID, challenge, r.FormValue("code"))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
principal = &store.Principal{UUID: principalUUID}
|
principal = &store.Principal{UUID: principalUUID}
|
||||||
mfaLevel = 1
|
mfaLevel = 1
|
||||||
@@ -201,18 +206,14 @@ func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
|||||||
err = store.ErrAccessDenied
|
err = store.ErrAccessDenied
|
||||||
}
|
}
|
||||||
if err == nil {
|
if err == nil {
|
||||||
var token string
|
token, lifetime, issueErr := s.store.CreateLoginSession(domainUUID, principal.UUID, mfaLevel, !strings.Contains(r.Header.Get("Accept"), "application/json"), remember)
|
||||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
err = issueErr
|
||||||
token, err = s.store.CreateAuthSessionWithMFA(domainUUID, principal.UUID, mfaLevel)
|
|
||||||
} else {
|
|
||||||
token, err = s.store.CreateBrowserAuthSession(domainUUID, principal.UUID, mfaLevel)
|
|
||||||
}
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||||
writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": s.store.AuthSessionLifetimeMinutes(domainUUID) * 60})
|
writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": int(lifetime.Seconds())})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.setAuthCookie(w, r, token)
|
s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds()))
|
||||||
http.Redirect(w, r, safeReturnPath(r.FormValue("return")), http.StatusSeeOther)
|
http.Redirect(w, r, safeReturnPath(r.FormValue("return")), http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -221,7 +221,7 @@ func (s *Server) handleLDAPLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if s.store.HasTOTP(principal.UUID) {
|
if s.store.HasTOTP(principal.UUID) {
|
||||||
challenge, challengeErr := s.store.CreateTOTPLoginChallenge(domainUUID, principal.UUID)
|
challenge, challengeErr := s.store.CreateTOTPLoginChallengeForLogin(domainUUID, principal.UUID, r.PostForm.Get("remember") == "1")
|
||||||
if challengeErr != nil {
|
if challengeErr != nil {
|
||||||
http.Error(w, "authentication unavailable", http.StatusServiceUnavailable)
|
http.Error(w, "authentication unavailable", http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
@@ -234,20 +234,15 @@ func (s *Server) handleLDAPLogin(w http.ResponseWriter, r *http.Request) {
|
|||||||
s.renderAuthPage(w, r, map[string]any{"MFA": true, "Return": returnPath})
|
s.renderAuthPage(w, r, map[string]any{"MFA": true, "Return": returnPath})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var token string
|
token, lifetime, err := s.store.CreateLoginSession(domainUUID, principal.UUID, 0, !strings.Contains(r.Header.Get("Accept"), "application/json"), r.PostForm.Get("remember") == "1")
|
||||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
|
||||||
token, err = s.store.CreateAuthSession(domainUUID, principal.UUID)
|
|
||||||
} else {
|
|
||||||
token, err = s.store.CreateBrowserAuthSession(domainUUID, principal.UUID, 0)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "authentication unavailable", http.StatusServiceUnavailable)
|
http.Error(w, "authentication unavailable", http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
if strings.Contains(r.Header.Get("Accept"), "application/json") {
|
||||||
writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": s.store.AuthSessionLifetimeMinutes(domainUUID) * 60})
|
writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": int(lifetime.Seconds())})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.setAuthCookie(w, r, token)
|
s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds()))
|
||||||
http.Redirect(w, r, returnPath, http.StatusSeeOther)
|
http.Redirect(w, r, returnPath, http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSessionPolicyAdminUIAndCookie(t *testing.T) {
|
func TestSessionPolicyAdminUIAndCookie(t *testing.T) {
|
||||||
@@ -48,3 +49,99 @@ func TestSessionPolicyAdminUIAndCookie(t *testing.T) {
|
|||||||
t.Fatalf("cookie policy %#v", cookies)
|
t.Fatalf("cookie policy %#v", cookies)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTrustedSessionPolicyAndRevocation(t *testing.T) {
|
||||||
|
s, admin, domain := configFixture(t)
|
||||||
|
p := s.mustCLIPrincipal(t, domain, admin)
|
||||||
|
for _, days := range []string{"30", "7", "0"} {
|
||||||
|
form := url.Values{"action": {"save_trusted_session_policy"}, "trusted_session_days": {days}}
|
||||||
|
w := configRequest(s, admin, "POST", "/-/sys/config/auth", form)
|
||||||
|
if w.Code != 303 {
|
||||||
|
t.Fatalf("policy %s: %d %s", days, w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
want := 24 * time.Hour
|
||||||
|
if days == "30" {
|
||||||
|
want *= 30
|
||||||
|
}
|
||||||
|
if days == "7" {
|
||||||
|
want *= 7
|
||||||
|
}
|
||||||
|
for _, browser := range []bool{false, true} {
|
||||||
|
token, lifetime, err := s.store.CreateLoginSession(domain, p, 0, browser, true)
|
||||||
|
if err != nil || lifetime != want {
|
||||||
|
t.Fatalf("duration %v %v", lifetime, err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.PrincipalForSession(domain, token); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = s.store.RevokeAuthSession(token); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.PrincipalForSession(domain, token); err == nil {
|
||||||
|
t.Fatal("revoked trusted session accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
s.handleAuth(w, httptest.NewRequest("GET", "https://localhost/_/auth/login", nil))
|
||||||
|
if strings.Contains(w.Body.String(), `id="auth-remember"`) != (days != "0") {
|
||||||
|
t.Fatal("login choice does not reflect policy")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"", "-1", "31", "abc"} {
|
||||||
|
w := configRequest(s, admin, "POST", "/-/sys/config/auth", url.Values{"action": {"save_trusted_session_policy"}, "trusted_session_days": {bad}})
|
||||||
|
if w.Code != 400 {
|
||||||
|
t.Fatalf("invalid policy %q accepted: %d", bad, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
user, err := s.store.CreatePasswordAccount(domain, "trusted-reader", "a long test password", "Reader", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = s.store.SetConfigInDomain(domain, "auth_trusted_session_days", "30"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, _, err := s.store.CreateLoginSession(domain, user.UUID, 0, false, true)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
w := configRequest(s, token, "POST", "/-/sys/config/auth", url.Values{"action": {"save_trusted_session_policy"}, "trusted_session_days": {"7"}})
|
||||||
|
if w.Code != 403 {
|
||||||
|
t.Fatalf("reader changed trusted policy: %d", w.Code)
|
||||||
|
}
|
||||||
|
if err = s.store.SetPrincipalState(domain, user.UUID, "suspended"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.PrincipalForSession(domain, token); err == nil {
|
||||||
|
t.Fatal("suspended trusted session accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrustedSessionExpiryIsFixed(t *testing.T) {
|
||||||
|
s, admin, domain := configFixture(t)
|
||||||
|
p := s.mustCLIPrincipal(t, domain, admin)
|
||||||
|
token, lifetime, err := s.store.CreateLoginSession(domain, p, 0, false, true)
|
||||||
|
if err != nil || lifetime != 30*24*time.Hour {
|
||||||
|
t.Fatalf("trusted default: %v %v", lifetime, err)
|
||||||
|
}
|
||||||
|
var id string
|
||||||
|
var expiry int64
|
||||||
|
if err = s.store.DB.QueryRow(`SELECT uuid,expires_at_ms FROM auth_sessions ORDER BY rowid DESC LIMIT 1`).Scan(&id, &expiry); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = s.store.SetConfigInDomain(domain, "auth_trusted_session_days", "0"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.PrincipalForSession(domain, token); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var after int64
|
||||||
|
if err = s.store.DB.QueryRow(`SELECT expires_at_ms FROM auth_sessions WHERE uuid=?`, id).Scan(&after); err != nil || after != expiry {
|
||||||
|
t.Fatalf("policy/read changed expiry: %d %d %v", expiry, after, err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.DB.Exec(`UPDATE auth_sessions SET expires_at_ms=? WHERE uuid=?`, time.Now().Add(-time.Second).UnixMilli(), id); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.PrincipalForSession(domain, token); err == nil {
|
||||||
|
t.Fatal("expired trusted session accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
for lang, entries := range map[string]map[string]string{
|
||||||
|
"en": {"auth.remember": "Keep me signed in on this trusted device", "auth.days": "days", "auth.remember_cli": "Keep this CLI signed in for up to", "auth.trusted_days": "Trusted device session (days; 0 disables)"},
|
||||||
|
"ja": {"auth.remember": "信頼できる端末でログインを維持する", "auth.days": "日間", "auth.remember_cli": "CLIのログイン継続期間(最大)", "auth.trusted_days": "信頼できる端末の有効期間(日・0で無効)"},
|
||||||
|
} {
|
||||||
|
for key, value := range entries {
|
||||||
|
translations[lang][key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBrowserUploadQueueChromium(t *testing.T) {
|
||||||
|
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||||
|
t.Skip("opt-in Chromium")
|
||||||
|
}
|
||||||
|
for _, width := range []string{"1280", "390"} {
|
||||||
|
t.Run(width, func(t *testing.T) { testBrowserUploadQueueChromium(t, width) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testBrowserUploadQueueChromium(t *testing.T, width string) {
|
||||||
|
s, token, domain := configFixture(t)
|
||||||
|
s.mux.HandleFunc("/v/browser/", s.handleBrowser)
|
||||||
|
s.mux.HandleFunc("/v/upload", s.handleUpload)
|
||||||
|
object, err := s.store.CreatePageAtPathInDomain(domain, "/drop/existing.txt")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.SaveRevisionContent(object, []byte("original"), "", "und", "text/plain", "existing.txt"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.CreatePageAtPathInDomain(domain, "/drop/sub/seed"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
script, err := os.ReadFile("internal/server/testdata/browser-upload.js")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var active, peak atomic.Int32
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.Host = "localhost"
|
||||||
|
r.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if r.Method == "POST" && r.URL.Path == "/v/upload" {
|
||||||
|
n := active.Add(1)
|
||||||
|
defer active.Add(-1)
|
||||||
|
if n > peak.Load() {
|
||||||
|
peak.Store(n)
|
||||||
|
}
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/v/browser/drop" && r.URL.Query().Has("fixture") {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||||
|
for key, values := range rec.Header() {
|
||||||
|
w.Header()[key] = values
|
||||||
|
}
|
||||||
|
w.WriteHeader(rec.Code)
|
||||||
|
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", "<script>"+string(script)+"</script></body>", 1)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
out, err := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+"/v/browser/drop?fixture=1", t.TempDir(), "/tmp/pageswiki-browser-upload-"+width+".png", width, "850").CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("browser: %v %s", err, out)
|
||||||
|
}
|
||||||
|
if peak.Load() != 1 {
|
||||||
|
t.Fatalf("parallel uploads: %d", peak.Load())
|
||||||
|
}
|
||||||
|
for _, path := range []string{"/drop/日本語 #1.txt", "/drop/sub/nested.txt"} {
|
||||||
|
if _, err = s.store.ResolvePathInDomain(domain, path); err != nil {
|
||||||
|
t.Fatal(path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err = s.store.ResolvePathInDomain(domain, "/drop/cancel.txt"); err == nil {
|
||||||
|
t.Fatal("cancelled file uploaded")
|
||||||
|
}
|
||||||
|
revs, err := s.store.ListRevisions(object)
|
||||||
|
if err != nil || len(revs) != 1 {
|
||||||
|
t.Fatal("existing file overwritten")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -36,14 +36,7 @@ func (s *Server) calendars() (*calendar.Repository, error) {
|
|||||||
s.calendarErr = errors.New("calendar storage unavailable")
|
s.calendarErr = errors.New("calendar storage unavailable")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
s.calendarRepo, s.calendarErr = calendar.New(filepath.Join(s.store.DocumentRoot, "calendars"), s.store.DB)
|
s.calendarRepo, s.calendarErr = s.store.NewCalendarRepository(context.Background())
|
||||||
if s.calendarErr == nil {
|
|
||||||
s.calendarRepo.PublicAllowed = func(domain string) bool {
|
|
||||||
var allowed bool
|
|
||||||
err := s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM locality_publication_policies p JOIN domains d ON d.uuid=p.domain_uuid AND d.enabled=1 JOIN config c ON c.domain_uuid=p.domain_uuid AND c.key='authorization_mode' AND c.value='enforcing' WHERE p.domain_uuid=? AND p.node_kind='domain' AND p.node_uuid=p.domain_uuid AND p.policy='public')`, domain).Scan(&allowed)
|
|
||||||
return err == nil && allowed
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
return s.calendarRepo, s.calendarErr
|
return s.calendarRepo, s.calendarErr
|
||||||
}
|
}
|
||||||
@@ -316,9 +309,8 @@ func (s *Server) handleCalendarAPI(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
id = p.UUID
|
id = p.UUID
|
||||||
}
|
}
|
||||||
var count int
|
active, e := s.store.ActiveDomainMember(r.Context(), domain, id)
|
||||||
e := s.store.DB.QueryRowContext(r.Context(), `SELECT COUNT(*) FROM domain_memberships WHERE domain_uuid=? AND principal_uuid=? AND state='active'`, domain, id).Scan(&count)
|
if e != nil || !active {
|
||||||
if e != nil || count != 1 {
|
|
||||||
http.Error(w, "unknown collaborator", 400)
|
http.Error(w, "unknown collaborator", 400)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -161,14 +161,7 @@ func fetchCalendarSource(ctx context.Context, client *http.Client, c calendar.Ca
|
|||||||
return events, response.Header.Get("ETag"), response.Header.Get("Last-Modified"), false, e
|
return events, response.Header.Get("ETag"), response.Header.Get("Last-Modified"), false, e
|
||||||
}
|
}
|
||||||
func (s *Server) ensureCalendarSweep() error {
|
func (s *Server) ensureCalendarSweep() error {
|
||||||
var exists bool
|
return s.store.EnsureBuiltinEventDefinition(store.EventDefinition{UUID: calendarSweepType, Name: "Calendar source synchronization", EventType: calendarSweepType, EventKey: calendarSweepType, Payload: "{}", ScheduleKind: "interval", IntervalSeconds: 60, Enabled: true, Priority: -10, MaxAttempts: 1})
|
||||||
if e := s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM event_definitions WHERE uuid=?)`, calendarSweepType).Scan(&exists); e != nil {
|
|
||||||
return e
|
|
||||||
}
|
|
||||||
if exists {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return s.store.SaveEventDefinition(&store.EventDefinition{UUID: calendarSweepType, Name: "Calendar source synchronization", EventType: calendarSweepType, EventKey: calendarSweepType, Payload: "{}", ScheduleKind: "interval", IntervalSeconds: 60, Enabled: true, Priority: -10, MaxAttempts: 1})
|
|
||||||
}
|
}
|
||||||
func (s *Server) enqueueCalendarSource(domain, id string, force bool) (bool, error) {
|
func (s *Server) enqueueCalendarSource(domain, id string, force bool) (bool, error) {
|
||||||
b, _ := json.Marshal(calendarSyncPayload{Domain: domain, Calendar: id, Force: force})
|
b, _ := json.Marshal(calendarSyncPayload{Domain: domain, Calendar: id, Force: force})
|
||||||
@@ -220,8 +213,7 @@ func (s *Server) runCalendarSource(job *store.EventJob) error {
|
|||||||
if !c.Source.Enabled || (!p.Force && c.Source.Next > time.Now().UnixMilli()) {
|
if !c.Source.Enabled || (!p.Force && c.Source.Next > time.Now().UnixMilli()) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
var active bool
|
active, e := s.store.ActiveDomainMember(context.Background(), p.Domain, c.Owner)
|
||||||
e = s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid JOIN domains d ON d.uuid=m.domain_uuid WHERE m.domain_uuid=? AND m.principal_uuid=? AND m.state='active' AND p.state='active' AND d.enabled=1)`, p.Domain, c.Owner).Scan(&active)
|
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,6 +72,15 @@ func TestCalendarUpcomingDefaultsAndBounds(t *testing.T) {
|
|||||||
t.Fatal("tomorrow event in today's widget", event.Start)
|
t.Fatal("tomorrow event in today's widget", event.Start)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
w = calendarRequest(s, token, "GET", calendarAPI+"upcoming?period=day&date="+end.Format("2006-01-02"), "", "")
|
||||||
|
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
||||||
|
t.Fatal(w.Code, w.Body)
|
||||||
|
}
|
||||||
|
for _, event := range result.Events {
|
||||||
|
if !event.Start.Before(end.AddDate(0, 0, 1)) || !event.End.After(end) {
|
||||||
|
t.Fatal("event outside tomorrow", event.Start, event.End)
|
||||||
|
}
|
||||||
|
}
|
||||||
if w = calendarRequest(s, "", "GET", calendarAPI+"upcoming", "", ""); w.Code != 403 {
|
if w = calendarRequest(s, "", "GET", calendarAPI+"upcoming", "", ""); w.Code != 403 {
|
||||||
t.Fatal("anonymous access", w.Code)
|
t.Fatal("anonymous access", w.Code)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"pageswiki/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
type cityAutoPlanItem struct {
|
type cityAutoPlanItem struct {
|
||||||
@@ -46,15 +48,7 @@ func (s *Server) availableCityAutoName(domain, kind, parent, base, boundary stri
|
|||||||
}
|
}
|
||||||
name = stem + "-" + hex.EncodeToString(sum[:8])
|
name = stem + "-" + hex.EncodeToString(sum[:8])
|
||||||
}
|
}
|
||||||
var exists bool
|
exists, err := s.store.CityNameExists(domain, kind, parent, name)
|
||||||
var err error
|
|
||||||
if kind == "spot" {
|
|
||||||
err = s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM spots WHERE domain_uuid=? AND name=? AND state!='archived')`, domain, name).Scan(&exists)
|
|
||||||
} else if kind == "quartier" {
|
|
||||||
err = s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM zones WHERE domain_uuid=? AND kind='quartier' AND name=? AND state!='archived')`, domain, name).Scan(&exists)
|
|
||||||
} else {
|
|
||||||
err = s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM zones WHERE domain_uuid=? AND parent_uuid=? AND name=? AND state!='archived')`, domain, parent, name).Scan(&exists)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -66,19 +60,29 @@ func (s *Server) availableCityAutoName(domain, kind, parent, base, boundary stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) buildCityAutoPlan(domainUUID string) ([]cityAutoPlanItem, error) {
|
func (s *Server) buildCityAutoPlan(domainUUID string) ([]cityAutoPlanItem, error) {
|
||||||
rows, err := s.store.DB.Query(`SELECT p.path,p.object_uuid FROM paths p WHERE p.domain_uuid=? AND p.path LIKE '/%' AND p.path!='/u' AND p.path NOT LIKE '/u/%'
|
candidates, err := s.store.CityAutoCandidates(domainUUID)
|
||||||
AND NOT EXISTS(SELECT 1 FROM city_page_overrides ov JOIN spots dest ON dest.uuid=ov.spot_uuid AND dest.domain_uuid=ov.domain_uuid AND dest.state!='archived' WHERE ov.domain_uuid=p.domain_uuid AND ov.page_uuid=p.object_uuid)
|
|
||||||
ORDER BY p.path`, domainUUID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
|
||||||
var out []cityAutoPlanItem
|
var out []cityAutoPlanItem
|
||||||
for rows.Next() {
|
// Many Pages share one boundary. Resolve each boundary once, without
|
||||||
var semanticPath, pageUUID string
|
// retaining a database cursor while making nested repository calls.
|
||||||
if err := rows.Scan(&semanticPath, &pageUUID); err != nil {
|
type lookupResult struct {
|
||||||
return nil, err
|
node store.CityNodeDetail
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
cache := map[string]lookupResult{}
|
||||||
|
lookup := func(kind, parent, boundary string) (store.CityNodeDetail, error) {
|
||||||
|
key := kind + "\x00" + parent + "\x00" + boundary
|
||||||
|
if r, ok := cache[key]; ok {
|
||||||
|
return r.node, r.err
|
||||||
}
|
}
|
||||||
|
node, err := s.store.CityNodeOverlappingPath(domainUUID, kind, parent, boundary)
|
||||||
|
cache[key] = lookupResult{node, err}
|
||||||
|
return node, err
|
||||||
|
}
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
semanticPath, pageUUID := candidate.Path, candidate.ObjectUUID
|
||||||
parts := strings.Split(strings.Trim(semanticPath, "/"), "/")
|
parts := strings.Split(strings.Trim(semanticPath, "/"), "/")
|
||||||
if len(parts) < 3 || parts[0] == "system" {
|
if len(parts) < 3 || parts[0] == "system" {
|
||||||
continue
|
continue
|
||||||
@@ -93,19 +97,25 @@ func (s *Server) buildCityAutoPlan(domainUUID string) ([]cityAutoPlanItem, error
|
|||||||
item.SpotPath = item.StreetPath + "/_undefined"
|
item.SpotPath = item.StreetPath + "/_undefined"
|
||||||
}
|
}
|
||||||
item.Action = "create"
|
item.Action = "create"
|
||||||
if q, e := s.store.CityNodeOverlappingPath(domainUUID, "quartier", "", item.QuartierPath); e == nil {
|
if q, e := lookup("quartier", "", item.QuartierPath); e == nil {
|
||||||
item.Quartier = q.Name
|
item.Quartier = q.Name
|
||||||
item.Action = "merge"
|
item.Action = "merge"
|
||||||
if st, e := s.store.CityNodeOverlappingPath(domainUUID, "street", q.UUID, item.StreetPath); e == nil {
|
if st, e := lookup("street", q.UUID, item.StreetPath); e == nil {
|
||||||
item.Street = st.Name
|
item.Street = st.Name
|
||||||
if spot, e := s.store.CityNodeOverlappingPath(domainUUID, "spot", st.UUID, item.SpotPath); e == nil {
|
if spot, e := lookup("spot", st.UUID, item.SpotPath); e == nil {
|
||||||
item.Spot = spot.Name
|
item.Spot = spot.Name
|
||||||
|
} else if !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
return nil, e
|
||||||
}
|
}
|
||||||
|
} else if !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
return nil, e
|
||||||
}
|
}
|
||||||
|
} else if !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
return nil, e
|
||||||
}
|
}
|
||||||
out = append(out, item)
|
out = append(out, item)
|
||||||
}
|
}
|
||||||
return out, rows.Err()
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) applyCityAutoPlan(domainUUID, actor string) (int, error) {
|
func (s *Server) applyCityAutoPlan(domainUUID, actor string) (int, error) {
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ func (s *Server) handleCityGovernance(w http.ResponseWriter, r *http.Request) {
|
|||||||
kind := map[string]string{"spots": "spot", "domains": "domain"}[p[0]]
|
kind := map[string]string{"spots": "spot", "domains": "domain"}[p[0]]
|
||||||
var err error
|
var err error
|
||||||
if p[0] == "zones" {
|
if p[0] == "zones" {
|
||||||
err = s.store.DB.QueryRowContext(r.Context(), `SELECT kind FROM zones WHERE uuid=? AND domain_uuid=?`, p[1], domain).Scan(&kind)
|
kind, err = s.store.CityZoneKind(r.Context(), domain, p[1])
|
||||||
}
|
}
|
||||||
var result any
|
var result any
|
||||||
if err == nil && automatic {
|
if err == nil && automatic {
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ func (s *Server) transpileMarkdownFromPath(r *http.Request, path string, mode ma
|
|||||||
|
|
||||||
html := latest.Body
|
html := latest.Body
|
||||||
if mode == markdownProjection {
|
if mode == markdownProjection {
|
||||||
html = s.expandMacrosForRequest(r, html, path, s.domainUUIDForRequest(r))
|
html = s.safeHTMLProjection(r, html, path, true)
|
||||||
} else {
|
} else {
|
||||||
return grammaratur.HTMLToMarkdownAuthoring(html)
|
return grammaratur.HTMLToMarkdownAuthoring(html)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -131,14 +131,17 @@ func (s *Server) handleConfig(
|
|||||||
campusAdminRequired := strings.HasPrefix(section, "campus-") || strings.HasPrefix(section, "domain-") || section == "instance-status"
|
campusAdminRequired := strings.HasPrefix(section, "campus-") || strings.HasPrefix(section, "domain-") || section == "instance-status"
|
||||||
if campusAdminRequired {
|
if campusAdminRequired {
|
||||||
targetCampusUUID := currentDomain.CampusUUID
|
targetCampusUUID := currentDomain.CampusUUID
|
||||||
|
var targetErr error
|
||||||
if section == "domain-create" {
|
if section == "domain-create" {
|
||||||
targetCampusUUID = r.FormValue("domain_campus_uuid")
|
targetCampusUUID = r.FormValue("domain_campus_uuid")
|
||||||
} else if section == "domain-update" || section == "domain-delete" || section == "domain-entry" || section == "domain-projection" {
|
} else if section == "domain-update" || section == "domain-delete" || section == "domain-entry" || section == "domain-projection" {
|
||||||
_ = s.store.DB.QueryRow(`SELECT campus_uuid FROM domains WHERE id=?`, r.FormValue("domain_id")).Scan(&targetCampusUUID)
|
id, _ := strconv.ParseInt(r.FormValue("domain_id"), 10, 64)
|
||||||
|
targetCampusUUID, targetErr = s.store.ConfigTargetCampus(r.Context(), true, id)
|
||||||
} else if section != "campus-create" && r.FormValue("campus_id") != "" {
|
} else if section != "campus-create" && r.FormValue("campus_id") != "" {
|
||||||
_ = s.store.DB.QueryRow(`SELECT uuid FROM campuses WHERE id=?`, r.FormValue("campus_id")).Scan(&targetCampusUUID)
|
id, _ := strconv.ParseInt(r.FormValue("campus_id"), 10, 64)
|
||||||
|
targetCampusUUID, targetErr = s.store.ConfigTargetCampus(r.Context(), false, id)
|
||||||
}
|
}
|
||||||
if !s.store.IsCampusAdmin(targetCampusUUID, principal.UUID) {
|
if targetErr != nil || !s.store.IsCampusAdmin(targetCampusUUID, principal.UUID) {
|
||||||
http.Error(w, "campus admin required", http.StatusForbidden)
|
http.Error(w, "campus admin required", http.StatusForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -824,6 +827,10 @@ func (s *Server) handleConfig(
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "zombie-purge":
|
case "zombie-purge":
|
||||||
|
if !s.store.SupportsZombieGC() {
|
||||||
|
http.Error(w, store.ErrBackendFeatureUnavailable.Error(), http.StatusServiceUnavailable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
_, err = s.store.PurgeZombieObjectsInDomain(
|
_, err = s.store.PurgeZombieObjectsInDomain(
|
||||||
r.Context(), domainUUID,
|
r.Context(), domainUUID,
|
||||||
@@ -918,7 +925,7 @@ func (s *Server) handleConfig(
|
|||||||
s.getZombieGraceHours(s.domainUUIDForRequest(r))
|
s.getZombieGraceHours(s.domainUUIDForRequest(r))
|
||||||
|
|
||||||
var zombies []store.ZombieObject
|
var zombies []store.ZombieObject
|
||||||
if r.URL.Query().Get("panel") == "objects" {
|
if r.URL.Query().Get("panel") == "objects" && s.store.SupportsZombieGC() {
|
||||||
zombies, err =
|
zombies, err =
|
||||||
s.store.ListZombieObjectsInDomain(
|
s.store.ListZombieObjectsInDomain(
|
||||||
r.Context(), s.domainUUIDForRequest(r),
|
r.Context(), s.domainUUIDForRequest(r),
|
||||||
@@ -1078,49 +1085,50 @@ func (s *Server) handleConfig(
|
|||||||
s.getSystemNavItems(s.domainUUIDForRequest(r)),
|
s.getSystemNavItems(s.domainUUIDForRequest(r)),
|
||||||
NavContext{},
|
NavContext{},
|
||||||
),
|
),
|
||||||
"HomePath": homePath,
|
"HomePath": homePath,
|
||||||
"HomeWallpaperPath": homeWallpaperPath,
|
"HomeWallpaperPath": homeWallpaperPath,
|
||||||
"HomeWallpaperOpacity": homeWallpaperOpacity,
|
"HomeWallpaperOpacity": homeWallpaperOpacity,
|
||||||
"HomeGlassTransparency": s.homeGlassTransparency(domainUUID),
|
"HomeGlassTransparency": s.homeGlassTransparency(domainUUID),
|
||||||
"HomePalette": s.homePalette(domainUUID),
|
"HomePalette": s.homePalette(domainUUID),
|
||||||
"HomeLayout": s.homeLayout(s.domainUUIDForRequest(r)),
|
"HomeLayout": s.homeLayout(s.domainUUIDForRequest(r)),
|
||||||
"HomeBookmarks": s.homeBookmarksText(s.domainUUIDForRequest(r)),
|
"HomeBookmarks": s.homeBookmarksText(s.domainUUIDForRequest(r)),
|
||||||
"VirtualFolderPages": s.getVirtualFolderPages(s.domainUUIDForRequest(r)),
|
"VirtualFolderPages": s.getVirtualFolderPages(s.domainUUIDForRequest(r)),
|
||||||
"WikiName": wikiName,
|
"WikiName": wikiName,
|
||||||
"Locale": s.getLocale(s.domainUUIDForRequest(r)),
|
"Locale": s.getLocale(s.domainUUIDForRequest(r)),
|
||||||
"Timezone": s.getTimezoneName(s.domainUUIDForRequest(r)),
|
"Timezone": s.getTimezoneName(s.domainUUIDForRequest(r)),
|
||||||
"Theme": s.getTheme(s.domainUUIDForRequest(r)),
|
"Theme": s.getTheme(s.domainUUIDForRequest(r)),
|
||||||
"ThemeOptions": themeOptions(),
|
"ThemeOptions": themeOptions(),
|
||||||
"EditorKeymap": s.getEditorKeymap(s.domainUUIDForRequest(r)),
|
"EditorKeymap": s.getEditorKeymap(s.domainUUIDForRequest(r)),
|
||||||
"EditorFormat": s.getEditorFormat(s.domainUUIDForRequest(r)),
|
"EditorFormat": s.getEditorFormat(s.domainUUIDForRequest(r)),
|
||||||
"EditorPreviewDefault": s.getEditorPreviewDefault(s.domainUUIDForRequest(r)),
|
"EditorPreviewDefault": s.getEditorPreviewDefault(s.domainUUIDForRequest(r)),
|
||||||
"EditorSyntax": s.getEditorSyntaxHighlight(s.domainUUIDForRequest(r)),
|
"EditorSyntax": s.getEditorSyntaxHighlight(s.domainUUIDForRequest(r)),
|
||||||
"EditorAutocomplete": s.getEditorAutocomplete(s.domainUUIDForRequest(r)),
|
"EditorAutocomplete": s.getEditorAutocomplete(s.domainUUIDForRequest(r)),
|
||||||
"ZombieGraceHours": zombieGraceHours,
|
"ZombieGraceHours": zombieGraceHours,
|
||||||
"Objects": recent,
|
"Objects": recent,
|
||||||
"ZombieObjects": zombies,
|
"ZombieObjects": zombies,
|
||||||
"Domains": domains,
|
"Domains": domains,
|
||||||
"DomainEntries": domainEntries,
|
"DomainEntries": domainEntries,
|
||||||
"PeriodicalProjections": projections,
|
"PeriodicalProjections": projections,
|
||||||
"PeriodicalKinds": []string{"diary", "blog"},
|
"PeriodicalKinds": []string{"diary", "blog"},
|
||||||
"CampusLegacyPeers": legacyPeers,
|
"CampusLegacyPeers": legacyPeers,
|
||||||
"Campuses": campuses,
|
"Campuses": campuses,
|
||||||
"CampusManaged": campusManaged,
|
"CampusManaged": campusManaged,
|
||||||
"CampusOnline": campusOnline,
|
"CampusOnline": campusOnline,
|
||||||
"FederationInstances": federationInstances,
|
"FederationInstances": federationInstances,
|
||||||
"CampusTokens": campusTokens,
|
"CampusTokens": campusTokens,
|
||||||
"AuthPrincipals": authPrincipals,
|
"AuthPrincipals": authPrincipals,
|
||||||
"AuthSessions": authSessions,
|
"AuthSessions": authSessions,
|
||||||
"AuthSessionMinutes": s.store.AuthSessionLifetimeMinutes(s.domainUUIDForRequest(r)),
|
"AuthSessionMinutes": s.store.AuthSessionLifetimeMinutes(s.domainUUIDForRequest(r)),
|
||||||
"OIDCConfig": oidcConfig,
|
"AuthTrustedSessionDays": s.store.TrustedSessionDays(s.domainUUIDForRequest(r)),
|
||||||
"SMTPConfig": smtpConfig,
|
"OIDCConfig": oidcConfig,
|
||||||
"LDAPConfig": ldapConfig,
|
"SMTPConfig": smtpConfig,
|
||||||
"LDAPTest": r.URL.Query().Get("ldap_test"),
|
"LDAPConfig": ldapConfig,
|
||||||
"ObjectsCampusUUID": selectedCampusUUID,
|
"LDAPTest": r.URL.Query().Get("ldap_test"),
|
||||||
"ObjectsDomainUUID": selectedDomain.UUID,
|
"ObjectsCampusUUID": selectedCampusUUID,
|
||||||
"ObjectsDomainHost": objectsDomainHost,
|
"ObjectsDomainUUID": selectedDomain.UUID,
|
||||||
"HomeNavItemsConfig": s.getHomeNavItems(s.domainUUIDForRequest(r)),
|
"ObjectsDomainHost": objectsDomainHost,
|
||||||
"SystemNavItemsConfig": s.getSystemNavItems(s.domainUUIDForRequest(r)),
|
"HomeNavItemsConfig": s.getHomeNavItems(s.domainUUIDForRequest(r)),
|
||||||
|
"SystemNavItemsConfig": s.getSystemNavItems(s.domainUUIDForRequest(r)),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"html"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const csvEditorFixtureBody = "\ufeff\"name\",description\r\n日本語,\"a,b\r\nnext\"\r\n"
|
||||||
|
|
||||||
|
func TestCSVEditorRevisionAndBounds(t *testing.T) {
|
||||||
|
s, token, domain, _ := editorFixture(t)
|
||||||
|
object, err := s.store.CreatePageAtPathInDomain(domain, "/table.csv")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
first, err := s.store.SaveRevisionContent(object, []byte(csvEditorFixtureBody), "", "und", "text/csv; charset=utf-8", "table.csv")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, query := range []string{"", "?edittype=markdown", "?lang=und"} {
|
||||||
|
w := configRequest(s, token, "GET", "/e/-/table.csv"+query, nil)
|
||||||
|
if w.Code != 200 || !strings.Contains(w.Body.String(), `data-csv="true"`) || !strings.Contains(w.Body.String(), `value="code"`) || strings.Contains(w.Body.String(), `data-editor-action="markdown"`) {
|
||||||
|
t.Fatalf("editor %d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
head, _ := s.store.GetRevisionForExactLanguage(object, "und")
|
||||||
|
if head.UUID != first.UUID {
|
||||||
|
t.Fatal("GET changed revision")
|
||||||
|
}
|
||||||
|
save := func(auth, base, body string) int {
|
||||||
|
data, _ := json.Marshal(map[string]any{"object_uuid": object, "body": body, "lang": "und", "content_type": "text/csv; charset=utf-8", "filename": "table.csv", "base_revision_uuid": base})
|
||||||
|
r := httptest.NewRequest("POST", "http://localhost/_/api/v1/revisions/save", bytes.NewReader(data))
|
||||||
|
r.Header.Set("Authorization", "Bearer "+auth)
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
return w.Code
|
||||||
|
}
|
||||||
|
changed := strings.Replace(csvEditorFixtureBody, "日本語", "更新", 1)
|
||||||
|
if code := save(token, first.UUID, changed); code != 200 {
|
||||||
|
t.Fatal("save", code)
|
||||||
|
}
|
||||||
|
if code := save(token, first.UUID, "stale"); code != 409 {
|
||||||
|
t.Fatal("stale save", code)
|
||||||
|
}
|
||||||
|
head, _ = s.store.GetRevisionForExactLanguage(object, "und")
|
||||||
|
if head.Body != changed || head.ContentType != "text/csv; charset=utf-8" || head.Filename != "table.csv" {
|
||||||
|
t.Fatal("CSV altered")
|
||||||
|
}
|
||||||
|
state := configRequest(s, token, "GET", "/_/api/v1/editor/state?uuid="+object+"&lang=und&revision="+first.UUID, nil)
|
||||||
|
var content struct {
|
||||||
|
Body string
|
||||||
|
Editable bool
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(state.Body.Bytes(), &content); err != nil || state.Code != 200 || !content.Editable || content.Body != csvEditorFixtureBody {
|
||||||
|
t.Fatal("restore", state.Code, err)
|
||||||
|
}
|
||||||
|
reader, err := s.store.CreatePasswordAccount(domain, "csvreader", "a long test password", "Reader", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = s.store.SetPrincipalState(domain, reader.UUID, "readonly"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
denied, _ := s.store.CreateAuthSession(domain, reader.UUID)
|
||||||
|
if code := save(denied, head.UUID, "forbidden"); code != 403 {
|
||||||
|
t.Fatal("readonly save", code)
|
||||||
|
}
|
||||||
|
// Initial CSV is embedded as an escaped JS string to preserve CRLF. A
|
||||||
|
// field must not terminate that script or become executable markup.
|
||||||
|
if _, err = s.store.SaveRevisionContent(object, []byte("\"</script><script>alert(1)</script>\",value\r\n"), "", "und", "text/csv", "table.csv"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
escaped := configRequest(s, token, "GET", "/e/-/table.csv", nil)
|
||||||
|
if escaped.Code != 200 || strings.Contains(escaped.Body.String(), "<script>alert(1)</script>") || !strings.Contains(escaped.Body.String(), `\u003c/script\u003e`) {
|
||||||
|
t.Fatal("CSV script string was not escaped")
|
||||||
|
}
|
||||||
|
for _, input := range []struct {
|
||||||
|
body []byte
|
||||||
|
code int
|
||||||
|
}{{[]byte(strings.Repeat("x", maxCSVMacroBytes+1)), 413}, {[]byte{0xff, 0xfe}, 415}, {[]byte("a,\x00"), 415}} {
|
||||||
|
rev, e := s.store.SaveRevisionContent(object, input.body, "", "und", "text/csv", "table.csv")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
w := configRequest(s, token, "GET", "/e/-/table.csv", nil)
|
||||||
|
if w.Code != input.code {
|
||||||
|
t.Fatalf("editor bounds %d wanted %d", w.Code, input.code)
|
||||||
|
}
|
||||||
|
w = configRequest(s, token, "GET", "/_/api/v1/editor/state?uuid="+object+"&lang=und&revision="+rev.UUID, nil)
|
||||||
|
if w.Code != input.code {
|
||||||
|
t.Fatalf("state bounds %d wanted %d", w.Code, input.code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCSVEditorChromium(t *testing.T) {
|
||||||
|
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
||||||
|
t.Skip("opt-in Chromium")
|
||||||
|
}
|
||||||
|
for _, width := range []string{"1280", "390"} {
|
||||||
|
t.Run(width, func(t *testing.T) {
|
||||||
|
s, token, domain, _ := editorFixture(t)
|
||||||
|
object, err := s.store.CreatePageAtPathInDomain(domain, "/table.csv")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.store.SaveRevisionContent(object, []byte(csvEditorFixtureBody), "", "und", "text/csv; charset=utf-8", "table.csv"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
script, err := os.ReadFile("internal/server/testdata/csv-editor.js")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
r.Host = "localhost"
|
||||||
|
r.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
if r.URL.Path == "/e/-/table.csv" {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(rec, r)
|
||||||
|
for k, v := range rec.Header() {
|
||||||
|
w.Header()[k] = v
|
||||||
|
}
|
||||||
|
w.WriteHeader(rec.Code)
|
||||||
|
_, policy, _ := strings.Cut(rec.Header().Get("Content-Security-Policy"), "'nonce-")
|
||||||
|
nonce, _, _ := strings.Cut(policy, "'")
|
||||||
|
w.Write([]byte(strings.Replace(rec.Body.String(), "</body>", `<script nonce="`+html.EscapeString(nonce)+`">`+string(script)+"</script></body>", 1)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
out, err := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", server.URL+"/e/-/table.csv", t.TempDir(), "/tmp/pageswiki-csv-editor-"+width+".png", width, "850").CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("browser: %v %s", err, out)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/csv"
|
||||||
|
"errors"
|
||||||
|
"html"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"path"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Projection only: no network fetch, shared rendered cache or write-back.
|
||||||
|
const maxCSVMacroBytes = 256 << 10
|
||||||
|
|
||||||
|
var csvMacroRE = regexp.MustCompile(`^\{\{csv:(?:"([^"]+)"|([^\s}]+))(.*?)\}\}$`)
|
||||||
|
var csvRangeRE = regexp.MustCompile(`^([A-Z]{1,2})([1-9][0-9]{0,3}):([A-Z]{1,2})([1-9][0-9]{0,3})$`)
|
||||||
|
|
||||||
|
type csvMacroOptions struct {
|
||||||
|
Path, Revision string
|
||||||
|
Row, EndRow, Column, EndColumn int
|
||||||
|
Header bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseCSVMacro(raw string) (csvMacroOptions, error) {
|
||||||
|
o := csvMacroOptions{Row: 1, EndRow: 200, Column: 1, EndColumn: 32, Header: true}
|
||||||
|
m := csvMacroRE.FindStringSubmatch(raw)
|
||||||
|
bad := errors.New("invalid CSV macro")
|
||||||
|
if m == nil {
|
||||||
|
return o, bad
|
||||||
|
}
|
||||||
|
o.Path = m[1]
|
||||||
|
if o.Path == "" {
|
||||||
|
o.Path = m[2]
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(o.Path, "/") || strings.HasPrefix(o.Path, "//") || path.Clean(o.Path) != o.Path || strings.ContainsAny(o.Path, "\\\x00\r\n") || len(o.Path) > 2048 {
|
||||||
|
return o, bad
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, field := range strings.Fields(m[3]) {
|
||||||
|
key, value, ok := strings.Cut(field, "=")
|
||||||
|
if !ok || seen[key] {
|
||||||
|
return o, bad
|
||||||
|
}
|
||||||
|
seen[key] = true
|
||||||
|
switch key {
|
||||||
|
case "header":
|
||||||
|
if value != "true" && value != "false" {
|
||||||
|
return o, bad
|
||||||
|
}
|
||||||
|
o.Header = value == "true"
|
||||||
|
case "rev":
|
||||||
|
if _, err := uuid.Parse(value); len(value) != 36 || err != nil {
|
||||||
|
return o, bad
|
||||||
|
}
|
||||||
|
o.Revision = value
|
||||||
|
case "range":
|
||||||
|
parts := csvRangeRE.FindStringSubmatch(strings.ToUpper(value))
|
||||||
|
if parts == nil {
|
||||||
|
return o, bad
|
||||||
|
}
|
||||||
|
col := func(s string) int {
|
||||||
|
n := 0
|
||||||
|
for _, c := range s {
|
||||||
|
n = n*26 + int(c-'A') + 1
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
o.Column, o.EndColumn = col(parts[1]), col(parts[3])
|
||||||
|
o.Row, _ = strconv.Atoi(parts[2])
|
||||||
|
o.EndRow, _ = strconv.Atoi(parts[4])
|
||||||
|
if o.Column > o.EndColumn || o.EndColumn > 100 || o.EndColumn-o.Column >= 32 || o.Row > o.EndRow || o.EndRow > 2000 || o.EndRow-o.Row >= 200 {
|
||||||
|
return o, bad
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return o, bad
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return o, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func csvMacroTable(body []byte, o csvMacroOptions) (string, error) {
|
||||||
|
if len(body) > maxCSVMacroBytes || !utf8.Valid(body) || strings.IndexByte(string(body), 0) >= 0 {
|
||||||
|
return "", errors.New("invalid CSV input")
|
||||||
|
}
|
||||||
|
reader := csv.NewReader(strings.NewReader(strings.TrimPrefix(string(body), "\ufeff")))
|
||||||
|
reader.FieldsPerRecord = -1
|
||||||
|
var out strings.Builder
|
||||||
|
out.WriteString(`<div class="csv-projection table-scroll"><table><caption><a href="` + html.EscapeString((&url.URL{Path: o.Path}).EscapedPath()) + `" title="Revision ` + html.EscapeString(o.Revision) + `">` + html.EscapeString(path.Base(o.Path)) + `</a></caption><tbody>`)
|
||||||
|
for row := 1; row <= o.EndRow; row++ {
|
||||||
|
record, err := reader.Read()
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(record) > 100 {
|
||||||
|
return "", errors.New("too many CSV columns")
|
||||||
|
}
|
||||||
|
if row < o.Row {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out.WriteString("<tr>")
|
||||||
|
cell := "td"
|
||||||
|
if o.Header && row == o.Row {
|
||||||
|
cell = "th"
|
||||||
|
}
|
||||||
|
for col := o.Column; col <= o.EndColumn && col <= len(record); col++ {
|
||||||
|
if len(record[col-1]) > 16<<10 {
|
||||||
|
return "", errors.New("CSV cell too large")
|
||||||
|
}
|
||||||
|
// Never expand macros, formulas or markup from CSV cells.
|
||||||
|
out.WriteString("<" + cell + ">" + html.EscapeString(record[col-1]) + "</" + cell + ">")
|
||||||
|
}
|
||||||
|
out.WriteString("</tr>")
|
||||||
|
}
|
||||||
|
out.WriteString("</tbody></table></div>")
|
||||||
|
return out.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) expandCSVMacro(r *http.Request, macro string) string {
|
||||||
|
fallback := `<span class="projection-warning">` + html.EscapeString(translate(s.getLocale(s.domainUUIDForRequest(r)), "viewer.csv_unavailable")) + `</span>`
|
||||||
|
o, err := parseCSVMacro(macro)
|
||||||
|
if err != nil || r.Context().Err() != nil || s.store == nil || isAnonymousProjection(r) || !s.pathReadFilter(r)(o.Path) {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
domain := s.domainUUIDForRequest(r)
|
||||||
|
object, err := s.store.ResolvePathInDomainContext(r.Context(), domain, o.Path)
|
||||||
|
if err != nil {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
rev, err := s.store.GetLatestRevisionMetadataForLanguagesContext(r.Context(), object, s.revisionLanguageCandidates(r))
|
||||||
|
if o.Revision != "" {
|
||||||
|
rev, err = s.store.GetRevisionMetadataContext(r.Context(), o.Revision)
|
||||||
|
}
|
||||||
|
if err != nil || rev == nil || rev.UUID == "" || rev.ObjectUUID != object {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
media := strings.ToLower(strings.TrimSpace(strings.Split(rev.ContentType, ";")[0]))
|
||||||
|
if media != "text/csv" && media != "application/csv" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
size, err := s.store.DocumentSizeContext(r.Context(), rev.DocumentHash)
|
||||||
|
if err != nil || size > maxCSVMacroBytes {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
window, err := s.store.ReadDocumentWindowContext(r.Context(), rev.DocumentHash, 0, maxCSVMacroBytes)
|
||||||
|
if err != nil || window.Truncated {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
o.Revision = rev.UUID
|
||||||
|
table, err := csvMacroTable(window.Data, o)
|
||||||
|
if err != nil || r.Context().Err() != nil {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
return table
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
translations["en"]["viewer.csv_unavailable"] = "CSV unavailable (access, format or size limit)."
|
||||||
|
translations["ja"]["viewer.csv_unavailable"] = "CSVを表示できません(権限・形式・サイズ制限)。"
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"pageswiki/internal/grammaratur"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCSVMacroParsingAndBounds(t *testing.T) {
|
||||||
|
for _, raw := range []string{`{{csv:/data/a.csv}}`, `{{csv:"/data/日本語 table.csv" range=B2:D4 header=false}}`} {
|
||||||
|
if _, err := parseCSVMacro(raw); err != nil {
|
||||||
|
t.Fatal(raw, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, raw := range []string{`{{csv:https://example.org/a.csv}}`, `{{csv://evil/a.csv}}`, `{{csv:/a/../secret}}`, `{{csv:/a range=A1:C201}}`, `{{csv:/a range=A1:AG2}}`, `{{csv:/a range=A2001:B2002}}`, `{{csv:/a range=D2:A1}}`, `{{csv:/a header=yes}}`, `{{csv:/a header=true header=false}}`, `{{csv:/a unsupported=1}}`, `{{csv:/a rev=bad}}`} {
|
||||||
|
if _, err := parseCSVMacro(raw); err == nil {
|
||||||
|
t.Fatal("accepted", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o, _ := parseCSVMacro(`{{csv:/data/a.csv range=A1:C3}}`)
|
||||||
|
body := "\ufeffname,description,formula\r\n日本語,\"a,b\r\nnext\",=1+1\r\n<script>,{{children:/private}},end\r\n"
|
||||||
|
got, err := csvMacroTable([]byte(body), o)
|
||||||
|
if err != nil || !strings.Contains(got, "<th>name</th>") || !strings.Contains(got, "a,b\nnext") || !strings.Contains(got, "<script>") || !strings.Contains(got, "{{children:/private}}") {
|
||||||
|
t.Fatalf("CSV: %s %v", got, err)
|
||||||
|
}
|
||||||
|
checkInertProjection(t, got)
|
||||||
|
for _, bad := range [][]byte{[]byte("a,\"unterminated"), {0xff}, []byte("a,\x00"), []byte(strings.Repeat("x", maxCSVMacroBytes+1)), []byte(strings.Repeat("x", (16<<10)+1)), []byte(strings.Repeat("a,", 101))} {
|
||||||
|
if _, err := csvMacroTable(bad, o); err == nil {
|
||||||
|
t.Fatal("invalid/large CSV accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCSVMacroProjectionAuthorizationAndRevision(t *testing.T) {
|
||||||
|
s, token, domain := configFixture(t)
|
||||||
|
object, err := s.store.CreatePageAtPathInDomain(domain, "/data/report.csv")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
first, err := s.store.SaveRevisionContent(object, []byte("name,value\r\noriginal,1\r\n"), "", "und", "text/csv", "report.csv")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := httptest.NewRequest("GET", "http://localhost/guide", nil)
|
||||||
|
r.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
macro := `{{csv:/data/report.csv range=A1:B2}}`
|
||||||
|
got := s.safeHTMLProjection(r, "<p>"+macro+"</p><code>"+macro+"</code>", "/guide", true)
|
||||||
|
if strings.Count(got, `class="csv-projection table-scroll"`) != 1 || !strings.Contains(got, "original") || !strings.Contains(got, "<code>"+macro+"</code>") || !strings.Contains(got, first.UUID) {
|
||||||
|
t.Fatal(got)
|
||||||
|
}
|
||||||
|
second, err := s.store.SaveRevisionContent(object, []byte("name,value\nupdated,2\n"), "", "und", "text/csv", "report.csv")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got = s.safeHTMLProjection(r, macro, "/guide", true)
|
||||||
|
if !strings.Contains(got, "updated") || !strings.Contains(got, second.UUID) || strings.Contains(got, "original") {
|
||||||
|
t.Fatal("stale projection", got)
|
||||||
|
}
|
||||||
|
got = s.safeHTMLProjection(r, `{{csv:/data/report.csv rev=`+first.UUID+`}}`, "/guide", true)
|
||||||
|
if !strings.Contains(got, "original") || strings.Contains(got, "updated") {
|
||||||
|
t.Fatal("pinned revision", got)
|
||||||
|
}
|
||||||
|
other, err := s.store.CreatePageAtPathInDomain(domain, "/data/other.csv")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
foreign, err := s.store.SaveRevisionContent(other, []byte("SECRET_DIFFERENT_OBJECT"), "", "und", "text/csv", "other.csv")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got = s.safeHTMLProjection(r, `{{csv:/data/report.csv rev=`+foreign.UUID+`}}`, "/guide", true)
|
||||||
|
if strings.Contains(got, "SECRET") || strings.Contains(got, "<table") {
|
||||||
|
t.Fatal("foreign revision leaked", got)
|
||||||
|
}
|
||||||
|
// A fresh request with no credentials must not reuse another reader's table.
|
||||||
|
denied := httptest.NewRequest("GET", "http://localhost/guide", nil)
|
||||||
|
got = s.safeHTMLProjection(denied, macro, "/guide", true)
|
||||||
|
if strings.Contains(got, "updated") || strings.Contains(got, "<table") {
|
||||||
|
t.Fatal("unauthorized table", got)
|
||||||
|
}
|
||||||
|
public := r.WithContext(context.WithValue(r.Context(), anonymousProjectionKey{}, true))
|
||||||
|
if got = s.safeHTMLProjection(public, macro, "/guide", true); strings.Contains(got, "<table") {
|
||||||
|
t.Fatal("anonymous CSV expanded", got)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(r.Context())
|
||||||
|
cancel()
|
||||||
|
if got = s.expandCSVMacro(r.WithContext(ctx), macro); strings.Contains(got, "<table") {
|
||||||
|
t.Fatal("cancelled projection ran")
|
||||||
|
}
|
||||||
|
// Authoring must preserve the macro, never bake projected rows into HTML.
|
||||||
|
source := "<p>" + macro + "</p>"
|
||||||
|
md, err := grammaratur.HTMLToMarkdownAuthoring(source)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(grammaratur.MarkdownAuthoringHTML(md), macro) || strings.Contains(md, "updated") {
|
||||||
|
t.Fatal("authoring expanded CSV", md)
|
||||||
|
}
|
||||||
|
// Four distinct CSV reads per projection, then leave authored syntax literal.
|
||||||
|
input := strings.Repeat(macro, 2)
|
||||||
|
for _, col := range []string{"A1:A2", "B1:B2", "A1:B1", "A2:B2"} {
|
||||||
|
input += `{{csv:/data/report.csv range=` + col + `}}`
|
||||||
|
}
|
||||||
|
got = s.safeHTMLProjection(r, input, "/guide", true)
|
||||||
|
if strings.Count(got, "<table>") != 5 || !strings.Contains(got, "{{csv:") {
|
||||||
|
t.Fatal("CSV budget not enforced", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 402 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user