Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbcb8a24b4 | ||
|
|
367bfa3a2a | ||
|
|
aaa0e457bf | ||
|
|
4a863fe63c | ||
|
|
1fd2de4c6b | ||
|
|
fdf6dffc84 | ||
|
|
37c1443219 | ||
|
|
6a67fd9afe | ||
|
|
0c7897d695 | ||
|
|
46c185d928 |
No files matched your search
@@ -15,6 +15,24 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if len(os.Args) > 1 && os.Args[1] == "mysql-identity-schema" {
|
||||||
|
if err := runMySQLSchemaCommand(os.Args[2:], os.Stdout, "identity"); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(os.Args) > 1 && os.Args[1] == "mysql-namespace-schema" {
|
||||||
|
if err := runMySQLComponentSchema(os.Args[2:], os.Stdout, true); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(os.Args) > 1 && os.Args[1] == "mysql-ml-schema" {
|
||||||
|
if err := runMySQLMLSchema(os.Args[2:], os.Stdout); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
if len(os.Args) > 1 && os.Args[1] == "migrate-postgres" {
|
if len(os.Args) > 1 && os.Args[1] == "migrate-postgres" {
|
||||||
if err := runPostgreSQLMigration(os.Args[2:], os.Stdout); err != nil {
|
if err := runPostgreSQLMigration(os.Args[2:], os.Stdout); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func runMySQLMLSchema(args []string, out io.Writer) error {
|
||||||
|
return runMySQLComponentSchema(args, out, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runMySQLComponentSchema(args []string, out io.Writer, namespace bool) error {
|
||||||
|
component := "ml"
|
||||||
|
if namespace {
|
||||||
|
component = "namespace"
|
||||||
|
}
|
||||||
|
return runMySQLSchemaCommand(args, out, component)
|
||||||
|
}
|
||||||
|
func runMySQLSchemaCommand(args []string, out io.Writer, component string) error {
|
||||||
|
command, scope, label := "mysql-ml-schema", "ml-only", "ML component ONLY"
|
||||||
|
if component == "namespace" {
|
||||||
|
command, scope, label = "mysql-namespace-schema", "namespace-pilot", "Namespace pilot ONLY (includes shared config/ML schema; no Domain mutations or authentication)"
|
||||||
|
} else if component == "identity" {
|
||||||
|
command, scope, label = "mysql-identity-schema", "identity-pilot", "Identity/group persistence pilot ONLY; not a complete authentication server"
|
||||||
|
} else if component != "ml" {
|
||||||
|
return errors.New("unknown MySQL component")
|
||||||
|
}
|
||||||
|
usage := "pageswiki " + command + " {status|check|apply|resume} [--timeout 2m] [--allow-insecure]\nUses PAGESWIKI_MYSQL_DSN. " + label + "; does not make Pages serve from MySQL. status/check are read-only. apply refuses interrupted migrations; resume explicitly verifies and continues."
|
||||||
|
if len(args) == 0 || args[0] == "--help" {
|
||||||
|
_, e := fmt.Fprintln(out, usage)
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
mode := args[0]
|
||||||
|
if mode != "status" && mode != "check" && mode != "apply" && mode != "resume" {
|
||||||
|
return errors.New("invalid MySQL component schema action")
|
||||||
|
}
|
||||||
|
f := flag.NewFlagSet(command, flag.ContinueOnError)
|
||||||
|
f.SetOutput(out)
|
||||||
|
timeout := f.Duration("timeout", 2*time.Minute, "operation deadline")
|
||||||
|
insecure := f.Bool("allow-insecure", false, "isolated disposable database tests only")
|
||||||
|
if e := f.Parse(args[1:]); e != nil {
|
||||||
|
if errors.Is(e, flag.ErrHelp) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if f.NArg() != 0 || *timeout <= 0 {
|
||||||
|
return errors.New("invalid MySQL component schema arguments")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||||
|
defer cancel()
|
||||||
|
database, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: os.Getenv("PAGESWIKI_MYSQL_DSN"), AllowInsecure: *insecure})
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
var repo interface {
|
||||||
|
PrepareSchema(context.Context) error
|
||||||
|
InspectSchema(context.Context) (db.MySQLMigrationStatus, error)
|
||||||
|
ResumeSchema(context.Context) error
|
||||||
|
} = store.NewMySQLMLRepository(database)
|
||||||
|
if component == "namespace" {
|
||||||
|
repo = store.NewMySQLNamespaceRepository(database)
|
||||||
|
} else if component == "identity" {
|
||||||
|
repo = store.NewMySQLIdentityRepository(database)
|
||||||
|
}
|
||||||
|
switch mode {
|
||||||
|
case "apply":
|
||||||
|
e = repo.PrepareSchema(ctx)
|
||||||
|
case "resume":
|
||||||
|
e = repo.ResumeSchema(ctx)
|
||||||
|
}
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
status, e := repo.InspectSchema(ctx)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if e = json.NewEncoder(out).Encode(struct {
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
db.MySQLMigrationStatus
|
||||||
|
}{scope, status}); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if mode == "check" && (status.Dirty || status.Pending > 0) {
|
||||||
|
return errors.New("MySQL component schema is pending or interrupted")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-sql-driver/mysql"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMySQLMLSchemaArguments(t *testing.T) {
|
||||||
|
t.Setenv("PAGESWIKI_MYSQL_DSN", "")
|
||||||
|
for _, args := range [][]string{{"bad"}, {"apply", "--timeout", "0s"}, {"resume", "unexpected"}, {"status"}} {
|
||||||
|
var out bytes.Buffer
|
||||||
|
if runMySQLMLSchema(args, &out) == nil {
|
||||||
|
t.Fatal("accepted invalid arguments", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
if e := runMySQLMLSchema([]string{"--help"}, &out); e != nil || !strings.Contains(out.String(), "ML component ONLY") {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLMLSchemaCommand(t *testing.T) {
|
||||||
|
for _, component := range []string{"ml", "namespace", "identity"} {
|
||||||
|
t.Run(component, func(t *testing.T) { testMySQLSchemaCommand(t, component) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testMySQLSchemaCommand(t *testing.T, component string) {
|
||||||
|
dsn := os.Getenv("PAGESWIKI_TEST_MYSQL_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("set disposable MySQL DSN")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
admin, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: dsn, AllowInsecure: true})
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
defer admin.Close()
|
||||||
|
name := "pages_ml_cmd_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||||
|
if _, e = admin.ExecContext(ctx, "CREATE DATABASE "+name+" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if _, e := admin.Exec("DROP DATABASE " + name); e != nil {
|
||||||
|
t.Error(e)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
c, e := mysql.ParseDSN(dsn)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
c.DBName = name
|
||||||
|
t.Setenv("PAGESWIKI_MYSQL_DSN", c.FormatDSN())
|
||||||
|
var out bytes.Buffer
|
||||||
|
run := func(action string) error {
|
||||||
|
return runMySQLSchemaCommand([]string{action, "--allow-insecure"}, &out, component)
|
||||||
|
}
|
||||||
|
pending := `"pending":2`
|
||||||
|
if component == "namespace" {
|
||||||
|
pending = `"pending":3`
|
||||||
|
} else if component == "identity" {
|
||||||
|
pending = `"pending":5`
|
||||||
|
}
|
||||||
|
if e = run("status"); e != nil || !strings.Contains(out.String(), pending) {
|
||||||
|
t.Fatal(out.String(), e)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if e = admin.QueryRowContext(ctx, `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=?`, name).Scan(&count); e != nil || count != 0 {
|
||||||
|
t.Fatal("status wrote schema", count, e)
|
||||||
|
}
|
||||||
|
if e = run("check"); e == nil {
|
||||||
|
t.Fatal("pending check succeeded")
|
||||||
|
}
|
||||||
|
if e = run("apply"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = run("check"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if component != "ml" {
|
||||||
|
if e = admin.QueryRowContext(ctx, "SELECT COUNT(*) FROM "+name+".domains").Scan(&count); e != nil || count != 0 {
|
||||||
|
t.Fatal("schema command created unauthorized Domain data", count, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ledger, version := "machine-learning", 2
|
||||||
|
if component == "namespace" {
|
||||||
|
ledger, version = "store-namespaces", 1
|
||||||
|
} else if component == "identity" {
|
||||||
|
ledger, version = "store-auth-core", 2
|
||||||
|
}
|
||||||
|
if _, e = admin.ExecContext(ctx, "UPDATE "+name+".schema_mysql_migrations SET state='running',next_operation=1 WHERE component=? AND version=?", ledger, version); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = run("apply"); e == nil {
|
||||||
|
t.Fatal("dirty apply succeeded")
|
||||||
|
}
|
||||||
|
if e = run("resume"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# 2026年11月・じさばかん展示環境
|
||||||
|
|
||||||
|
展示時の構成と合成データツールを保存する。汎用本番デプロイのテンプレートではない。
|
||||||
|
利用者から展示成功の報告あり。2026-11-30の整理では実クラスタへ接続していない。
|
||||||
|
|
||||||
|
## ファイルの役割
|
||||||
|
|
||||||
|
| ファイル | 用途・注意 |
|
||||||
|
| --- | --- |
|
||||||
|
| `postgres.yaml` | PostgreSQL、専用ディレクトリ初期化、Service、NetworkPolicy。初期化だけroot、常駐は非root |
|
||||||
|
| `bootstrap.yaml` | **新規展示DB向け、一度限り**。emptyDirのSQLiteからPostgreSQLへ初期import。GitOpsの継続同期へ入れない |
|
||||||
|
| `app.yaml` | bootstrap成功後のPages本体とService。1 replica、Recreate、固定digest |
|
||||||
|
| `storage-check.yaml.example` | 非rootで専用一時ディレクトリを使う保存先の検査 |
|
||||||
|
| `root-storage-check.yaml.example` | rootで専用一時ディレクトリを準備し、非rootで検査する別案。運営の許可が必要 |
|
||||||
|
| `pageswiki.yaml.example` | 初期のSQLite向け一般ひな形。**展示NFSには適用しない** |
|
||||||
|
| `demo/` | 架空データのカタログ、生成・投入手順 |
|
||||||
|
|
||||||
|
`kubectl apply -f deploy/kubernetes/exhibition/` のような一括適用は禁止。
|
||||||
|
namespace、PVC、Secret、公開Gateway/TLSは、このディレクトリだけでは準備されない。
|
||||||
|
Secretの値、秘密鍵、kubeconfig、投入済みDBはGitへ含めない。初期化Jobの削除・再実行を更新手段にしない。
|
||||||
|
|
||||||
|
最後に指定された公開名は `pages.anya.jisaba.sh`、Serviceは `pageswiki:80`。
|
||||||
|
公開TLS終端はNOC側。古いFQDNとCloudflare案は
|
||||||
|
[当時の運用記録](../../../docs/operations/exhibition-kubernetes-dns-tls.md)に経緯として残す。
|
||||||
|
固定digest・UID・PVC subPath・Secret名・証明書期限は展示当時の値であり、再利用時に照合が必要。
|
||||||
|
|
||||||
|
## ローカル検証
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tools/exhibition-demo -v
|
||||||
|
go test ./tools/exhibition-demo
|
||||||
|
```
|
||||||
|
|
||||||
|
合成データだけでZIP/Markdown/CSV/iCalendar/vCardを検証する。クラスタ、DB、外部カレンダーへ接続しない。
|
||||||
|
YAMLの構文検査だけではRBAC、admission、NFS永続性、TLS、公開経路の成立は保証しない。
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# Apply only after the one-time bootstrap Job has completed successfully.
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata: {name: pageswiki}
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
strategy: {type: Recreate}
|
||||||
|
selector:
|
||||||
|
matchLabels: {app: pageswiki}
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels: {app: pageswiki, pageswiki-db-client: 'true'}
|
||||||
|
spec:
|
||||||
|
automountServiceAccountToken: false
|
||||||
|
terminationGracePeriodSeconds: 90
|
||||||
|
securityContext:
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 10001
|
||||||
|
runAsGroup: 10001
|
||||||
|
seccompProfile: {type: RuntimeDefault}
|
||||||
|
affinity:
|
||||||
|
podAffinity:
|
||||||
|
requiredDuringSchedulingIgnoredDuringExecution:
|
||||||
|
- labelSelector:
|
||||||
|
matchLabels: {app: pageswiki-postgres}
|
||||||
|
topologyKey: kubernetes.io/hostname
|
||||||
|
containers:
|
||||||
|
- name: pageswiki
|
||||||
|
image: git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9
|
||||||
|
env:
|
||||||
|
- {name: PAGESWIKI_DATA_DIR, value: /data}
|
||||||
|
- {name: PAGESWIKI_DB_BACKEND, value: postgresql}
|
||||||
|
- name: PAGESWIKI_AUTH_KEY
|
||||||
|
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: auth-key}}
|
||||||
|
- name: PAGESWIKI_POSTGRES_DSN
|
||||||
|
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: postgres-dsn}}
|
||||||
|
ports: [{name: http, containerPort: 3000}]
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
capabilities: {drop: [ALL]}
|
||||||
|
resources:
|
||||||
|
requests: {cpu: 250m, memory: 512Mi}
|
||||||
|
limits: {cpu: '1', memory: 2Gi}
|
||||||
|
startupProbe:
|
||||||
|
httpGet: {path: /health, port: http}
|
||||||
|
periodSeconds: 5
|
||||||
|
failureThreshold: 120
|
||||||
|
readinessProbe:
|
||||||
|
httpGet: {path: /health, port: http}
|
||||||
|
periodSeconds: 5
|
||||||
|
volumeMounts:
|
||||||
|
- {name: data, mountPath: /data, subPath: pageswiki-exhibit-v018/wiki}
|
||||||
|
- {name: ca, mountPath: /pg-ca, readOnly: true}
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
persistentVolumeClaim: {claimName: pageswiki-data}
|
||||||
|
- name: ca
|
||||||
|
secret:
|
||||||
|
secretName: pageswiki-exhibition-tls
|
||||||
|
items: [{key: ca.crt, path: ca.crt}]
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata: {name: pageswiki}
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
selector: {app: pageswiki}
|
||||||
|
ports: [{name: http, port: 80, targetPort: http}]
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# One-time, fresh exhibition only. SQLite lives on emptyDir, NEVER on NFS.
|
||||||
|
# Refuses any second import. Keep the completed Job until verification ends.
|
||||||
|
apiVersion: batch/v1
|
||||||
|
kind: Job
|
||||||
|
metadata: {name: pageswiki-exhibition-bootstrap}
|
||||||
|
spec:
|
||||||
|
backoffLimit: 0
|
||||||
|
activeDeadlineSeconds: 1800
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels: {pageswiki-db-client: 'true'}
|
||||||
|
spec:
|
||||||
|
restartPolicy: Never
|
||||||
|
automountServiceAccountToken: false
|
||||||
|
securityContext:
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 10001
|
||||||
|
runAsGroup: 10001
|
||||||
|
seccompProfile: {type: RuntimeDefault}
|
||||||
|
affinity:
|
||||||
|
podAffinity:
|
||||||
|
requiredDuringSchedulingIgnoredDuringExecution:
|
||||||
|
- labelSelector:
|
||||||
|
matchLabels: {app: pageswiki-postgres}
|
||||||
|
topologyKey: kubernetes.io/hostname
|
||||||
|
initContainers:
|
||||||
|
- name: initialize-local-source
|
||||||
|
image: python@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e
|
||||||
|
command: [python3, -c, "import os; os.chown('/data', 10001, 10001)"]
|
||||||
|
securityContext:
|
||||||
|
runAsNonRoot: false
|
||||||
|
runAsUser: 0
|
||||||
|
runAsGroup: 0
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true
|
||||||
|
capabilities: {drop: [ALL], add: [CHOWN]}
|
||||||
|
resources:
|
||||||
|
requests: {cpu: 50m, memory: 32Mi}
|
||||||
|
limits: {cpu: 100m, memory: 64Mi}
|
||||||
|
volumeMounts:
|
||||||
|
- {name: source, mountPath: /data}
|
||||||
|
containers:
|
||||||
|
- name: bootstrap
|
||||||
|
image: git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9
|
||||||
|
command: [/bin/sh, -ec]
|
||||||
|
args:
|
||||||
|
- |
|
||||||
|
umask 077
|
||||||
|
test ! -e /persistent/import-complete.json
|
||||||
|
PAGESWIKI_DB_BACKEND=sqlite /pageswiki >/tmp/bootstrap.log 2>&1 &
|
||||||
|
pid=$!
|
||||||
|
trap 'kill -TERM "$pid" 2>/dev/null || true' EXIT
|
||||||
|
healthy=false
|
||||||
|
for attempt in $(seq 1 120); do
|
||||||
|
if wget -q -O /dev/null http://127.0.0.1:3000/health; then healthy=true; break; fi
|
||||||
|
kill -0 "$pid"
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
test "$healthy" = true
|
||||||
|
kill -TERM "$pid"
|
||||||
|
wait "$pid"
|
||||||
|
trap - EXIT
|
||||||
|
/pageswiki migrate-postgres --data-dir /data --apply --timeout 20m >/persistent/import-report.pending.json
|
||||||
|
mv /persistent/import-report.pending.json /persistent/import-complete.json
|
||||||
|
# Preserve the stopped synthetic source for audit, not runtime use.
|
||||||
|
mkdir /persistent/bootstrap-source
|
||||||
|
cp /data/pages.db /persistent/bootstrap-source/pages.db
|
||||||
|
echo 'Synthetic namespace initialized and verified PostgreSQL import committed.'
|
||||||
|
env:
|
||||||
|
- {name: PAGESWIKI_DATA_DIR, value: /data}
|
||||||
|
- name: PAGESWIKI_AUTH_KEY
|
||||||
|
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: auth-key}}
|
||||||
|
- name: PAGESWIKI_POSTGRES_DSN
|
||||||
|
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: postgres-dsn}}
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
capabilities: {drop: [ALL]}
|
||||||
|
resources:
|
||||||
|
requests: {cpu: 250m, memory: 512Mi}
|
||||||
|
limits: {cpu: '1', memory: 2Gi}
|
||||||
|
volumeMounts:
|
||||||
|
- {name: source, mountPath: /data}
|
||||||
|
- {name: data, mountPath: /data/documents, subPath: pageswiki-exhibit-v018/wiki/documents}
|
||||||
|
- {name: data, mountPath: /persistent, subPath: pageswiki-exhibit-v018/wiki}
|
||||||
|
- {name: ca, mountPath: /pg-ca, readOnly: true}
|
||||||
|
volumes:
|
||||||
|
- name: source
|
||||||
|
emptyDir: {}
|
||||||
|
- name: data
|
||||||
|
persistentVolumeClaim: {claimName: pageswiki-data}
|
||||||
|
- name: ca
|
||||||
|
secret:
|
||||||
|
secretName: pageswiki-exhibition-tls
|
||||||
|
items: [{key: ca.crt, path: ca.crt}]
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# 展示用合成データの準備と投入前確認
|
||||||
|
|
||||||
|
灯架図書館、雲庭研究街区、帆灯運用街区という架空の街を巡るデータセットです。日本語のWiki 26ページ、合成CSV 1件、タスク8件、予定6件、架空連絡先6件をローカル生成します。実在の人物や団体、実測値、本番データ、認証情報を含みません。連絡先はすべて `example.invalid` です。
|
||||||
|
|
||||||
|
生成ツール `generate.py` にはHTTPクライアント、DB接続、クラスタ操作、投入機能がありません。別の `seed.py` が、展示namespaceと固定releaseイメージを確認し、localhost限定port-forward越しに通常のimport/API/DAVで投入します。
|
||||||
|
|
||||||
|
2026年11月15日に展示環境へ全件投入済みです。PostgreSQLとPagesWikiのPod再作成後にも、ログイン、Wiki/CSV 27文書、予定6件・タスク8件・連絡先6件のUIDとETagを確認しました。再投入は既存DAV20件を上書きせずにスキップします。本番や外部カレンダーのデータは使いません。
|
||||||
|
|
||||||
|
## 配置済み展示環境の検証
|
||||||
|
|
||||||
|
保存済みの展示用kubeconfigを利用し、別の端末で次を起動します。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
kubectl -n exhibit-anya port-forward --address 127.0.0.1 service/pageswiki 18381:80
|
||||||
|
```
|
||||||
|
|
||||||
|
`seed.py` はこのリポジトリの保存済み展示用kubeconfigと、`pageswiki-exhibition-app` Secretの `owner-password` を利用します。接続先は `127.0.0.1:18381` 固定、既定Hostは `pages.anya.jisaba.sh`、管理者は `exhibition-admin` です。トークンやパスワードは表示しません。
|
||||||
|
|
||||||
|
この投入ツールは2026年11月の展示専用です。kubectlとkubeconfigの参照先は
|
||||||
|
Git管理外の `.deployment-backups/exhibition-session/` に固定されており、別環境向けの汎用CLIではありません。
|
||||||
|
当時の資格情報は同梱しません。`verify` もログインを行うため、オフライン検証には下記の単体テストを使います。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 tools/exhibition-demo/seed.py verify
|
||||||
|
```
|
||||||
|
|
||||||
|
新規環境での投入順は `configure --host localhost`、`wiki`、`organizers`、`city-labels`、`verify` です。既存展示への通常確認には `verify` だけを使います。`organizers` の再実行は `If-None-Match: *` により既存項目をスキップし、更新しません。
|
||||||
|
|
||||||
|
Cityの内部名はASCII制約があるため、日本語を識別子として渡しません。現在の展示は `/exhibition-demo` を起点としたURL自動生成を維持し、`city-labels` で表示タイトルだけを日本語化しています。データセットの3領域はこの起点の下に表示され、3つのトップレベルQuartierへ手動分割する構成ではありません。
|
||||||
|
|
||||||
|
## ローカル生成
|
||||||
|
|
||||||
|
リポジトリのルートでPython 3.10以上を使用します。追加パッケージは不要です。`--base-date` は日本時間の展示開始日を明示指定してください。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 tools/exhibition-demo/generate.py \
|
||||||
|
--base-date 2026-11-15 \
|
||||||
|
--output /tmp/pageswiki-exhibition-demo
|
||||||
|
|
||||||
|
python3 -m unittest discover -s tools/exhibition-demo -p 'test_*.py' -v
|
||||||
|
|
||||||
|
go test ./tools/exhibition-demo
|
||||||
|
```
|
||||||
|
|
||||||
|
投入前には独立したPythonテスト(生成6件・投入補助3件)を必ず実行します。Goテストはアプリの既存パーサーとの追加確認です。Pythonを含まない既存CI環境ではGoの追加確認だけをskipし、CIイメージに新しい依存は要求しません。
|
||||||
|
|
||||||
|
予定は基準日の9時、11時、14時と、その翌日、3日後、6日後に配置します。タスクの期限は前日から6日後までに分散し、完了・進行中・未着手の状態を用意しています。JSONには日本時間のオフセットを残し、ICSの時刻はUTCで出力します。
|
||||||
|
|
||||||
|
同じ基準日とprefixからは同じ内容とZIPが生成されます。基準日を変えてもタスク、予定、連絡先のUIDは変わりません。再生成は既存の `manifest.json` と全ファイルのSHA-256を照合し、手編集したファイル、無関係なファイル、symlinkがある出力先を拒否します。生成物を手編集した場合は別の出力先を指定してください。中断で生成が不完全になった場合も、新しいディレクトリで再生成してください。
|
||||||
|
|
||||||
|
## 出力内容
|
||||||
|
|
||||||
|
| 出力 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `wiki.zip` | 既存Archive Import向け。26個のMarkdownと1個のCSVのみを収録 |
|
||||||
|
| `wiki/` | ZIPと同一内容の閲覧用展開データ |
|
||||||
|
| `fixtures.json` | 日付を解決済みの合成データ。アプリの直接import形式ではない |
|
||||||
|
| `tasks/*.ics` | 1ファイルにつき1個のVTODO。タスクDAVの単一リソース形式を想定 |
|
||||||
|
| `events/*.ics` | 1ファイルにつき1個のVEVENT |
|
||||||
|
| `calendar.ics` | 6予定をまとめた閲覧・import用カレンダー |
|
||||||
|
| `contacts/*.vcf` | 1ファイルにつき1人のvCard 3.0 |
|
||||||
|
| `manifest.json` | 基準日、prefix、件数、生成物のSHA-256 |
|
||||||
|
|
||||||
|
Wikiの階層は「街区 → 通り → 場所 → 個別資料」の最大4階層です。各ページには `children` マクロと内部リンクがあり、風見テラスには表とCSV、再現ノートには集計コードを用意しています。五分の案内コースは `帆灯運用街区/案内通り/案内台本` から始められます。
|
||||||
|
|
||||||
|
## 展示用Wikiへの投入手順
|
||||||
|
|
||||||
|
以下は、展示専用の新規データ領域、利用者、接続先が確定した後に運営者が行う手順です。本番や既存利用者の環境には投入しません。
|
||||||
|
|
||||||
|
1. 展示専用環境のバックアップ方針と権限を確認し、通常の `/v/import` 画面を開きます。
|
||||||
|
2. `wiki.zip` を選び、投入先prefixを **`/exhibition-demo`** に指定します。変更する場合は、生成時にも同じ `--target-prefix` を指定します。内部リンクはこのprefixを含むため、ZIPだけ別prefixに投入しないでください。
|
||||||
|
3. 解析結果の27項目を確認します。Markdownは拡張子が除去されたPathになり、CSVの拡張子は残ります。
|
||||||
|
4. 現在の展示構成ではimportのQuartier、Street、Spotを空欄とし、保存後のURL自動生成に任せます。手動指定する場合はASCIIの内部名を使い、日本語は別途Cityの表示タイトルへ設定します。
|
||||||
|
5. 競合は `skip` を選びます。既存import APIのcommitは `conflict=skip` が既定です。`rename` は複製を作るので再投入には使用しません。
|
||||||
|
6. `/exhibition-demo/展示案内` を開き、children一覧、パンくず、内部リンク、コード、表、CSVを確認します。
|
||||||
|
|
||||||
|
同prefixでの `skip` は既存Pathを上書きしません。日付や内容を変更したZIPの再投入でも既存ページは更新されません。更新や削除が必要な場合は、展示専用データであることを確認して別途計画してください。ローカル再生成の安全性と、サーバ側での再投入の安全性は別の確認事項です。
|
||||||
|
|
||||||
|
## タスクと予定と連絡先の投入前確認
|
||||||
|
|
||||||
|
JSON fixtureはアプリのAPIペイロードを装っていません。通常のタスクDAV、カレンダー、CardDAVのディスカバリと権限確認を経て、展示専用コレクションへ投入する後続作業が必要です。認証設定や外部カレンダー購読はこの準備ツールでは作成しません。
|
||||||
|
|
||||||
|
- タスクDAVには `tasks/` の単一VTODOを使います。全タスクを1個のリソースに連結しないでください。
|
||||||
|
- 予定は対応するimport経路で `calendar.ics` を使うか、通常のDAVリソース操作で `events/` を使います。両方を重複投入しません。
|
||||||
|
- 連絡先は `contacts/` の単一vCardを使います。電話番号、実住所、実在ドメインは含みません。
|
||||||
|
- DAVの新規作成は固定のリソース名・UIDを使い、`If-None-Match: *` で既存リソースの上書きを防ぎます。412応答は内容を確認し、無条件PUTで上書きしないでください。日付を更新する場合は既存ETagの確認と `If-Match` による更新を別途実装・検証します。
|
||||||
|
|
||||||
|
投入後は展示専用アカウントで当日・今週の予定、タスク状態、日本時間の表示を確認してください。実サーバでのimport、条件付き作成、UID/ETagと文書の読み戻しは `seed.py` で検証済みです。公開HTTPS経路を通したブラウザの描画・操作確認は残っています。
|
||||||
|
|
||||||
|
## 仕様の参照先
|
||||||
|
|
||||||
|
- [Archive Importの設計](../../../../docs/design/archive-import.md)
|
||||||
|
- [childrenマクロの設計](../../../../docs/design/projection-adapters.md#children-macro-views)
|
||||||
|
- ソース上の確認箇所は `internal/server/import_handler.go`、`internal/server/task_ical.go`、`internal/server/contact_dav.go` です。
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"dataset_id": "pageswiki-exhibition-fiction-v1",
|
||||||
|
"notice": "すべて架空の展示用データです。実在の人物、団体、設備、観測値とは関係ありません。",
|
||||||
|
"districts": [
|
||||||
|
{
|
||||||
|
"name": "灯架図書館",
|
||||||
|
"intro": "空想の港町にある灯架図書館。物語と設計記録を同じ棚に並べ、読むことから小さな発見を始めます。",
|
||||||
|
"streets": [
|
||||||
|
{"name": "閲覧通り", "intro": "初めての来館者が、書棚と読書の記録を巡る通りです。", "spots": [
|
||||||
|
{"name": "星図の書棚", "intro": "架空の星座を描いた地図帳を集めました。星の位置ではなく、物語のつながりを調べる棚です。", "details": ["銀の帆座は航海日誌の章から探せます。", "青い栞は共同読書で選ばれた資料の目印です。"]},
|
||||||
|
{"name": "読書ラウンジ", "intro": "短い感想を持ち寄る静かな場所。結論を急がず、気になった一文から話を始めます。", "details": ["一回の読書会は二十五分を想定しています。", "紹介カードには作品名と問いを一つ書きます。"]}
|
||||||
|
]},
|
||||||
|
{"name": "記録通り", "intro": "紙の資料を整理し、次の読者に伝えるための作業記録です。", "spots": [
|
||||||
|
{"name": "修復工房", "intro": "破れた架空の航海日誌を題材に、修復前後の記録の残し方を学びます。", "details": ["修復前の状態と作業の判断を分けて記録します。", "展示の作業記録には実物の文化財情報を含めません。"]},
|
||||||
|
{"name": "目録編集室", "intro": "題名、分類、紹介文を揃えて資料を見つけやすくします。", "details": ["分類は星図、航海、暮らしの三種類です。", "略称から正式な架空資料名へのリンクを残します。"]}
|
||||||
|
]}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "雲庭研究街区",
|
||||||
|
"intro": "雲庭研究街区は、合成データで観察と分析を練習する架空の研究拠点です。数値は測定結果ではありません。",
|
||||||
|
"streets": [
|
||||||
|
{"name": "観測通り", "intro": "データの意味、単位、欠測を揃えてから図や表に進みます。", "spots": [
|
||||||
|
{"name": "風見テラス", "intro": "紙で作った風車の回転数を想定した、完全合成の観測セットです。", "details": ["回転数は説明用の規則から生成します。", "気象予測や設備判断には利用できません。"]},
|
||||||
|
{"name": "露の温室", "intro": "架空の苗床ごとの観察メモを並べ、記録の粒度を比較します。", "details": ["苗床名は琥珀、翡翠、真珠の三つです。", "成長の違いは物語上の設定で、栽培助言ではありません。"]}
|
||||||
|
]},
|
||||||
|
{"name": "解析通り", "intro": "小さな表から仮説と確認事項を分けて考える通りです。", "spots": [
|
||||||
|
{"name": "比較実験室", "intro": "同じ条件のつもりでも何が異なるか、試行表から探します。", "details": ["条件名、入力、結果を一行にまとめます。", "一つの結果だけで原因を決めない練習に使います。"]},
|
||||||
|
{"name": "再現ノート", "intro": "入力と手順を残し、別の人が同じ合成結果を得られるか確かめます。", "details": ["基準日を固定すると展示データを再現できます。", "実データや認証情報のコピーは使いません。"]}
|
||||||
|
]}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "帆灯運用街区",
|
||||||
|
"intro": "帆灯運用街区は、展示を案内する架空の運営チームです。受付、点検、振り返りを一つの流れで紹介します。",
|
||||||
|
"streets": [
|
||||||
|
{"name": "案内通り", "intro": "初めての見学者にも、現在地と次の見どころを伝えます。", "spots": [
|
||||||
|
{"name": "受付デスク", "intro": "三つの街区を巡る見学コースの起点です。参加者の実名や連絡先は収集しません。", "details": ["図書館、研究街区、運用街区の順に巡ります。", "質問は架空の案内係に向けたサンプルとして扱います。"]},
|
||||||
|
{"name": "案内台本", "intro": "階層、内部リンク、タスクと予定の関係を短い説明でつなぎます。", "details": ["まず子ページ一覧から目的の場所へ移動します。", "最後に日付の変わる展示用予定を紹介します。"]}
|
||||||
|
]},
|
||||||
|
{"name": "整備通り", "intro": "点検結果と引き継ぎ事項を分けて記録する運用の練習場です。", "spots": [
|
||||||
|
{"name": "点検室", "intro": "架空の案内灯と展示端末を題材に、確認項目を見える形にします。", "details": ["点検項目は表示、操作、案内文の三つです。", "このページの手順は実設備を操作しません。"]},
|
||||||
|
{"name": "引継ぎ広場", "intro": "終わったこと、残ったこと、次に確かめることを短く残します。", "details": ["未完了の項目には確認する日を添えます。", "担当名は展示専用の架空役名を使います。"]}
|
||||||
|
]}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"deep_pages": [
|
||||||
|
{"parent": "灯架図書館/閲覧通り/星図の書棚", "name": "銀の帆座", "intro": "銀の帆座は、迷った船が灯りを持ち寄るという架空の物語です。", "details": ["分類は星図、資料番号は SYN-LIB-001 です。", "関連する読書会は合成カレンダーに収録しています。"]},
|
||||||
|
{"parent": "灯架図書館/記録通り/修復工房", "name": "青い航海日誌", "intro": "青い航海日誌の綴じ直しを想定した、展示専用の修復記録です。", "details": ["作業前の課題は架空の綴じ糸のゆるみです。", "完了条件は記録表の項目が揃っていることです。"]},
|
||||||
|
{"parent": "雲庭研究街区/解析通り/再現ノート", "name": "合成データの読み方", "intro": "CSVの各列が何を表すかを確認します。行の日付は展示の基準日から相対生成されます。", "details": ["sample_id は固定の標本識別子です。", "rotations は説明用の整数、synthetic は常に true です。"]},
|
||||||
|
{"parent": "帆灯運用街区/整備通り/点検室", "name": "開場前チェック", "intro": "実環境を変更せず、展示画面の見どころを確認するチェックリストです。", "details": ["階層を移動して戻れることを確認します。", "図書館から研究街区へのリンクを確認します。"]}
|
||||||
|
],
|
||||||
|
"tasks": [
|
||||||
|
{"id": "task-01", "title": "星図の紹介カードを揃える", "due_offset": -1, "status": "COMPLETED", "page": "灯架図書館/閲覧通り/星図の書棚"},
|
||||||
|
{"id": "task-02", "title": "読書会の問いを一つ選ぶ", "due_offset": 0, "status": "IN-PROCESS", "page": "灯架図書館/閲覧通り/読書ラウンジ"},
|
||||||
|
{"id": "task-03", "title": "合成観測表の単位を確認する", "due_offset": 0, "status": "NEEDS-ACTION", "page": "雲庭研究街区/観測通り/風見テラス"},
|
||||||
|
{"id": "task-04", "title": "再現ノートに基準日を記録する", "due_offset": 1, "status": "NEEDS-ACTION", "page": "雲庭研究街区/解析通り/再現ノート"},
|
||||||
|
{"id": "task-05", "title": "開場前の表示を点検する", "due_offset": 0, "status": "NEEDS-ACTION", "page": "帆灯運用街区/整備通り/点検室"},
|
||||||
|
{"id": "task-06", "title": "案内台本を読み合わせる", "due_offset": 2, "status": "NEEDS-ACTION", "page": "帆灯運用街区/案内通り/案内台本"},
|
||||||
|
{"id": "task-07", "title": "修復記録の分類を揃える", "due_offset": 3, "status": "NEEDS-ACTION", "page": "灯架図書館/記録通り/修復工房"},
|
||||||
|
{"id": "task-08", "title": "見学コースを振り返る", "due_offset": 6, "status": "NEEDS-ACTION", "page": "帆灯運用街区/整備通り/引継ぎ広場"}
|
||||||
|
],
|
||||||
|
"events": [
|
||||||
|
{"id": "event-01", "title": "開場前の読み合わせ", "offset": 0, "hour": 9, "duration_minutes": 30, "location": "帆灯運用街区 受付デスク"},
|
||||||
|
{"id": "event-02", "title": "銀の帆座の読書会", "offset": 0, "hour": 11, "duration_minutes": 45, "location": "灯架図書館 読書ラウンジ"},
|
||||||
|
{"id": "event-03", "title": "合成観測表の見学", "offset": 0, "hour": 14, "duration_minutes": 30, "location": "雲庭研究街区 風見テラス"},
|
||||||
|
{"id": "event-04", "title": "再現ノートの交換会", "offset": 1, "hour": 13, "duration_minutes": 45, "location": "雲庭研究街区 比較実験室"},
|
||||||
|
{"id": "event-05", "title": "青い航海日誌の紹介", "offset": 3, "hour": 10, "duration_minutes": 30, "location": "灯架図書館 修復工房"},
|
||||||
|
{"id": "event-06", "title": "街区横断の振り返り", "offset": 6, "hour": 16, "duration_minutes": 30, "location": "帆灯運用街区 引継ぎ広場"}
|
||||||
|
],
|
||||||
|
"contacts": [
|
||||||
|
{"id": "contact-01", "name": "栞係 ルリ", "organization": "架空の灯架図書館", "email": "ruri@example.invalid"},
|
||||||
|
{"id": "contact-02", "name": "修復係 コハク", "organization": "架空の灯架図書館", "email": "kohaku@example.invalid"},
|
||||||
|
{"id": "contact-03", "name": "観測係 ソラ", "organization": "架空の雲庭研究街区", "email": "sora@example.invalid"},
|
||||||
|
{"id": "contact-04", "name": "記録係 ナギ", "organization": "架空の雲庭研究街区", "email": "nagi@example.invalid"},
|
||||||
|
{"id": "contact-05", "name": "案内係 トワ", "organization": "架空の帆灯運用街区", "email": "towa@example.invalid"},
|
||||||
|
{"id": "contact-06", "name": "点検係 ハル", "organization": "架空の帆灯運用街区", "email": "haru@example.invalid"}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
# 旧SQLite用の一般ひな形。現在の展示NFSへは適用しない。
|
||||||
|
# 展示ではpostgres.yaml、初回のみbootstrap.yaml、app.yamlを使う。
|
||||||
|
# 適用前に運営の方針と照合する。
|
||||||
|
# kubectl -n "$NS" apply -f pageswiki.yaml
|
||||||
|
apiVersion: v1
|
||||||
|
kind: PersistentVolumeClaim
|
||||||
|
metadata:
|
||||||
|
name: pageswiki-data
|
||||||
|
spec:
|
||||||
|
storageClassName: REPLACE_WITH_STORAGE_CLASS
|
||||||
|
accessModes:
|
||||||
|
- ReadWriteOnce
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
storage: 20Gi
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: pageswiki
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
strategy:
|
||||||
|
type: Recreate
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: pageswiki
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: pageswiki
|
||||||
|
spec:
|
||||||
|
automountServiceAccountToken: false
|
||||||
|
terminationGracePeriodSeconds: 60
|
||||||
|
securityContext:
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 10001
|
||||||
|
runAsGroup: 10001
|
||||||
|
fsGroup: 10001
|
||||||
|
seccompProfile:
|
||||||
|
type: RuntimeDefault
|
||||||
|
containers:
|
||||||
|
- name: pageswiki
|
||||||
|
# 本書の作成時点のrelease例。新しい展示機能を含める場合は別途releaseし検証する。
|
||||||
|
image: git.anya.jp/anya/pageswiki-app:v0.17.3
|
||||||
|
imagePullPolicy: IfNotPresent
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
containerPort: 3000
|
||||||
|
env:
|
||||||
|
- name: PAGESWIKI_DATA_DIR
|
||||||
|
value: /data
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 250m
|
||||||
|
memory: 512Mi
|
||||||
|
limits:
|
||||||
|
cpu: "2"
|
||||||
|
memory: 2Gi
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
capabilities:
|
||||||
|
drop:
|
||||||
|
- ALL
|
||||||
|
volumeMounts:
|
||||||
|
- name: data
|
||||||
|
mountPath: /data
|
||||||
|
- name: tmp
|
||||||
|
mountPath: /tmp
|
||||||
|
startupProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: http
|
||||||
|
periodSeconds: 5
|
||||||
|
failureThreshold: 120
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: http
|
||||||
|
periodSeconds: 5
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
persistentVolumeClaim:
|
||||||
|
claimName: pageswiki-data
|
||||||
|
- name: tmp
|
||||||
|
emptyDir: {}
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: pageswiki
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
selector:
|
||||||
|
app: pageswiki
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
port: 80
|
||||||
|
targetPort: http
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: ConfigMap
|
||||||
|
metadata:
|
||||||
|
name: pageswiki-exhibition-init
|
||||||
|
data:
|
||||||
|
storage.py: |
|
||||||
|
import os, pathlib, shutil, stat
|
||||||
|
root = pathlib.Path('/volume/pageswiki-exhibit-v018')
|
||||||
|
def owned_directory(path, uid, gid, mode):
|
||||||
|
try:
|
||||||
|
path.mkdir(mode=mode)
|
||||||
|
except FileExistsError:
|
||||||
|
s = path.lstat()
|
||||||
|
if not stat.S_ISDIR(s.st_mode) or (s.st_uid, s.st_gid) != (uid, gid):
|
||||||
|
raise RuntimeError('unexpected existing directory ownership: ' + str(path))
|
||||||
|
else:
|
||||||
|
os.chown(path, uid, gid)
|
||||||
|
owned_directory(root, 0, 0, 0o755)
|
||||||
|
owned_directory(root / 'wiki', 10001, 10001, 0o700)
|
||||||
|
owned_directory(root / 'wiki' / 'documents', 10001, 10001, 0o700)
|
||||||
|
owned_directory(root / 'postgres', 70, 70, 0o700)
|
||||||
|
os.chown('/pgsocket', 70, 70)
|
||||||
|
for name in ('server.crt', 'server.key'):
|
||||||
|
shutil.copyfile('/cert-source/' + name, '/tls/' + name)
|
||||||
|
os.chmod('/tls/' + name, 0o600)
|
||||||
|
os.chown('/tls/' + name, 70, 70)
|
||||||
|
print('Dedicated directories and PostgreSQL TLS files ready; existing ownership unchanged.')
|
||||||
|
10-app.sh: |
|
||||||
|
set -eu
|
||||||
|
psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres <<SQL
|
||||||
|
CREATE ROLE pageswiki LOGIN PASSWORD '${APP_DB_PASSWORD}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
|
||||||
|
CREATE DATABASE pageswiki OWNER pageswiki;
|
||||||
|
SQL
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: pageswiki-postgres
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
strategy: {type: Recreate}
|
||||||
|
selector:
|
||||||
|
matchLabels: {app: pageswiki-postgres}
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels: {app: pageswiki-postgres}
|
||||||
|
spec:
|
||||||
|
automountServiceAccountToken: false
|
||||||
|
terminationGracePeriodSeconds: 90
|
||||||
|
securityContext:
|
||||||
|
seccompProfile: {type: RuntimeDefault}
|
||||||
|
initContainers:
|
||||||
|
- name: initialize-storage
|
||||||
|
image: python@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e
|
||||||
|
command: [python3, /scripts/storage.py]
|
||||||
|
securityContext:
|
||||||
|
runAsUser: 0
|
||||||
|
runAsGroup: 0
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true
|
||||||
|
capabilities: {drop: [ALL], add: [CHOWN, DAC_OVERRIDE]}
|
||||||
|
resources:
|
||||||
|
requests: {cpu: 50m, memory: 32Mi}
|
||||||
|
limits: {cpu: 250m, memory: 128Mi}
|
||||||
|
volumeMounts:
|
||||||
|
- {name: data, mountPath: /volume}
|
||||||
|
- {name: scripts, mountPath: /scripts, readOnly: true}
|
||||||
|
- {name: certificates, mountPath: /cert-source, readOnly: true}
|
||||||
|
- {name: tls, mountPath: /tls}
|
||||||
|
- {name: socket, mountPath: /pgsocket}
|
||||||
|
containers:
|
||||||
|
- name: postgres
|
||||||
|
image: postgres@sha256:005c5c37db96c1e6652a79ea31f9886402fba81ac95dc2db897739121dd7f8f2
|
||||||
|
args:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- ssl=on
|
||||||
|
- -c
|
||||||
|
- ssl_cert_file=/tls/server.crt
|
||||||
|
- -c
|
||||||
|
- ssl_key_file=/tls/server.key
|
||||||
|
- -c
|
||||||
|
- shared_buffers=128MB
|
||||||
|
- -c
|
||||||
|
- max_connections=40
|
||||||
|
env:
|
||||||
|
- {name: PGDATA, value: /var/lib/postgresql/data/pgdata}
|
||||||
|
- name: POSTGRES_PASSWORD
|
||||||
|
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-db, key: admin-password}}
|
||||||
|
- name: APP_DB_PASSWORD
|
||||||
|
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-db, key: app-password}}
|
||||||
|
- {name: POSTGRES_INITDB_ARGS, value: '--auth-host=scram-sha-256'}
|
||||||
|
ports: [{name: postgres, containerPort: 5432}]
|
||||||
|
securityContext:
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 70
|
||||||
|
runAsGroup: 70
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
capabilities: {drop: [ALL]}
|
||||||
|
resources:
|
||||||
|
requests: {cpu: 250m, memory: 256Mi}
|
||||||
|
limits: {cpu: '1', memory: 1Gi}
|
||||||
|
startupProbe:
|
||||||
|
exec: {command: [pg_isready, -U, postgres, -d, postgres]}
|
||||||
|
periodSeconds: 5
|
||||||
|
failureThreshold: 60
|
||||||
|
readinessProbe:
|
||||||
|
exec: {command: [pg_isready, -U, postgres, -d, postgres]}
|
||||||
|
periodSeconds: 5
|
||||||
|
volumeMounts:
|
||||||
|
- {name: data, mountPath: /var/lib/postgresql/data, subPath: pageswiki-exhibit-v018/postgres}
|
||||||
|
- {name: scripts, mountPath: /docker-entrypoint-initdb.d/10-app.sh, subPath: 10-app.sh, readOnly: true}
|
||||||
|
- {name: tls, mountPath: /tls, readOnly: true}
|
||||||
|
- {name: socket, mountPath: /var/run/postgresql}
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
persistentVolumeClaim: {claimName: pageswiki-data}
|
||||||
|
- name: scripts
|
||||||
|
configMap: {name: pageswiki-exhibition-init}
|
||||||
|
- name: certificates
|
||||||
|
secret: {secretName: pageswiki-exhibition-tls, defaultMode: 0400}
|
||||||
|
- name: tls
|
||||||
|
emptyDir: {}
|
||||||
|
- name: socket
|
||||||
|
emptyDir: {}
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata: {name: pageswiki-postgres}
|
||||||
|
spec:
|
||||||
|
selector: {app: pageswiki-postgres}
|
||||||
|
ports: [{name: postgres, port: 5432, targetPort: postgres}]
|
||||||
|
---
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: NetworkPolicy
|
||||||
|
metadata: {name: pageswiki-postgres}
|
||||||
|
spec:
|
||||||
|
podSelector:
|
||||||
|
matchLabels: {app: pageswiki-postgres}
|
||||||
|
policyTypes: [Ingress]
|
||||||
|
ingress:
|
||||||
|
- from:
|
||||||
|
- podSelector:
|
||||||
|
matchLabels: {pageswiki-db-client: 'true'}
|
||||||
|
ports: [{protocol: TCP, port: 5432}]
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Isolated root initialization followed by a non-root storage test.
|
||||||
|
# Does not inspect or change existing data or the PVC root permissions.
|
||||||
|
apiVersion: batch/v1
|
||||||
|
kind: Job
|
||||||
|
metadata:
|
||||||
|
name: pageswiki-root-storage-check
|
||||||
|
spec:
|
||||||
|
backoffLimit: 0
|
||||||
|
activeDeadlineSeconds: 120
|
||||||
|
ttlSecondsAfterFinished: 3600
|
||||||
|
template:
|
||||||
|
spec:
|
||||||
|
restartPolicy: Never
|
||||||
|
automountServiceAccountToken: false
|
||||||
|
securityContext:
|
||||||
|
runAsUser: 0
|
||||||
|
runAsGroup: 0
|
||||||
|
seccompProfile:
|
||||||
|
type: RuntimeDefault
|
||||||
|
containers:
|
||||||
|
- name: check
|
||||||
|
image: python:3.13-alpine
|
||||||
|
command: [python3, -u, -c]
|
||||||
|
args:
|
||||||
|
- |
|
||||||
|
import hashlib, json, os, pathlib, tempfile
|
||||||
|
mount = None
|
||||||
|
for line in pathlib.Path('/proc/self/mountinfo').read_text().splitlines():
|
||||||
|
before, after = line.split(' - ', 1)
|
||||||
|
fields, detail = before.split(), after.split()
|
||||||
|
if fields[4] == '/check':
|
||||||
|
mount = (detail[0], set(fields[5].split(',')) | set(detail[2].split(',')))
|
||||||
|
if mount is None:
|
||||||
|
raise RuntimeError('PVC mount not found')
|
||||||
|
fs, options = mount
|
||||||
|
if fs in ('nfs', 'nfs4') and ('hard' not in options or options & {'soft', 'softerr', 'softreval'}):
|
||||||
|
raise RuntimeError('NFS hard mount required')
|
||||||
|
root = pathlib.Path(tempfile.mkdtemp(prefix='.pageswiki-root-check-', dir='/check'))
|
||||||
|
print(json.dumps({'stage': 'created', 'directory': root.name, 'filesystem': fs, 'hard_mount': 'hard' in options}))
|
||||||
|
try:
|
||||||
|
os.chown(root, 10001, 10001)
|
||||||
|
pid = os.fork()
|
||||||
|
if pid == 0:
|
||||||
|
try:
|
||||||
|
os.setgroups([])
|
||||||
|
os.setgid(10001)
|
||||||
|
os.setuid(10001)
|
||||||
|
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
|
||||||
|
payload = b'PagesWiki isolated non-root storage verification\n'
|
||||||
|
try:
|
||||||
|
with (root / 'source').open('xb') as f:
|
||||||
|
f.write(payload)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.link(root / 'source', root / 'published')
|
||||||
|
try:
|
||||||
|
os.link(root / 'source', root / 'published')
|
||||||
|
except FileExistsError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise RuntimeError('no-replace publication failed')
|
||||||
|
os.rename(root / 'source', root / 'renamed')
|
||||||
|
os.fsync(directory)
|
||||||
|
for name in ('published', 'renamed'):
|
||||||
|
if hashlib.sha256((root / name).read_bytes()).digest() != hashlib.sha256(payload).digest():
|
||||||
|
raise RuntimeError('readback mismatch')
|
||||||
|
print(json.dumps({'result': 'passed', 'process_uid': os.getuid(), 'process_gid': os.getgid(), 'server_durability': 'not verified'}))
|
||||||
|
finally:
|
||||||
|
for name in ('source', 'published', 'renamed'):
|
||||||
|
(root / name).unlink(missing_ok=True)
|
||||||
|
os.fsync(directory)
|
||||||
|
os.close(directory)
|
||||||
|
except BaseException:
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
os._exit(1)
|
||||||
|
os._exit(0)
|
||||||
|
_, status = os.waitpid(pid, 0)
|
||||||
|
if os.waitstatus_to_exitcode(status) != 0:
|
||||||
|
raise RuntimeError('non-root storage verification failed')
|
||||||
|
finally:
|
||||||
|
# Only remove the empty directory created by this process.
|
||||||
|
root.rmdir()
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true
|
||||||
|
capabilities:
|
||||||
|
drop: [ALL]
|
||||||
|
add: [CHOWN, SETUID, SETGID]
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 64Mi
|
||||||
|
limits:
|
||||||
|
cpu: 250m
|
||||||
|
memory: 128Mi
|
||||||
|
volumeMounts:
|
||||||
|
- name: data
|
||||||
|
mountPath: /check
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
persistentVolumeClaim:
|
||||||
|
claimName: pageswiki-data
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# Run only in the assigned exhibit-anya namespace after release verification.
|
||||||
|
# kubectl -n exhibit-anya apply --dry-run=server -f storage-check.yaml.example
|
||||||
|
# No database or existing application data is opened by this job.
|
||||||
|
apiVersion: batch/v1
|
||||||
|
kind: Job
|
||||||
|
metadata:
|
||||||
|
name: pageswiki-storage-check
|
||||||
|
spec:
|
||||||
|
backoffLimit: 0
|
||||||
|
activeDeadlineSeconds: 120
|
||||||
|
ttlSecondsAfterFinished: 3600
|
||||||
|
template:
|
||||||
|
spec:
|
||||||
|
restartPolicy: Never
|
||||||
|
automountServiceAccountToken: false
|
||||||
|
securityContext:
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 10001
|
||||||
|
runAsGroup: 10001
|
||||||
|
seccompProfile:
|
||||||
|
type: RuntimeDefault
|
||||||
|
containers:
|
||||||
|
- name: check
|
||||||
|
image: python:3.13-alpine
|
||||||
|
imagePullPolicy: IfNotPresent
|
||||||
|
command: [python3, -c]
|
||||||
|
args:
|
||||||
|
- |
|
||||||
|
import hashlib, json, os, pathlib, tempfile
|
||||||
|
mount = None
|
||||||
|
for line in pathlib.Path('/proc/self/mountinfo').read_text().splitlines():
|
||||||
|
before, after = line.split(' - ', 1)
|
||||||
|
fields, detail = before.split(), after.split()
|
||||||
|
if fields[4] == '/check':
|
||||||
|
mount = (detail[0], set(fields[5].split(',')) | set(detail[2].split(',')))
|
||||||
|
if mount is None:
|
||||||
|
raise RuntimeError('PVC mount was not found')
|
||||||
|
fs, options = mount
|
||||||
|
if fs in ('nfs', 'nfs4') and ('hard' not in options or options & {'soft', 'softerr', 'softreval'}):
|
||||||
|
raise RuntimeError('NFS hard mount required; unsafe or unknown options')
|
||||||
|
root = pathlib.Path(tempfile.mkdtemp(prefix='.pageswiki-storage-check-', dir='/check'))
|
||||||
|
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
|
||||||
|
payload = b'PagesWiki isolated storage verification\n'
|
||||||
|
try:
|
||||||
|
with (root / 'source').open('xb') as f:
|
||||||
|
f.write(payload)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
os.link(root / 'source', root / 'published')
|
||||||
|
try:
|
||||||
|
os.link(root / 'source', root / 'published')
|
||||||
|
except FileExistsError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise RuntimeError('link publication replaced an existing entry')
|
||||||
|
os.fsync(directory)
|
||||||
|
os.rename(root / 'source', root / 'renamed')
|
||||||
|
os.fsync(directory)
|
||||||
|
expected = hashlib.sha256(payload).digest()
|
||||||
|
for name in ('published', 'renamed'):
|
||||||
|
if hashlib.sha256((root / name).read_bytes()).digest() != expected:
|
||||||
|
raise RuntimeError('content mismatch')
|
||||||
|
print(json.dumps({'result': 'passed', 'filesystem': fs,
|
||||||
|
'hard_mount': 'hard' in options,
|
||||||
|
'server_durability': 'not verified by this client-side test'}))
|
||||||
|
finally:
|
||||||
|
for name in ('source', 'published', 'renamed'):
|
||||||
|
(root / name).unlink(missing_ok=True)
|
||||||
|
os.fsync(directory)
|
||||||
|
os.close(directory)
|
||||||
|
root.rmdir()
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 64Mi
|
||||||
|
limits:
|
||||||
|
cpu: 250m
|
||||||
|
memory: 128Mi
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true
|
||||||
|
capabilities:
|
||||||
|
drop: [ALL]
|
||||||
|
volumeMounts:
|
||||||
|
- name: data
|
||||||
|
mountPath: /check
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
persistentVolumeClaim:
|
||||||
|
claimName: pageswiki-data
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Optional pilot only; does not enable indexing or modify the Pages database.
|
||||||
|
# docker compose -f docker-compose.yml -f docker-compose.ml.yml up -d --build machine-learning
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
networks:
|
||||||
|
ml-front: {}
|
||||||
|
machine-learning:
|
||||||
|
build: ./services/machine-learning
|
||||||
|
image: pageswiki-machine-learning:dev
|
||||||
|
environment:
|
||||||
|
PAGES_ML_TOKEN_FILE: /run/secrets/ml-token
|
||||||
|
PAGES_ML_MODEL_DIR: /models
|
||||||
|
PAGES_ML_ALLOW_OPENAI: "false"
|
||||||
|
volumes:
|
||||||
|
- ${PAGES_ML_TOKEN_PATH:?Set absolute shared token file path}:/run/secrets/ml-token:ro
|
||||||
|
- ${PAGES_ML_MODELS_PATH:?Set absolute trusted model directory path}:/models:ro
|
||||||
|
expose: ["8010"]
|
||||||
|
networks:
|
||||||
|
ml-front: {}
|
||||||
|
read_only: true
|
||||||
|
tmpfs: [/tmp:size=32m,mode=1777]
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: [no-new-privileges:true]
|
||||||
|
mem_limit: 1g
|
||||||
|
cpus: 1.0
|
||||||
|
pids_limit: 64
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8010/healthz', timeout=2).read()"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 3
|
||||||
|
networks:
|
||||||
|
ml-front:
|
||||||
|
internal: true
|
||||||
|
ipam:
|
||||||
|
config:
|
||||||
|
- subnet: ${PAGES_ML_FRONT_SUBNET:-172.24.1.0/27}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
# AI連携とKnowledge Cityの自動整理
|
||||||
|
|
||||||
|
2026-11-17。展示後の要望を受けた実施計画。優先順は
|
||||||
|
**AI向けCLIスキル → CLIに依存しないMCPサーバー → 意味ベースのCity整理**。
|
||||||
|
この文書は設計であり、MCPやベクトル索引が既に稼働していることを意味しない。
|
||||||
|
既存のURL由来の分類・手動編集を置き換えるのではなく、それを補助する。
|
||||||
|
|
||||||
|
同日追記:**Pages Machine Learning** を独立サービスとする方針を採用。
|
||||||
|
`services/machine-learning/` と `internal/machinelearning/` に内部API/クライアントの
|
||||||
|
初期実装を追加した。Doc2Vecの合成データによる学習→HTTP推論→Goクライアントを検証。
|
||||||
|
OpenAIは通信を模擬した契約試験のみ。2026-11-28にDomain別の設定API/UIと予算保存層を追加。
|
||||||
|
文書抽出・推論worker・キュー・ベクトル索引は未接続で、設定保存だけでは推論を開始しない。
|
||||||
|
[サービス境界・運用・残件](../../operations/pages-machine-learning.md)を参照。
|
||||||
|
|
||||||
|
## 1. AI向けスキル(AI-01)
|
||||||
|
|
||||||
|
配布用ソースを `skills/pages-cli/` に置いた。文書の検索・読み取り・編集、タスク、
|
||||||
|
作業記録、メール取り込みを対象にする。初版は独立CLI v0.5.0のhelpと契約を参照。
|
||||||
|
グローバルなエージェント設定や認証状態を変更しない。
|
||||||
|
|
||||||
|
設置時はそのフォルダを利用するエージェントのskillsディレクトリへコピーする。
|
||||||
|
Codexなら通常 `~/.codex/skills/pages-cli/`。CLI自体と接続プロファイルは別に必要。
|
||||||
|
将来はpages-cliリポジトリ/リリースに同梱する。今回は独立リポジトリを変更していない。
|
||||||
|
|
||||||
|
受入:未認証、検索0件、言語分岐、競合、通信断、削除済みcaptureを模擬し、無許可の
|
||||||
|
上書き・公開・資格情報表示をしない。文書/メール中の指示でscopeを変更しない。
|
||||||
|
スキルの文法検証だけを行動試験の完了とは扱わない。
|
||||||
|
|
||||||
|
## 2. MCPサーバー(AI-02、未実装)
|
||||||
|
|
||||||
|
候補URIは `/_/api/v1/mcp`。PagesのGoサーバー内に薄いMCP transport層を置き、既存の
|
||||||
|
業務サービスを呼ぶ。pages-cliの子プロセス起動、HTTPハンドラの文字列出力解析、
|
||||||
|
独自SQLでの認可回避はしない。CLIは人間の端末操作用として継続する。
|
||||||
|
|
||||||
|
### 段階とtool契約
|
||||||
|
|
||||||
|
| 段階 | 候補tool | 必須の結果・制限 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| M1 読取 | search_pages, list_children, read_page, list_tasks | Page UUID、Revision、言語、出典URL、cursor、truncated。件数・本文量を制限 |
|
||||||
|
| M2 更新 | update_page, create_task, update_task | 基点Revision/version、request ID、変更後ID。競合は明示エラー |
|
||||||
|
| M3 整理 | suggest_city_placement, preview_city_changes, apply_city_changes | まず提案・差分のみ。applyは承認済み計画IDと現行版一致が必要 |
|
||||||
|
|
||||||
|
tool名は案。M1公開時点では書込toolを広告しない。descriptionやreadOnlyHint等の注釈は
|
||||||
|
認可の代わりではない。任意URL取得・shell・SQL実行toolは提供しない。
|
||||||
|
|
||||||
|
### transport・認証のゲート
|
||||||
|
|
||||||
|
- HTTP transportと認証は公式SDK/仕様の特定版に固定し、採用版を実装時に記録する。
|
||||||
|
まず2025-11-25世代との相互運用を調べ、最新版と混在させない。SDKが実装する
|
||||||
|
lifecycle、GET/POST、SSE、protocol negotiationを検証し、自前の部分JSON-RPCを公開しない。
|
||||||
|
- Remote MCPのOAuth discovery、resource/audience、PKCE、client registrationの対応を先に
|
||||||
|
決める。既存のOIDC「ログインできる」ことは、PagesがMCP用OAuth認可サーバーであることを
|
||||||
|
意味しない。通常のWeb CookieやCLI handoff tokenの転用を標準対応とは呼ばない。
|
||||||
|
- 各要求でDomain・Principal・scope・現在の権限を確定する。引数のdomain_uuidで権限を切替えない。
|
||||||
|
読取専用を既定、書込は別scope。セッションがあっても権限失効を反映する。
|
||||||
|
- Origin検査、TLS、要求サイズ、時間制限、キャンセル、同時数、監査の本文/秘密情報非記録を実装。
|
||||||
|
MCP上の文書本文は信頼しないデータとして渡し、tool出力に次の実行命令を埋め込まない。
|
||||||
|
- 受入は対応クライアントの実接続、別Domain・失効・scope不足・巨大入力・再送・キャンセル・
|
||||||
|
更新競合。SQLiteとPostgreSQLの双方で同じ認可結果を要求する。
|
||||||
|
|
||||||
|
## 3. ベクトル化の共通設計(CITY-SEM-01、サービス基盤のみ実装)
|
||||||
|
|
||||||
|
Pages本体が文書選定・認可・抽出・キュー・結果保存・適用を管理する。
|
||||||
|
Pages Machine Learningは渡された入力のベクトル化とモデル計算だけを担当し、
|
||||||
|
PagesのDB/文書ディレクトリをmountしない。MCPやCLIからMLへ直接アクセスしない。
|
||||||
|
永続ジョブは既存イベントスケジューラに一本化する。ML障害は通常閲覧・編集を妨げない。
|
||||||
|
|
||||||
|
プロバイダーはまず **OpenAI Embeddings API** と **ローカルDoc2Vec** の2種類。
|
||||||
|
外部送信は既定OFF。Domain単位に対象prefix、除外、送信可否、件数/トークン予算を
|
||||||
|
管理者が選ぶ。本人の読取権限だけで全Domainの外部送信を許可しない。
|
||||||
|
|
||||||
|
HTMLから本文・見出し・コードを抽出する。script/style、展開済みchildren、外部埋め込みは
|
||||||
|
入力に含めず、リンク先を取りに行かない。長文は節/段落で分割し、モデル別上限で制限。
|
||||||
|
タイトル・Pathは補助特徴とし、URLだけで同じ分類を再生して高精度に見せない。
|
||||||
|
バイナリOCR、添付解析、外部カレンダーは初期対象外。実データの送信・学習は今回行わない。
|
||||||
|
|
||||||
|
### プロバイダーごとの違い
|
||||||
|
|
||||||
|
| 項目 | OpenAI Embeddings | Doc2Vec |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 初期候補 | text-embedding-3-small、dimensionsは設定 | Gensim PV-DBOWまたはPV-DM、比較して固定 |
|
||||||
|
| 実行場所 | APIへ対象テキストを送信 | ローカルの低優先度worker |
|
||||||
|
| 準備 | API鍵・送信同意・料金予算 | 学習コーパス・日本語tokenizer・学習設定 |
|
||||||
|
| 注意 | 入力長、429、timeout、再送による追加課金 | 少量文書・未知語・短文の精度、学習CPU/RAM |
|
||||||
|
|
||||||
|
Doc2Vecを常に軽い/高精度とは仮定しない。同じtokenizerを学習・推論に使用し、
|
||||||
|
seed、workers、epochs、語彙、学習対象のdigest、モデル世代を固定する。
|
||||||
|
新モデル生成時は旧ベクトルとの混在比較を禁止。modelファイルは信頼済みの自前生成物のみを
|
||||||
|
ロードし、任意アップロードのpickleを読み込まない。Domain/権限境界を越えた学習はしない。
|
||||||
|
削除・権限変更後は結果を即座に読取不可にし、学習済みモデル内の残存情報は再学習で除去する。
|
||||||
|
|
||||||
|
### 保存・キュー・規模
|
||||||
|
|
||||||
|
ベクトルと分類候補は再構築できるデータ。キーはDomain、Page UUID、Revision UUID、言語、
|
||||||
|
chunk、入力hash、provider、model revision、次元、抽出/tokenizer版、設定hash。
|
||||||
|
別provider・別modelの空間を混ぜない。非数・次元不一致・空出力は失敗として扱う。
|
||||||
|
原文や鍵はログに出さず、ベクトルも本文相当の機密性で扱う。
|
||||||
|
|
||||||
|
作成・編集の確定イベントで重複排除付きの低優先度ジョブを投入。削除は索引を無効化し、
|
||||||
|
renameはPath特徴だけの再評価を可能にする。既存schedulerを使い、foregroundへ推論を置かない。
|
||||||
|
夜間backfill、手動実行、停止、進捗・失敗・予算表示を設定画面へ追加する。
|
||||||
|
古いジョブの完了時にRevision・権限・provider設定の世代を再検査する。
|
||||||
|
|
||||||
|
初期は小規模Domainに限定したバッチ比較(件数・メモリ上限付き)。全ペアO(N²)を
|
||||||
|
ページ表示時に実行しない。大規模化はANN索引を別段階にし、PostgreSQLのpgvectorは
|
||||||
|
選択肢として検証するが必須DB拡張にはしない。SQLiteとの差をAPI契約へ漏らさない。
|
||||||
|
|
||||||
|
## 4. Cityへの提案と適用(CITY-SEM-02、未実装)
|
||||||
|
|
||||||
|
1. 既存のStreet/Spotに属する文書の代表ベクトルから候補を提示する。十分な文書が
|
||||||
|
ない場合は候補なし。類似度は確率ではなく、top-k候補・代表文書・根拠の語句を示す。
|
||||||
|
2. 未整理文書は小規模クラスタの候補を表示し、人が名前・親・境界を選ぶ。Embedding自体に
|
||||||
|
生成AIの命名能力はない。初版のラベルは見出し/キーワード候補と手入力にする。
|
||||||
|
3. 閲覧者に見える文書だけで根拠・件数を作る。非公開文書由来のクラスタ名や特徴を公開しない。
|
||||||
|
4. 現行のQuartier→Street→SpotのPath境界を維持。同じ親の境界重複やSpotの任意ネストを
|
||||||
|
類似度のために許可しない。範囲外の類似ページは関連付け候補とし、primary所属とは分ける。
|
||||||
|
5. 初版は提案のみ。自動rename・削除・merge・新規Path作成はしない。適用機能では計画の差分、
|
||||||
|
影響するPath/公開範囲、入力版、承認者、要求IDを固定し、並行編集時は再提案する。
|
||||||
|
6. 手動名・手動配置・拒否した提案を保持する。定期ジョブが手作業を戻さない。
|
||||||
|
|
||||||
|
品質は合成/明示同意データで評価し、top-k採用率、誤配置率、日本語・英語・コード・短文別、
|
||||||
|
遅延、最大メモリ、API費用、同一入力の安定性を両方式で比較する。未知・低信頼は保留する。
|
||||||
|
公開範囲変更と同時の推論、削除後の候補非表示、停止・再開、モデル更新、類似URLだが別内容も試験する。
|
||||||
|
|
||||||
|
## 実施チェックリスト
|
||||||
|
|
||||||
|
- [x] AI-01:CLIスキル初版の配布用ソース(グローバル導入・独立CLIリリースは未実施)
|
||||||
|
- [ ] AI-01受入:エージェント行動テストとpages-cliリリースへの同梱
|
||||||
|
- [ ] AI-02 M1:SDK/プロトコル版・認証方式決定、読取MCP、両DBと実クライアント試験
|
||||||
|
- [ ] AI-02 M2:条件付き保存・冪等なタスク作成・監査
|
||||||
|
- [x] ML-01:独立サービス、認証/入力上限、Goクライアント、両provider、Doc2Vec合成結合試験
|
||||||
|
- [ ] ML-02:モデル失効・配布、設定・予算、既存キューへの接続、実行状態UI
|
||||||
|
- [ ] CITY-SEM-01:本文抽出・永続索引・分類品質評価・差分キュー(provider基盤のみ実装)
|
||||||
|
- [ ] CITY-SEM-02:候補比較UI・手動修正保護・明示適用
|
||||||
|
|
||||||
|
## 一次資料
|
||||||
|
|
||||||
|
- [OpenAI Embeddings](https://developers.openai.com/api/docs/guides/embeddings):関連度・分類向けの数値表現。
|
||||||
|
- [Gensim Doc2Vec](https://radimrehurek.com/gensim/models/doc2vec.html):学習と推論にtoken列を使用。
|
||||||
|
- [MCP 2025-11-25 transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports)
|
||||||
|
/[authorization](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization):初期相互運用の参照版。
|
||||||
|
最新版/SDK対応状況は実装開始時に再照合する。
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
# SQLite依存の縮小とPostgreSQL/MySQL対応
|
||||||
|
|
||||||
|
2026-11-30更新。既存PostgreSQL対応を維持し、新規ML機能からMySQL対応を検証する。
|
||||||
|
SQL文字列をdriverで置換する方式や、未対応時のSQLite自動fallbackは採用しない。
|
||||||
|
既存本番DBの切替・実データ移行は本作業と分離する。
|
||||||
|
|
||||||
|
## 現状と今回の到達点
|
||||||
|
|
||||||
|
| 対象 | SQLite | PostgreSQL | MySQL |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Pages本体の起動 | 既存 | 既存のnative起動・SQLite import経路あり | 未対応。起動オプションを追加しない |
|
||||||
|
| ML設定/日次予算 | 実DB共通試験成功 | PostgreSQL 17で成功 | MySQL 8.4で成功、限定component pilot |
|
||||||
|
| ML予算schema | 明示migration | 明示migration | native migration、版/checksum台帳、検査・明示再開CLI。実DB試験済み、本番未適用 |
|
||||||
|
| Campus/Domain/設定 | 既存 | 既存 | DB-COREa+b:Campus作成・更新、ホスト解決、設定、standalone Campus内のlocal Domain作成・更新。Domain/Campus削除は未対応 |
|
||||||
|
| ユーザー/グループ | 既存 | 既存 | パスワードアカウント、所属、group/permission、管理者継承・失効の限定保存API。HTTP認証・完全な認可境界は未接続 |
|
||||||
|
| 認証設定/管理 | 既存 | 既存 | provider設定・暗号化secret保持、外部ID、challenge、TOTP、profile/avatarの保存処理。Domain別session一覧・失効を限定APIへ接続。CLI認証handoff・監査は未対応 |
|
||||||
|
| DBバックアップ/DR | 既存SQLite方式 | native backup、現行DR起動は拒否 | 設計・実装未着手 |
|
||||||
|
|
||||||
|
MySQL接続を`internal/db/mysql.go`に追加。既定は検証付きTLSのみ、秘密情報を含むdriverエラーや
|
||||||
|
DSNをログ/応答に出さない。multi-statements、LOCAL INFILEの全ファイル許可、平文fallback等を拒否。
|
||||||
|
TLSを緩める指定は使い捨て試験専用。現在の接続設定は意図的に限定している。
|
||||||
|
各プール接続へ所有コードの厳格sql_modeを設定し、長い値の黙示的な切詰め/不正値の変換を拒否する。
|
||||||
|
|
||||||
|
`MySQLMLRepository`はML設定と予算操作だけを公開する。`*Store`を外へ返さず、
|
||||||
|
未移植のメソッドがSQLite分岐へ流れるのを防ぐ。Domainの認可は既存API側の責務であり、
|
||||||
|
このfacadeを匿名/任意Domainの外部APIへ直接接続しない。
|
||||||
|
|
||||||
|
`MySQLNamespaceRepository`も移植済みメソッドだけを公開する。認可チェックは上位の責務。
|
||||||
|
Campusの外部管理への登録や削除はfederation等が未移植のため公開しない。
|
||||||
|
Domain変更は`MySQLIdentityRepository`で、built-in group/管理者継承と同一transactionに接続した。
|
||||||
|
対象はstandalone Campus/local placementのみ。remote/controller/managedの変更は拒否する。
|
||||||
|
旧SQLite schema初期化やDomain削除は引き続き未対応エラーで停止する。
|
||||||
|
|
||||||
|
`MySQLIdentityRepository`は保存APIであり、呼出元が認証・認可する必要がある。
|
||||||
|
権限評価の下位primitiveを完全なAuthorizeの代用として公開しない。
|
||||||
|
OIDC/LDAP/SMTP設定とsecret保持、外部ID紐付け、challenge、TOTP、profile/avatarの保存処理は
|
||||||
|
MySQLにも移植したが、HTTPサーバーや実providerとは未接続。CLI認証handoff、監査、
|
||||||
|
locality/publication policyまで含む完全な認可境界は未移植。
|
||||||
|
パスワード照合・session purpose/Domain分離・失効のprimitiveは実DB試験済みだが、
|
||||||
|
MySQLで本体ログイン画面が使えることを意味しない。
|
||||||
|
|
||||||
|
## 修正したSQL差異
|
||||||
|
|
||||||
|
- 予約前のロック:SQLiteはwriter確保、PostgreSQL/MySQLは設定行の`SELECT … FOR UPDATE`。
|
||||||
|
値を変えないUPDATEのRowsAffectedへ依存しない。
|
||||||
|
- 予約transaction:PostgreSQL/MySQLはREAD COMMITTED。ロック待機後に最新の予算を見る。
|
||||||
|
- UPSERT:SQLite/PostgreSQLはON CONFLICT、MySQLはON DUPLICATE KEY UPDATE。
|
||||||
|
設定の初回作成はMySQLの重複キーだけを競合へ変換し、INSERT IGNOREで他の不整合を隠さない。
|
||||||
|
- 設定CAS:MySQLではJSON文字列をbinary比較。新世代UUIDで実更新になるためchanged-row semanticsでも動作。
|
||||||
|
- MySQLのキー列:TEXT主キーではなくサイズを定めたVARCHAR/CHAR、ASCII binary collation。
|
||||||
|
本文設定はutf8mb4。InnoDB/CHECK制約を使う。
|
||||||
|
- 共通configのkeyは版2でVARCHAR(255)/utf8mb4_0900_binへ拡張。
|
||||||
|
日本語・大文字小文字・末尾空白・Unicode合成形を区別し、既存値と版1checksumは保持する。
|
||||||
|
- ホスト名の結合はMySQLのCONCATを使用。sql_modeで`||`の意味を変えて互換化しない。
|
||||||
|
- topology更新はMySQLでは専用行のtransaction lockを使う。WHERE 0のUPDATEに排他を期待しない。
|
||||||
|
既存PostgreSQLはadvisory transaction lock、SQLiteはwriter予約を維持する。
|
||||||
|
- MySQLの予約語groupsは識別子として明示quoteする。所有SQLの構築段階で分岐し、driverで書き換えない。
|
||||||
|
- groupメンバー/permission/継承設定は、MySQLのUPSERTのRowsAffected=0/1/2を存在判定に使わない。
|
||||||
|
所有者の降格・最後の所有者の削除は行政用transaction lock内で検査し、同値の再設定は成功とする。
|
||||||
|
- Campus管理者の投影は独立したgrantを入力とし、投影結果を再度の継承元にしない。
|
||||||
|
派生所属の除去とsession失効は元の設定変更と同時commit。MySQLの派生UUIDはUUID()を使う。
|
||||||
|
MySQL replication/HAは未受入(将来はROW形式等も含めて検証する)。
|
||||||
|
- providerの空secret更新では、UPSERT内で既存暗号文を保持する。外部IDは同一所有者の再設定を許し、
|
||||||
|
別principalへの再紐付けを拒否する。MySQLでは共通管理transaction lockで所有者確認と更新を直列化する。
|
||||||
|
- MySQLの単一テーブルUPDATEは代入順の差があるため、TOTPの失敗回数を増やす前に制限到達を判定する。
|
||||||
|
全backendで5回目にchallengeを消費し、コード・challengeの同時利用は一度だけ成功する。
|
||||||
|
- MySQLのDDLは暗黙commitがあるため、PostgreSQLのtransactional migrationを流用しない。
|
||||||
|
専用connectionのGET_LOCKと操作単位のjournalを併用する。通常applyは途中失敗を拒否し、
|
||||||
|
resumeのみが事後条件を確認して再開する。成功済みDDLを無条件に繰り返さない。
|
||||||
|
|
||||||
|
## 実施順と受入ゲート
|
||||||
|
|
||||||
|
1. **DB-ML(実装済み)**:ML設定・予算の3DB共通試験。ドライバ、ロック、照合、CAS差異の検証。
|
||||||
|
2. **DB-MIG(基盤実装済み)**:MySQLの版/checksum台帳、途中DDLからの回復、schema assertion、read-only検査。
|
||||||
|
ML schemaで実証。未知版/履歴改変/主キー欠落を拒否。実行中のschemaを勝手に採用しない。
|
||||||
|
全機能のDDL移植、CHECK式の意味まで含む厳密なschema比較、backup・復旧手順の受入は後続。
|
||||||
|
3. **DB-CORE**:Campus/Domain、config、ユーザー/グループ/認可、document metadata、revision/Path。
|
||||||
|
Pathの大文字小文字、日本語、末尾空白、NULLとunique、UUIDの同一性を両DBで検証する。
|
||||||
|
**DB-COREa実装済み**:Campus作成・設定更新、Domainの読み取り・ホスト解決、config。
|
||||||
|
**DB-COREb基盤実装済み**:principal/membership/built-in group、管理者継承、local Domain書込。
|
||||||
|
次はDB-COREcで文書metadata・Revision・Pathを移植する。
|
||||||
|
COREbの認証保存処理(外部ID/provider・MFA・profile)とsession管理は移植済み。
|
||||||
|
残件(CLI認証handoff・完全な認可snapshot・監査・group編集・認証/管理UI接続)も本体接続前に消化する。
|
||||||
|
部分対応を本体対応と混同しない。
|
||||||
|
4. **DB-JOBS**:activity outbox/イベントキュー/claim/lease/ログ保持を移植。
|
||||||
|
ワーカーの再起動・同時claim・timeout・receipt保持を確認してからML workerを接続する。
|
||||||
|
5. **DB-EXT**:タスク/CalDAV、カレンダー、連絡先、RSS、通知、City、資産、検索。
|
||||||
|
SQLite FTS/PostgreSQL検索を単純にMySQL FULLTEXTへ置換せず、日本語と権限付き検索を比較する。
|
||||||
|
6. **DB-APP**:全機能の起動検査、import/backup/復旧、CI matrix、管理画面の実ブラウザ検証。
|
||||||
|
ここまで通してからMySQLをPages本体の選択可能backendにする。
|
||||||
|
7. **DB-DECOUPLE**:portable repositoryとSQLite実装をパッケージ境界で分離し、
|
||||||
|
PostgreSQL/MySQL-onlyバイナリからSQLite driverを外せる構成を検討する。
|
||||||
|
|
||||||
|
粗い静的走査ではstore内にPRAGMA/sqlite_master/INSERT OR/COLLATE BINARY等の参照が64行ある。
|
||||||
|
これは未対応箇所数ではない(SQLite専用migration/import/分岐も含む)。主な確認先は
|
||||||
|
`schema_modules.go`、`config.go`、`domains.go`、`domain_paths.go`、`activity_outbox.go`、
|
||||||
|
`event_log_write.go`、`tasks*.go`、`feeds.go`、`contacts.go`、`object_listing.go`。
|
||||||
|
さらに`metadata.Repository`がSQLite/PostgreSQLの2backendに限定され、SQLiteのエラー型も直接参照している。
|
||||||
|
MySQL enumを増やしただけで全体対応を宣言せず、各repositoryの受入試験を移植単位とする。
|
||||||
|
|
||||||
|
## 再現試験
|
||||||
|
|
||||||
|
2026-11-30コミット整理時にも、使い捨てのMySQL 8.4/PostgreSQL 17とSQLiteで
|
||||||
|
下記のnamespace・identity・ML・migration契約を`-race -count=1`で再検証した。
|
||||||
|
`TestAccountBackend*`のCLI handoffは引き続きSQLite/PostgreSQLのみであり、
|
||||||
|
MySQL対応済みの範囲には含めない。Goクライアント/設定APIの回帰と
|
||||||
|
`go vet ./internal/db ./internal/machinelearning ./internal/store ./cmd/pageswiki`も成功。
|
||||||
|
全パッケージの全テスト、本番切替、MySQLでのHTTPサーバー起動確認を意味しない。
|
||||||
|
|
||||||
|
使い捨てPostgreSQL/MySQLを起動し、次の環境変数を設定して実行する。
|
||||||
|
本番DSNを渡さない。MySQL試験はCREATE DATABASE権限を要し、一意な試験DBを作成・削除する。
|
||||||
|
PostgreSQL試験は同様に一意schemaを作成・削除する。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PAGESWIKI_TEST_POSTGRES_DSN='postgres://USER:PASS@127.0.0.1:PORT/postgres?sslmode=disable' \
|
||||||
|
PAGESWIKI_TEST_MYSQL_DSN='USER:PASS@tcp(127.0.0.1:PORT)/mysql' \
|
||||||
|
go test -race ./internal/store ./cmd/pageswiki -run 'TestMLBudget|TestMachineLearningPolicyPersistence|TestMySQL|TestNamespaceCoreThreeBackendContract|TestStoreNamespaceBackendContract|TestDomainWriteBackend' -count=1 -v
|
||||||
|
```
|
||||||
|
|
||||||
|
未設定backendはSKIPとなる。SKIPを成功実績に数えない。2026-11-28の実試験では3backendともPASS。
|
||||||
|
設定の保存・競合・破損拒否、同時予算予約、日付境界、ID重複、世代変更、失敗時非返却を共通検証。
|
||||||
|
今回本番移行・自動migration・ML送信は行っていない。
|
||||||
|
|
||||||
|
2026-11-30:DB-COREaの共通契約もSQLite/PostgreSQL 17/MySQL 8.4で成功。
|
||||||
|
FQDN競合時のrollback、同時作成、取消、read-only、日本語・絵文字、Domain設定分離、
|
||||||
|
configキーのNO PAD比較を検証。MySQLの版1→版2で既存データを保持し、暗黙commit後の再開も試験する。
|
||||||
|
|
||||||
|
同日DB-COREb:`TestAdminInheritanceBackend*`、`TestGeneralGroupBackend*`、
|
||||||
|
`TestGroupPermissionBackend*`、`TestRoleGrantBackend*`、`TestPrincipalStateBackend*`、
|
||||||
|
AccountBackendのbootstrap/login/session/concurrent-bootstrap試験を3DBへ拡張。
|
||||||
|
MySQL専用の`TestMySQLIdentity*`はfacadeからDomain作成→owner作成→継承→Campus移動→session失効、
|
||||||
|
故障注入時のDomain rollback、schema復旧、跨Domain拒否を検証する。
|
||||||
|
上記の使い捨てDSNを設定して、次で再現できる。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go test -race ./internal/store ./cmd/pageswiki \
|
||||||
|
-run 'TestAdminInheritanceBackend|TestGeneralGroupBackend|TestGroupPermissionBackend|TestRoleGrantBackend|TestPrincipalStateBackend|TestAccountBackend(BootstrapProjectionFailureIsAtomic|LoginAndSession|ConcurrentBootstrap)|TestMySQL|TestDomainWriteBackend' \
|
||||||
|
-count=3
|
||||||
|
```
|
||||||
|
|
||||||
|
この反復試験は3回成功。既存CampusAdmin移行・失効試験とML/namespaceの回帰試験も成功。
|
||||||
|
全機能のMySQL本体受入試験ではない。
|
||||||
|
|
||||||
|
## MySQL migrationの運用境界
|
||||||
|
|
||||||
|
MLの3テーブルは`internal/store/mysql_ml_schema.sql`を版1として管理する。公開後は既存版を編集せず、
|
||||||
|
追加版で変更する。MySQL 8.4で、暗黙commit後のjournal更新漏れ、途中DDL失敗、並行実行、
|
||||||
|
版追加、未知版拒否、schema drift、台帳主キー破損、取消後のロック解放を試験する。
|
||||||
|
`status/check`は台帳を作らず検査する(同時DDLとの競合防止にsession lockのみ取得)。
|
||||||
|
`apply/resume`は明示指定時のみ実行し、Pagesの通常起動へ自動接続しない。
|
||||||
|
|
||||||
|
事後条件は各operationの責務。非冪等DMLをReplaySafeにしてはならない。
|
||||||
|
CHECK制約の現在の検査は個数までであり、同数の別式への差し替えを検出するものではない。
|
||||||
|
台帳検査もDB管理者による任意改ざんを防止するセキュリティ機構ではない。
|
||||||
|
実行前にバックアップを取得し、dirty時は原因調査・必要な修復後に明示resumeする。
|
||||||
|
CLI手順は[ML運用](../../operations/pages-machine-learning.md#mysqlのml-schema管理)を参照。
|
||||||
|
|
||||||
|
### Namespace pilotの操作
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pageswiki mysql-namespace-schema status
|
||||||
|
pageswiki mysql-namespace-schema apply
|
||||||
|
pageswiki mysql-namespace-schema check
|
||||||
|
pageswiki mysql-namespace-schema resume
|
||||||
|
```
|
||||||
|
|
||||||
|
接続先は同じ`PAGESWIKI_MYSQL_DSN`。空の専用DBにだけ明示的に適用する。
|
||||||
|
このコマンドも本体の起動オプションではない。Campus/Domainのデータや管理者を自動作成しない。
|
||||||
|
status/checkは読み取り専用。applied/pendingは依存componentも含む合計、dirty_componentは
|
||||||
|
先に修復するcomponent、next_operationはそのcomponent内の次の操作位置。
|
||||||
|
|
||||||
|
現在のconfigは最初のML移行台帳に所有させたまま、namespace側から依存する。
|
||||||
|
二つの移行履歴で同じテーブルを作成・adoptしない。ML台帳がdirtyなら先に
|
||||||
|
`mysql-ml-schema resume`で修復し、その後namespaceを再開する。
|
||||||
|
これは過渡期の所有境界であり、将来のbase-schema整理でも既存checksumを書き換えない。
|
||||||
|
|
||||||
|
このnamespace facade単体ではDomain変更を公開しない。後述identity facadeを使う。
|
||||||
|
未対応:Domain/Campus削除、個人設定、完全な認可、文書・Path、外部管理の同期、
|
||||||
|
全体import/backup。本番schemaの自動adoptは行わない。MySQL namespaceの制限は名前255文字、
|
||||||
|
設定キー255文字、UUIDはcanonical形式。制限超過はエラーにし、黙って切り詰めない。
|
||||||
|
|
||||||
|
### Identity/group pilotの操作
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pageswiki mysql-identity-schema status
|
||||||
|
pageswiki mysql-identity-schema apply
|
||||||
|
pageswiki mysql-identity-schema check
|
||||||
|
pageswiki mysql-identity-schema resume
|
||||||
|
```
|
||||||
|
|
||||||
|
前提componentのML/config、namespaceも含めて検査・適用する。ユーザーやパスワード、Domainデータは
|
||||||
|
このCLIで自動作成しない。失敗時はdirty_componentを調査し、依存順に各CLIのresumeを明示実行する。
|
||||||
|
authの台帳名はstore-auth-core。版1の14テーブル・checksumを維持し、版2でauth_challenges/
|
||||||
|
auth_providersを追加する。列型・照合・主キー・uniqueを検査する。依存を含む適用済み版数は5。
|
||||||
|
既存principalを持つ版1からの更新、dirty拒否と明示resume、providerのunique欠落拒否も試験対象とする。
|
||||||
|
版2の最終assertionには版1の全table検査を引き継ぎ、追加後も既存permission等のschema driftを検出する。
|
||||||
|
|
||||||
|
保存APIの範囲:初期owner/password account、Domainユーザー一覧・state、group作成/一覧/
|
||||||
|
メンバー追加・除去、Path permission設定、Campus管理者の継承設定、local Domain作成・更新、
|
||||||
|
Domain別session一覧・失効。session操作はcontext取消・read-only失効拒否・跨Domain拒否を検査する。
|
||||||
|
権限profileは既存read/read_write_once/read_write/upload_onlyの意味を維持し、writeはdeleteを含まない。
|
||||||
|
各変更の呼出権限チェックは上位の責務。外部API/MCPへの直接公開は禁止。
|
||||||
|
|
||||||
|
寸法:UUID 36、identity issuer/subject・credential identifier 255、permission scope Path/grant target 512文字。
|
||||||
|
既存データのimportは未対応で、上限を超える値を切り詰めて取り込まない。
|
||||||
|
COREcで文書Pathの最大長とpermission scope/grant targetの上限を整合させる。
|
||||||
|
groupの編集/archive、profile/avatar・provider/MFA等の管理UI接続、CLI認証handoff、監査、
|
||||||
|
完全な認可snapshot、Domain削除・federation・backupは後続。
|
||||||
|
Domain削除は文書・拡張機能の関連データ移植後に扱い、未対応tableを残した部分削除はしない。
|
||||||
|
公開前にこれらと文書metadataを接続する。
|
||||||
|
|
||||||
|
認証保存処理の共通試験は`TestAccountBackendExternalIdentity`、`TestAccountBackendProviderSecrets`、`TestAccountBackendTOTP`、
|
||||||
|
`TestAccountBackendProfileAndSessionManagement`。MySQLを追加し、暗号文保持・同一ID再設定・
|
||||||
|
不正な再紐付け・重複作成rollback・challenge同時消費・TOTP再登録と5回制限・avatarのbinary往復・
|
||||||
|
session Domain分離を検証する。実OIDC/LDAP/SMTPへの接続や既存ユーザーデータの読取は行わない。
|
||||||
|
|
||||||
|
2026-11-30の追加試験:上記4本と`TestMySQLIdentity*`/schema CLIを、SQLite・PostgreSQL 17・
|
||||||
|
MySQL 8.4で`-race -count=3`実行し成功。既存HTTPログイン・LDAP/OIDC設定・trusted session・
|
||||||
|
CLI OIDCの回帰試験も成功。本体MySQL受入や外部サービス接続の成功を意味しない。
|
||||||
@@ -44,6 +44,13 @@ IDなしRSSは記事URL、URLもなければ題名・日時・本文の組合せ
|
|||||||
|
|
||||||
### 高密度ビューア
|
### 高密度ビューア
|
||||||
|
|
||||||
|
2026-11-17:記事のX共有は通常クリックで640×720のポップアップを要求する。
|
||||||
|
クリックの同期処理中に一度だけ開き、元画面の遷移を抑止する。`noopener,noreferrer`
|
||||||
|
指定時の戻り値がnullでも別タブへ再試行しない。Ctrl/Cmd等の修飾クリックは通常の
|
||||||
|
リンク操作を保つ。ブラウザ設定やモバイルではタブ表示となる場合がある。
|
||||||
|
Chromiumのデスクトップ/モバイル幅テストで呼出し回数・元画面の保持・修飾クリックを検証。
|
||||||
|
本番反映は別途行う。
|
||||||
|
|
||||||
newsboat/neomuttを参考に、デスクトップは左から購読元・一行記事一覧・本文の3ペインとします。
|
newsboat/neomuttを参考に、デスクトップは左から購読元・一行記事一覧・本文の3ペインとします。
|
||||||
一覧には未読/star、日付、配信元、件名を並べます。狭幅は一覧と本文を切り替え、スマホでは
|
一覧には未読/star、日付、配信元、件名を並べます。狭幅は一覧と本文を切り替え、スマホでは
|
||||||
行とボタンのタッチ領域を広げます。モバイルの共通ナビはアイコンのみとし、名称はアクセシブル名と
|
行とボタンのタッチ領域を広げます。モバイルの共通ナビはアイコンのみとし、名称はアクセシブル名と
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# ファイル検査と配信制御
|
||||||
|
|
||||||
|
2026-11-30。アップロード受入、ファイル検査、Webへの配信許可を分離する。
|
||||||
|
**現段階は共通評価器・プラグイン契約・実行器のみ実装済み。HTTP配信制限、DB保存、
|
||||||
|
イベント登録、管理画面、実検査エンジンは未接続。現在のアップロードに検査が追加されたわけではない。**
|
||||||
|
|
||||||
|
利用者合意により、今回の実装範囲はSCAN-01/02の骨子までで一旦区切る。
|
||||||
|
SCAN-03以降は設計上の残件として保持し、このコミットを契機に自動で着手・有効化しない。
|
||||||
|
|
||||||
|
## 公開範囲・権限との関係
|
||||||
|
|
||||||
|
公開範囲は既存のDomain → Quartier → Street → Spotと、それらのPath境界に従う。
|
||||||
|
下位の既定値はinherit。上位の制約を下位が緩和できない。
|
||||||
|
公開可能な上限、Revisionの明示/自動公開、認証後のread/writeは別の判定として維持する。
|
||||||
|
検査結果は追加の配信条件であり、cleanになっても非公開文書を公開したり、権限を付与したりしない。
|
||||||
|
|
||||||
|
検査設定も同様に継承する。初期状態はdisabled。下位で明示したdisabledでも、上位の
|
||||||
|
monitor/requiredを解除しない。上位で要求したエンジンを下位で削除・別版へ置換しない。
|
||||||
|
下位で別エンジンを追加する場合は、すべての必要な検査を通す。
|
||||||
|
エンジン更新・検査解除は、その上位設定を変更できる管理者が明示的に行う。
|
||||||
|
|
||||||
|
| モード | 配信判定 |
|
||||||
|
| --- | --- |
|
||||||
|
| inherit | この範囲で追加の指定をせず上位に従う |
|
||||||
|
| disabled | 上位に制約がなければ既存の配信判定を維持 |
|
||||||
|
| monitor | 検査結果を記録・表示するが、検査だけを理由に配信を止めない |
|
||||||
|
| required | 必須エンジンすべてについて、有効なclean結果が必要 |
|
||||||
|
|
||||||
|
monitorはmaliciousでも配信を止めない明示的な観測モード。設定画面でこの性質を説明する。
|
||||||
|
requiredでエンジンが無効・不在・異常・期限切れなら拒否する。プラグイン停止を検査免除と解釈しない。
|
||||||
|
|
||||||
|
## 保存と非同期処理
|
||||||
|
|
||||||
|
1. 認証、create/write権限、条件付き保存、サイズ、MIME等を既存の保存境界で検証する。
|
||||||
|
2. 不変Documentを永続化する。Path・Revision・検査要求outboxは対応するDB transactionで公開する。
|
||||||
|
3. outboxをイベントキューへ転送し、重複を抑止して検査を実行する。
|
||||||
|
4. 現在のポリシー、送信同意、ジョブ所有権を再確認し、結果を条件付きで保存する。
|
||||||
|
5. 配信要求ごとに既存のアクセス権・公開状態と、有効な検査結果を確認する。
|
||||||
|
|
||||||
|
アップロードHTTP要求中にスキャナーの完了を待たない。配信要求から同期スキャンもしない。
|
||||||
|
保存成功と配信可能は別。検査待ちであっても保存済みなら保存APIは失敗扱いにしない。
|
||||||
|
CLIの新規作成PUT契約の201・identityヘッダーを維持し、検査状態は別メタデータとして追加する。
|
||||||
|
CLIは独自サニタイズや自動再送を行わない。スキャナーは保存本文を書き換えない。
|
||||||
|
無害化/CDRを将来追加する場合は、別Document/Revisionと由来を記録し、黙って置換しない。
|
||||||
|
|
||||||
|
## 結果と識別子
|
||||||
|
|
||||||
|
結果キーはDomain UUID、ポリシー世代、保存内容のSHA-256、エンジンID・版・定義版。
|
||||||
|
Path名やUUID単独、ファイル名、アップロード側が申告した検査結果を根拠にしない。
|
||||||
|
エンジンはclean/suspicious/maliciousを返す。本体はpending/error/expiredも管理する。
|
||||||
|
cleanは当該検査で検出なしを意味し、安全性の絶対保証ではない。
|
||||||
|
|
||||||
|
ポリシー世代は設定・関係するtopology・エンジン有効状態の変更時にサーバーが更新する。
|
||||||
|
初版はDomain世代の変更で保守的に無効化する。大規模Domainの再検査負荷は後続でscope単位へ分割する。
|
||||||
|
別Domainの同じhashには結果を流用しない。別エンジン版・定義版・世代や期限切れの結果も使わない。
|
||||||
|
検査開始・終了時刻、期限、監査用ジョブID、worker lease、試行番号、判定を保存する。
|
||||||
|
プラグインの生の例外・ファイル本文・資格情報を通常ログや通知へ出さない。
|
||||||
|
|
||||||
|
DB保存案は`inspection_policies`、`inspection_reports`と既存outbox/queueを使用する。
|
||||||
|
reportsは上記キーをuniqueとし、古い試行や失効leaseによる上書きを拒否する。
|
||||||
|
SQLはSQLite/PostgreSQL/MySQLのnative migrationと共通契約試験で追加する。
|
||||||
|
CHECKや索引を含むschema検査、既存版のchecksum保持を実施し、SQLite専用SQLを共通処理へ増やさない。
|
||||||
|
|
||||||
|
## プラグインと実行制約
|
||||||
|
|
||||||
|
検査はビューア/エディタではなくシステム拡張。拡張カタログへ公開するのは配信ゲート接続後。
|
||||||
|
現段階の`internal/inspection.Registry`はアプリ所有の信頼済み実装のみ登録でき、登録直後は無効。
|
||||||
|
任意コマンド実行、アップロードされたコードのロード、URLからのプラグイン取得は行わない。
|
||||||
|
実際のスキャナーはまだ登録していない。合成テストの模擬スキャナーを製品へ有効化しない。
|
||||||
|
|
||||||
|
実行器はGeduldhの不変Storeから読み、サイズとSHA-256をストリーム検証してからプラグインへ渡す。
|
||||||
|
プラグインには読み取りストリームのみ渡し、Path・Bearer・DB接続や保存変更権限は渡さない。
|
||||||
|
外部送信するプラグインは、Domain管理者の別の同意がないと読み取り開始前に拒否する。
|
||||||
|
送信URL、TLS、SSRF対策、応答上限、送信先サービスの保持・第三者再送方針は実アダプタ接続の受入条件。
|
||||||
|
|
||||||
|
実行枠は1〜4、入力上限は最大256 MiB、協調的timeoutは最大1分、結果TTLは最大24時間に制限する。
|
||||||
|
満杯時は待ち行列をメモリ上に増やさずErrBusyを返し、既存スケジューラで再配置する。
|
||||||
|
実行数、完了・失敗数、検証byte数、累積実行時間を取得可能。現状は実行器単位の値であり、
|
||||||
|
エンジン別永続集計、CPU/メモリ監視、設定画面への接続は後続。
|
||||||
|
|
||||||
|
実行直前・検証後・結果返却前に、呼出元のRecheckで世代・ジョブ・同意を再確認する。
|
||||||
|
結果DBへのcommitでは別途lease/世代CASが必須。コールバックだけでtransactionの代用にしない。
|
||||||
|
実行中のエンジン停止→再有効化も、旧実行結果を採用しない。
|
||||||
|
|
||||||
|
Go内プラグインはプロセス隔離ではない。contextを無視する実装を強制停止する保証はなく、
|
||||||
|
終了までは実行枠を保持する。実際の重い/外部エンジンはsidecarとCPU/メモリ/timeout制限を検討する。
|
||||||
|
恒久停止への対応・lease回収・再試行上限をイベントキュー側で担保してから有効化する。
|
||||||
|
|
||||||
|
## 配信・処理経路の受入ゲート
|
||||||
|
|
||||||
|
検査対象のバイト列を処理する前に共通ゲートを通す。HTTPであればETag/304・Range/206・
|
||||||
|
HEAD・identityヘッダー等を返す前に判定する。拒否応答はprivate,no-storeとする。
|
||||||
|
既にダウンロードされたデータやブラウザに残ったコピーの回収は保証できない。
|
||||||
|
|
||||||
|
| 経路 | 必要な確認 |
|
||||||
|
| --- | --- |
|
||||||
|
| 通常/匿名/ブログ等のビューア、履歴 | 対象Revisionと依存Document、公開・ACL判定を維持 |
|
||||||
|
| RAW、UUID、Revision、Asset、共有リンク | 名前空間やURL種別を変えて迂回しない |
|
||||||
|
| サムネイル、PDF/画像/アーカイブ解析、全文索引 | 未検査データを先にパーサーへ渡さない |
|
||||||
|
| エディタ、連携アダプタ、export、CLI get | バイト列引渡しを同じ条件で制御 |
|
||||||
|
| 生成済みpreview/cache/CDN | 元Documentとpolicy世代を保持し、旧キャッシュからの配信を防ぐ |
|
||||||
|
|
||||||
|
別名Pathを持つObjectは現在の関連範囲すべてを検査する。公開側の別名だけを選んで制約を外さない。
|
||||||
|
`DecidePaths`は渡された全Pathを評価し、空・上限超過・不正snapshotは拒否する。
|
||||||
|
ただし全Pathを列挙できたかは呼出元の責務。省略した配列を完全なsnapshotとして渡してはならない。
|
||||||
|
UUID/Asset/依存Documentの所属を解決できない場合も、ルートのdisabled設定に置き換えてはならない。
|
||||||
|
跨Domainでは各Domainの設定・権限を独立に評価する。
|
||||||
|
隔離ファイルを管理者が取得する操作を設ける場合は、通常RAWを例外化せず、専用監査経路とする。
|
||||||
|
|
||||||
|
## 段階と残件
|
||||||
|
|
||||||
|
| ID | 状態 | 内容 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| SCAN-01 | 実装済み | Path継承、世代・hash付き結果判定、別名の全件評価、認可と分離した追加ゲート |
|
||||||
|
| SCAN-02 | 実装済み | 無効開始の信頼済みプラグインregistry、制限付き実行器、合成試験 |
|
||||||
|
| SCAN-03 | 未実装 | 3DBの設定・結果保存、CAS/監査、outboxとqueue接続、lease/retry、プラグイン別計測 |
|
||||||
|
| SCAN-04 | 未実装 | 上表の全配信/解析経路への接続、依存物・別名・キャッシュ・HEAD/Range/304の結合試験 |
|
||||||
|
| SCAN-05 | 未実装 | 管理UI/CLI、継承元と実効値表示、監視モードの警告、権限制御、手動再検査 |
|
||||||
|
| SCAN-06 | 未実装 | MWDB/Karton等の実プラグイン、外部同意、隔離、資源制限、実機受入 |
|
||||||
|
|
||||||
|
SCAN-03/04完了まで必須モードをユーザーへ公開しない。本番データのスキャン・外部送信は別途明示的に開始する。
|
||||||
|
合成試験: `go test -race ./internal/inspection ./internal/schutzaria ./internal/geduldh -count=3`。
|
||||||
@@ -42,6 +42,42 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
|
|||||||
|
|
||||||
## 次の実施順
|
## 次の実施順
|
||||||
|
|
||||||
|
2026-11-30追記:利用者合意により[ファイル検査レイヤ](file-inspection.md)のSCAN-01/02を先行実装。
|
||||||
|
公開範囲は既存の上位Path継承を維持し、検査を追加の配信条件とする。
|
||||||
|
DB非依存のポリシー評価と無効開始のプラグイン実行基盤のみ。SCAN-03(3DB保存・queue)、
|
||||||
|
SCAN-04(全配信/解析経路)、SCAN-05/06(設定・実検査)を残件とし、未接続の必須モードは公開しない。
|
||||||
|
並行するpages-cliとの新規作成PUT契約は維持。検査待ちと保存失敗を混同しない。
|
||||||
|
利用者合意により検査レイヤはこの骨子で一旦区切り、SCAN-03以降への接続は保留する。
|
||||||
|
|
||||||
|
2026-11-28:SQLite固有依存を縮小し、PostgreSQL/MySQLへ段階的に移植する。
|
||||||
|
[DB移植計画](database-portability.md)のDB-MLを実DB3種類で検証済み。
|
||||||
|
DB-MIGの基盤(版/checksum台帳、operation journal、専用connection lock、schema検査、
|
||||||
|
明示resume、`mysql-ml-schema` CLI)をML schemaへ適用し、MySQL 8.4で実試験。
|
||||||
|
次はDB-CORE、DB-JOBSの順。CHECK式の厳密比較・全schema移植・backup受入は残件。
|
||||||
|
2026-11-30:DB-COREa(Campus作成・更新、Domain読取/ホスト解決、Domain別config)を限定MySQL facadeへ移植。
|
||||||
|
3DB共通試験とMySQL既存版からのデータ保持更新、名前空間schema CLIを追加。
|
||||||
|
同日DB-COREb基盤:principal/membership/built-in group/管理者継承とlocal Domain書込を一体で移植。
|
||||||
|
取消・独立grant保持・session失効・故障rollbackを3DBで比較、`mysql-identity-schema` CLIを追加。
|
||||||
|
続いてCOREbのprovider設定・暗号化secret保持・外部ID紐付け・challenge・TOTP・profile/avatar保存を移植。
|
||||||
|
Domain別session一覧・失効を限定APIへ接続。auth schema版2を追加し、版1の履歴とデータを保持する。
|
||||||
|
MySQLのUPDATE代入順によるTOTP失敗回数の差も修正し、3DB共通の5回制限を試験する。
|
||||||
|
次はCOREbのCLI認証handoff/監査/group編集と完全な認可snapshot、DB-COREcの文書metadata/Revision/Path。
|
||||||
|
管理UI接続、Domain削除・federationも残る。Domain削除は関連文書・拡張データを含めた移植後に行う。
|
||||||
|
保存pilotをHTTP認証サーバーとして公開しない。
|
||||||
|
ML後続はこの境界と整合させ、MySQL本体対応を宣言するのはDB-APP通過後とする。
|
||||||
|
|
||||||
|
2026-11-17、展示後の新サブプロジェクトは **AI向けpages-cliスキル → MCPサーバー →
|
||||||
|
OpenAI Embeddings/Doc2VecによるCity整理** の順。
|
||||||
|
[詳細設計・受入条件](ai-integration-and-city-organization.md)で AI-01、AI-02、
|
||||||
|
CITY-SEM-01/02を追跡する。CLIスキル初版とPages Machine Learningの内部サービス基盤は
|
||||||
|
ソース実装済み。MCP・文書抽出/ベクトル索引・自動整理UIは未実装。
|
||||||
|
[ML運用・実装境界](../../operations/pages-machine-learning.md)のML-02以降でキュー/設定を接続する。
|
||||||
|
2026-11-28:ML-02aのDomain別設定保存・世代付き競合検出・prefix除外・要求生成を追加。
|
||||||
|
同日ML-02bとして管理API/UI、ML-02cとして日次入力byte予算の永続予約を追加。
|
||||||
|
予算テーブルの本番適用、使用量表示・receipt保持方針、保存イベントへの接続は未実装。
|
||||||
|
既存文書の推論は開始しない。
|
||||||
|
下記2026-11-08の順序は過去の計画として保持し、既存の整合性・認可ゲートも維持する。
|
||||||
|
|
||||||
2026-11-08、利用者指定により、大きな機能を提供するサブプロジェクトを以下の順で進める。
|
2026-11-08、利用者指定により、大きな機能を提供するサブプロジェクトを以下の順で進める。
|
||||||
前案の小規模な回復・基盤改善を先に一巡する順序は、この順序へ置き換える。
|
前案の小規模な回復・基盤改善を先に一巡する順序は、この順序へ置き換える。
|
||||||
|
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ WebDAV/SSHFSの可変ファイルとimmutable CASは別です。最初はread-on
|
|||||||
|
|
||||||
MWDB/Karton等の接続はpending/clean/suspicious/malicious/error/expiredの状態と、engine・版・hash・時刻・由来を持つ非同期処理を案とします。監査必須の範囲ではcleanがない間のviewer/download/adapterを閉じます。scannerへ機密本文を送る操作には別の送信方針が必要です。
|
MWDB/Karton等の接続はpending/clean/suspicious/malicious/error/expiredの状態と、engine・版・hash・時刻・由来を持つ非同期処理を案とします。監査必須の範囲ではcleanがない間のviewer/download/adapterを閉じます。scannerへ機密本文を送る操作には別の送信方針が必要です。
|
||||||
|
|
||||||
|
2026-11-30:[ファイル検査と配信制御](file-inspection.md)へ詳細化。Path継承と追加判定、
|
||||||
|
プラグイン契約・制限付き実行器を実装。DB・queue・配信ゲート・実エンジンは未接続で、
|
||||||
|
現行アップロードを自動検査する状態ではありません。
|
||||||
|
|
||||||
## DRとHAの順序
|
## DRとHAの順序
|
||||||
|
|
||||||
次段階の詳細設計DR-D1は [役割・再参加](dr-authority-and-rejoin.md)、
|
次段階の詳細設計DR-D1は [役割・再参加](dr-authority-and-rejoin.md)、
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
# 20. 実装順序と受け入れ条件
|
# 20. 実装順序と受け入れ条件
|
||||||
|
|
||||||
|
2026-11-17追記:展示後の優先順は **AI向けCLIスキル → CLI不要のMCP →
|
||||||
|
OpenAI Embeddings/Doc2VecによるCity整理**。
|
||||||
|
[新サブプロジェクト](ai-integration-and-city-organization.md)と[残件台帳](implementation-backlog.md)を参照。
|
||||||
|
Pages Machine Learningの独立サービス基盤を先行実装。既存PagesのDB変更・自動索引化は未実施。
|
||||||
|
以下の日付付き計画は履歴として残す。
|
||||||
|
|
||||||
状態:2026-11-08再照合。旧Phase番号は原ロードマップとの対応用に残し、実装は依存関係とリスク順に進めます。
|
状態:2026-11-08再照合。旧Phase番号は原ロードマップとの対応用に残し、実装は依存関係とリスク順に進めます。
|
||||||
|
|
||||||
現在の作業単位・優先順・受入条件は[実装残件台帳](implementation-backlog.md)に集約しました。
|
現在の作業単位・優先順・受入条件は[実装残件台帳](implementation-backlog.md)に集約しました。
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# スライドショーの再生制御
|
||||||
|
|
||||||
|
状態:ソース実装とブラウザ検証済み。本番未反映。
|
||||||
|
|
||||||
|
pagesのスライドビューアとエディタのスライドプレビューに、再生/一時停止、ページ送り間隔、ループを設ける。正本本文やRevision、公開範囲は変更しない。
|
||||||
|
|
||||||
|
## 操作と時間
|
||||||
|
|
||||||
|
- 初期状態は停止、間隔30秒、ループなし。
|
||||||
|
- 間隔は整数の1〜3600秒。範囲外や空欄では新しい再生設定を送らない。
|
||||||
|
- 再生中にページを手動で切り替えると、次の送りまでの時間を設定秒数から数え直す。
|
||||||
|
- ループなしでは最終ページを設定秒数だけ表示して停止する。停止後、最終ページで再生すると先頭から開始する。
|
||||||
|
- ループありでは最終ページから先頭へ戻る。
|
||||||
|
- ブラウザの非表示中はタイマーを停止し、再表示後に設定秒数から再開する。非表示時間分をまとめて送らない。
|
||||||
|
- 同じプレビューを再描画する間は位置と再生設定を保持する。再読み込み後は停止に戻り、ブラウザへの永続設定保存は行わない。
|
||||||
|
|
||||||
|
ブラウザのタイマーは厳密な実時間保証ではない。表示中の10枚を30秒ずつ送る場合、通常動作で約5分となる。発表者による手動送りやタブの非表示時間は含めない。
|
||||||
|
|
||||||
|
## 信頼境界
|
||||||
|
|
||||||
|
親画面の操作部だけが再生設定を作り、sandbox iframeの固定スクリプトへ送る。iframe側は送信元がparentであること、描画ごとのtoken、固定message type、整数秒数とbooleanの型・範囲を検査する。親側も通知元のWindowとtokenを確認する。本文のdata属性、script、style、任意iframeは引き続き許可しない。
|
||||||
|
|
||||||
|
自動再生に認可権限はなく、読める本文の範囲は既存のPath認可に従う。ブラウザ履歴やURL hashを更新しない。ページを離れればiframeとタイマーを破棄する。全画面でも親の操作部を表示し、停止可能にする。
|
||||||
|
|
||||||
|
## 5分の技術紹介資料
|
||||||
|
|
||||||
|
編集元は `docs/presentations/pages-architecture-5min-ja.md`。10枚、30秒送りを目安にする。図の編集元は `static/diagrams/pages-architecture/*.svg`。構成・identity・City・保存順序を同じ配色で示し、残りは表と短い文章で説明する。
|
||||||
|
|
||||||
|
| 経過時間 | 内容 | 説明の焦点 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 0:00〜0:30 | pagesの狙い | 知識の住所と実体を分ける |
|
||||||
|
| 0:30〜1:00 | 全体構成 | Go・SQLite・Document Store・背景処理 |
|
||||||
|
| 1:00〜1:30 | identity | Path変更と複数参照で履歴を複製しない |
|
||||||
|
| 1:30〜2:00 | Knowledge City | 階層の案内と追加参照のグラフを両立する |
|
||||||
|
| 2:00〜2:30 | 保存 | Documentを先に永続化し、期待headを照合する |
|
||||||
|
| 2:30〜3:00 | Projection | 表示・編集形式を別正本にしない |
|
||||||
|
| 3:00〜3:30 | 認可と実行 | identity、read、publication、script実行の境界 |
|
||||||
|
| 3:30〜4:00 | 日々の作業 | タスク・DAV・RSS・メールとWikiを関連付ける |
|
||||||
|
| 4:00〜4:30 | 運用 | 前景優先、設定配信と記事複製の区別、単一writer |
|
||||||
|
| 4:30〜5:00 | まとめ | identity、探索、境界の維持 |
|
||||||
|
|
||||||
|
内容の根拠は `principles.md`、`address-storage.md`、`knowledge-city.md`、`viewer-editor.md`、`auth-permissions.md`、`publication.md`、`scheduler-resources.md`、`campus-federation.md`、`operations.md` とオーガナイザーの詳細契約。初期構想のMacaroon共有・任意プラグイン・自動HAを実装済みとして扱わない。
|
||||||
|
|
||||||
|
静的図版を含むアプリの反映後に、HTML化した5分版を既存の24枚版とは別Pathへ配置する。図版未配信の状態で既存の資料を置き換えない。
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
# 展示用PagesWikiのKubernetes配置とDNS認証
|
||||||
|
|
||||||
|
## 記録の位置づけ(2026-11-30整理)
|
||||||
|
|
||||||
|
展示は完了し、利用者から成功の報告を受けている。以下は準備・配置時点の記録で、
|
||||||
|
途中の疎通失敗や未確認項目も経緯として残す。現在の障害・稼働状態を示すものではない。
|
||||||
|
今回の整理ではクラスタ・公開URLへ接続せず、再配置・データ投入・Secret操作も行っていない。
|
||||||
|
|
||||||
|
最後に指定された入口は `https://pages.anya.jisaba.sh/`。初期の
|
||||||
|
`pages.jsb.anya.jp`/Cloudflare DNS-01案やHTTP公開案は採用済み設定ではない。
|
||||||
|
[展示ファイル一覧](../../deploy/kubernetes/exhibition/README.md)から用途別に参照する。
|
||||||
|
再利用時は当日の権限・保存先・証明書期限・イメージを確認し、ディレクトリ全体を一括applyしない。
|
||||||
|
|
||||||
|
## 最終指定の入口:HTTPS・pages.anya.jisaba.sh(当時の確認記録)
|
||||||
|
|
||||||
|
2026-11-15、利用者指定により入口を `https://pages.anya.jisaba.sh/` に再変更した。
|
||||||
|
展示キャンパスのFQDNを通常の設定APIで変更し、既存のドメインUUID・空ホスト指定・データを維持。
|
||||||
|
新しいHostでlocalhost限定port-forward越しのログイン、27文書、8タスク、6予定、6連絡先の
|
||||||
|
UID/ETagを確認済み。Serviceは引き続きHTTP port 80、アプリは3000。公開TLS終端はNOC管理。
|
||||||
|
|
||||||
|
この端末からDNS A `202.226.7.202` とHTTP 301による同一ホストHTTPSへの転送を確認した。
|
||||||
|
HTTPSは `/` と `/health` の両方で `Connection reset by peer`(curl exit 35)。
|
||||||
|
証明書検証の成功・公開ログイン・ブラウザ描画は未確認で、公開接続へ資格情報は送っていない。
|
||||||
|
TLS終端/経路/アクセス制御のどこが原因かは未確定。証明書検証を無効化して回避しない。
|
||||||
|
以前の `*.pages.jisaba.sh` とは別のホスト階層なので、新FQDNのListener・Route・証明書が必要。
|
||||||
|
PostgreSQL向けverified TLSは引き続き維持する。
|
||||||
|
|
||||||
|
## 旧公開案:HTTP・wiki.pages.jisaba.sh(上記で置換済み)
|
||||||
|
|
||||||
|
2026-11-15、利用者の確認により入口を `http://wiki.pages.jisaba.sh/` に変更した。
|
||||||
|
NOCへ `*.pages.jisaba.sh` のHTTP・80番転送を依頼済み(利用者報告)。
|
||||||
|
接続先は namespace `exhibit-anya`、Service `pageswiki`、port 80。
|
||||||
|
ワイルドカードに含まれない `pages.jisaba.sh` 自体は入口に使わない。
|
||||||
|
以下の `pages.jsb.anya.jp`・Cloudflare証明書の記述は旧案であり、現行の公開設定ではない。
|
||||||
|
|
||||||
|
既存キャンパスのFQDNだけを通常の設定APIで更新し、ドメインの空ホスト指定、UUID、
|
||||||
|
文書・設定・ユーザーは保持した。localhost限定port-forward経由で新Host名によるログインと
|
||||||
|
27文書、8タスク、6予定、6連絡先のUID/ETagを再確認した。外部カレンダーへはアクセスしていない。
|
||||||
|
公開DNSと会場からのHTTP到達・ブラウザ描画は別の確認事項。
|
||||||
|
HTTPRouteの参照権限はなく、NOC側の適用状況を直接確認できない。
|
||||||
|
|
||||||
|
公開HTTPではログイン資格情報・本文が暗号化されない。展示専用アカウント・合成データだけを使い、
|
||||||
|
本番の認証・秘密情報は持ち込まない。Web Push等のsecure context必須機能は利用できない。
|
||||||
|
これはブラウザ側の通信方針であり、アプリからPostgreSQLへのverified TLSは維持する。
|
||||||
|
任意のサブドメインがPagesのサイトとして自動作成されるわけではない。追加する場合はDomainの登録が必要。
|
||||||
|
|
||||||
|
## 2026年11月15日の配置記録(FQDN変更前を含む)
|
||||||
|
|
||||||
|
以下の初期案よりも、[運営の最新公開手順](https://github.com/cniajp/jisabakan-exhibit/blob/main/docs/publishing.md)と
|
||||||
|
[接続手順](https://github.com/cniajp/jisabakan-exhibit/blob/main/docs/omni-login.md)を優先する。
|
||||||
|
今回の展示は `anya/` → `exhibit-anya` の GitOps 配置であり、Gateway・HTTPRoute・TLS は NOC 管理。
|
||||||
|
この文書の Ingress・Certificate・公開用 LoadBalancer を参加者側で作る手順は適用しない。
|
||||||
|
独自ドメイン `pages.jsb.anya.jp` と Cloudflare DNS-01 を希望する場合も、公開先・TLS の受渡しを NOC と調整する。
|
||||||
|
|
||||||
|
保存済みの別端末用 kubeconfig で読取り・Deployment 作成権限を確認した。
|
||||||
|
`pageswiki-data` は `nfs-csi` の20Gi RWOで Bound、storage quotaの20Giを消費済み。
|
||||||
|
PagesWikiとPostgreSQLをそれぞれ1 replicaで起動済み。requests上限はCPU 2、メモリ4Gi、limits.memoryは8Gi、PVC上限は5。
|
||||||
|
SQLite WALをNFS上で動かさないため、PostgreSQL対応リリースを使って配置する。
|
||||||
|
本番のデータ・鍵・外部カレンダーは展示へ持ち込まない。
|
||||||
|
|
||||||
|
v0.18.0 は通常テスト・PostgreSQL 17実DBテスト・4イメージの公開とrelease昇格が成功済み。
|
||||||
|
アプリの固定イメージは `git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9`。
|
||||||
|
展示用の26ページ・8タスク・6予定・6連絡先は[合成データ手順](../../deploy/kubernetes/exhibition/demo/README.md)で生成できる。
|
||||||
|
通常のimport/API/DAV経路でWiki 26ページ、CSV 1件、タスク8件、予定6件、連絡先6件を投入済み。
|
||||||
|
DBとアプリのPod再作成後も認証・27文書・20 DAVリソースのUID/ETagを確認した。
|
||||||
|
公開FQDNのDNSは手元の名前解決では未登録。NOCのGateway/HTTPRoute/TLS設定と公開ブラウザ確認は残件。
|
||||||
|
|
||||||
|
PVC最上位はroot:root / 0755のまま保持し、承認されたroot初期化で新設した
|
||||||
|
`pageswiki-exhibit-v018/wiki` を10001:10001、`postgres`を70:70として分離した。
|
||||||
|
NFSv4のhard mount、非rootでのhard-link/no-replace・fsync・rename・読み戻しは隔離試験で成功。
|
||||||
|
既存領域の再帰的なchownは行っていない。NFS server側の障害時永続性はこの試験では保証しない。
|
||||||
|
root初期化にはPodSecurity restrictedの警告が出るが、現namespaceのadmissionは許可する。
|
||||||
|
常駐プロセスは非root。クラスタのポリシー自体は変更していない。
|
||||||
|
|
||||||
|
配置済みのマニフェストは `deploy/kubernetes/exhibition/postgres.yaml` と `app.yaml`。
|
||||||
|
今回はkubectlで直接適用しており、運営GitHubの `anya/` へのGitOps反映は未実施。
|
||||||
|
`bootstrap.yaml` は一度限りの初期化用で、継続同期するディレクトリへ入れない。
|
||||||
|
空のSQLiteはemptyDirで起動・停止し、verified TLSで全件importした。
|
||||||
|
停止した合成SQLiteはアプリPVC内の `bootstrap-source/pages.db` に監査用として保存するが、通常起動では開かない。
|
||||||
|
`import-complete.json` が完了記録。初期化Jobを削除・再作成して再移行しない。
|
||||||
|
|
||||||
|
Secretは `pageswiki-exhibition-app`、`pageswiki-exhibition-db`、`pageswiki-exhibition-tls`。
|
||||||
|
新規生成した展示専用値のみを使い、public repositoryへは記録しない。
|
||||||
|
PostgreSQLのサーバー証明書は90日、専用CAは180日で失効するため、長期展示では更新が必要。
|
||||||
|
管理者名は `exhibition-admin`。パスワードはapp Secretの `owner-password` を管理端末で確認する。
|
||||||
|
アプリのFQDN設定は `pages.jsb.anya.jp`。内部確認はlocalhost限定port-forwardとHostヘッダーで行う。
|
||||||
|
|
||||||
|
レジストリ `git.anya.jp` は当初IPv6のみでノードから到達できなかった。
|
||||||
|
IPv4追加後にpullが成功し、release digestを固定して起動した。
|
||||||
|
|
||||||
|
公開までの残件:
|
||||||
|
|
||||||
|
- NOCに `exhibit-anya` のService `pageswiki`、HTTP port 80、全Path、希望ホスト `pages.jsb.anya.jp` を接続先として伝え、DNS・Gateway・TLSを調整する。管理画面はログイン必須であり、展示管理者パスワードを公開しない。
|
||||||
|
- 公開HTTPSからのログイン・各ビューアの描画・操作をブラウザで確認する。現時点の確認はport-forward越しのHTTP/API検証。
|
||||||
|
- 運営GitHubの `anya/` に通常運用のConfigMap・Deployment・Service・NetworkPolicyを移管する。Secretと一度限りのbootstrap Jobは含めず、既存PVCを削除する差分も作らない。GitHubのpush権限はOmni認証とは別に確認する。
|
||||||
|
- NFS server側の永続化保証・保全方針はNOCと確認する。[PostgreSQLのNFS要件](https://www.postgresql.org/docs/17/creating-cluster.html#CREATING-CLUSTER-NFS)に従い、`fsync`は無効化しない。証明書の期限・更新と展示撤収時のSecret/PVCの扱いも決める。
|
||||||
|
|
||||||
|
以降は当初の一般手順として残す。保存と公開経路に関しては上記の実環境に合わせて読み替える。
|
||||||
|
|
||||||
|
運営のKubernetes Clusterを借りる方式Aを第一希望とし、展示用の独立したPagesWikiを1 replicaで配置する。公開名は `pages.jsb.anya.jp`。グローバルDNSに会場から到達できるローカルIPを登録し、Cloudflare DNS-01で取得した証明書をIngressへ設定する。
|
||||||
|
|
||||||
|
本書は実施手順であり、DNS登録・証明書発行・クラスタ操作はまだ実行していない。IP、Namespace、StorageClass、IngressClass、リソース上限は運営との相談後に確定する。本番データ・認証鍵・外部サービス資格情報は流用しない。
|
||||||
|
|
||||||
|
## 1 構成と役割
|
||||||
|
|
||||||
|
| 対象 | 方針 |
|
||||||
|
| --- | --- |
|
||||||
|
| 利用者の入口 | `https://pages.jsb.anya.jp/` |
|
||||||
|
| 追加Domainの例 | `https://blog.pages.jsb.anya.jp/` |
|
||||||
|
| 公開DNS | 入口のローカルIPv4をAへ登録。CloudflareはDNS only |
|
||||||
|
| TLS証明書のSAN | `pages.jsb.anya.jp` と `*.pages.jsb.anya.jp` |
|
||||||
|
| TLS終端 | 運営のIngress Controller等 |
|
||||||
|
| PagesWiki本体 | 1 replica、HTTP 3000、`/data`をPVCへ保存 |
|
||||||
|
| 初期の周辺機能 | code-server・Kroki・外部Campus等は追加せず、本体確認後に判断 |
|
||||||
|
| 証明書の取得 | 自分の管理端末でCertbotとCloudflare pluginを使用 |
|
||||||
|
| 更新 | 証明書更新とTLS Secret反映を一組で行う |
|
||||||
|
|
||||||
|
通信経路は、会場端末からIngressの443、Serviceの80、PagesWiki Podの3000、保存先PVCの順。DNSは入口の住所を知らせるだけで、ネットワーク到達性や経路を作らない。
|
||||||
|
|
||||||
|
DNS-01は公開DNSのTXTを検証するため、Webサーバーへのインターネットからの着信を必要とせず、ワイルドカードも取得できる。[Let's Encrypt DNS-01](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge)
|
||||||
|
|
||||||
|
### ローカルIPを公開DNSへ入れる場合の注意
|
||||||
|
|
||||||
|
- Aへ入れるのは、来場者用ネットワークから到達できるIngressのVIP等。Pod IP、ClusterIP、`127.0.0.1`は使用しない。Node IPを使う場合も443の受け口を運営に確認する。
|
||||||
|
- プライベートIPはインターネット全体から到達できない。会場LANやVPN等で経路がある利用者向けの公開となる。
|
||||||
|
- 公開DNS上に名前とローカルIPが掲載される。公開CAの証明書に含めた名前もCTログの対象となる。[Let's Encrypt CT](https://letsencrypt.org/docs/ct-logs/)
|
||||||
|
- DNSリバインディング対策で公開DNSからのプライベートIP応答を遮断する環境がある。会場の実利用DNSと端末で確認し、必要なら限定的な許可または運営管理のsplit DNSを相談する。防御機能全体を無効にしない。
|
||||||
|
- Cloudflareの通常のオレンジ雲proxyは使わずDNS onlyとする。private originへの接続には別の構成が必要。[Cloudflare proxy status](https://developers.cloudflare.com/dns/proxy-status/)
|
||||||
|
- 証明書の取得成功と、会場からのHTTPS到達成功は別々に検証する。
|
||||||
|
|
||||||
|
## 2 運営から受け取る情報
|
||||||
|
|
||||||
|
| 確認項目 | 必要な情報 |
|
||||||
|
| --- | --- |
|
||||||
|
| 接続 | kubeconfig、Namespace、接続可能な期間・ネットワーク |
|
||||||
|
| 権限 | Deployment、Service、PVC、ConfigMap、Secret、Ingress等の操作、ログとport-forward |
|
||||||
|
| ノード | `linux/amd64`対応。現在のリリースイメージの対象architecture |
|
||||||
|
| リソース | CPU・メモリQuota、PVC容量、ephemeral storage制限 |
|
||||||
|
| 保存 | StorageClass名、実体、SQLiteのlocking/fsyncに適するか、PVC保持・撤収時の扱い |
|
||||||
|
| 公開 | IngressまたはGateway API、Class、入口のローカルIP、会場LANから443の到達性 |
|
||||||
|
| TLS | 自分のNamespaceでTLS Secretを作れるか、終端の所有者、証明書更新の反映方法 |
|
||||||
|
| 通信 | イメージレジストリへのpull、必要な外向き通信、会場DNSでの名前解決 |
|
||||||
|
| セキュリティ | 非root UID、fsGroup、Pod Security、NetworkPolicy等の制約 |
|
||||||
|
| 検証 | 展示前に同じ制約でデプロイ・再起動・HTTPS確認できる期間 |
|
||||||
|
|
||||||
|
最初の相談値は合計CPU 2〜4 vCPU、メモリ4〜8 GiB、PVC 20 GiB程度。計測済みの必要量ではなく、展示データと連携機能の選択後に調整する。NamespaceやIngress Controller、cert-managerを自分でクラスタ全体へ新設する前提にはしない。
|
||||||
|
|
||||||
|
## 3 手元の接続設定
|
||||||
|
|
||||||
|
対応バージョンのkubectlを手元へインストールする。受領したkubeconfigはGitへ入れず、信頼できる運営から受け取ったものだけを使用する。[kubeconfig](https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod 600 "$HOME/.kube/jsb-exhibition.yaml"
|
||||||
|
export KUBECONFIG="$HOME/.kube/jsb-exhibition.yaml"
|
||||||
|
export NS='REPLACE_WITH_ASSIGNED_NAMESPACE'
|
||||||
|
|
||||||
|
kubectl config current-context
|
||||||
|
kubectl -n "$NS" get pods
|
||||||
|
kubectl -n "$NS" auth can-i create deployments.apps
|
||||||
|
kubectl -n "$NS" auth can-i create persistentvolumeclaims
|
||||||
|
kubectl -n "$NS" auth can-i create secrets
|
||||||
|
kubectl -n "$NS" auth can-i create ingresses.networking.k8s.io
|
||||||
|
```
|
||||||
|
|
||||||
|
Forbiddenが出たら運営へ相談する。別の管理者contextへ切り替えて回避しない。
|
||||||
|
|
||||||
|
## 4 CloudflareにDNSを登録する
|
||||||
|
|
||||||
|
前提として、対象の実際の権威DNS zoneを自分がCloudflareで管理できることを確認する。`jsb.anya.jp`が別のDNSへ委譲されている場合、親zoneの画面へレコードを追加しただけでは有効にならない。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dig +short NS anya.jp
|
||||||
|
dig +short SOA pages.jsb.anya.jp
|
||||||
|
dig +trace pages.jsb.anya.jp A
|
||||||
|
```
|
||||||
|
|
||||||
|
`anya.jp`がCloudflare上の対象zoneで、途中のNS委譲がない場合の入力例:
|
||||||
|
|
||||||
|
| 種別 | Name | Content | Proxy | TTL |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| A | `pages.jsb` | 運営指定のIngress入口IPv4 | DNS only | 300秒を目安に選択 |
|
||||||
|
| A | `*.pages.jsb` | 同じIngress入口IPv4 | DNS only | 同上 |
|
||||||
|
|
||||||
|
最初は本体のAだけでもよい。追加Domainを展示する場合にワイルドカードAを使う。不要なAAAAや旧A、競合するCNAMEがあれば影響を確認する。既存の別サービスのレコードを無断で消さない。
|
||||||
|
|
||||||
|
証明書のワイルドカードとDNSのワイルドカードは別設定。`*.pages.jsb.anya.jp`の証明書は `blog.pages.jsb.anya.jp`を含むが、`pages.jsb.anya.jp`自身や `a.b.pages.jsb.anya.jp`はカバーしない。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 公開DNSの応答を確認。これは会場の実利用DNSでの確認とは別。
|
||||||
|
dig @1.1.1.1 pages.jsb.anya.jp A +short
|
||||||
|
dig @1.1.1.1 blog.pages.jsb.anya.jp A +short
|
||||||
|
dig @1.1.1.1 pages.jsb.anya.jp AAAA +short
|
||||||
|
|
||||||
|
# CA制限が設定されている場合は親からの継承も含めて確認する
|
||||||
|
dig pages.jsb.anya.jp CAA
|
||||||
|
dig jsb.anya.jp CAA
|
||||||
|
dig anya.jp CAA
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5 自分の管理端末で証明書を取得する
|
||||||
|
|
||||||
|
共有クラスタへCloudflareのzone更新権限を置かないことを基本とする。運営へ渡すのは展示用の証明書・秘密鍵を格納したTLS Secretであり、Cloudflare API Tokenや本番サービスの秘密は渡さない。ただし運営のクラスタ管理者はTLS Secretへアクセス可能なため、鍵の管理責任は事前に合意する。
|
||||||
|
|
||||||
|
### 5.1 CertbotとCloudflare plugin
|
||||||
|
|
||||||
|
以下は自分が管理するUbuntu/Debianホストの例。運営のノードへSSHして実行しない。他のOSでは公式の導入手順を使い、Snap・pip・ディストリビューションpackageのpluginを混在させない。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install certbot python3-certbot-dns-cloudflare
|
||||||
|
sudo certbot plugins
|
||||||
|
```
|
||||||
|
|
||||||
|
`dns-cloudflare`が利用可能であることを確認する。[Certbot導入](https://eff-certbot.readthedocs.io/en/stable/install.html)、[Cloudflare plugin](https://certbot-dns-cloudflare.readthedocs.io/en/stable/)
|
||||||
|
|
||||||
|
### 5.2 専用API Token
|
||||||
|
|
||||||
|
CloudflareでDNS更新用のAPI Tokenを作る。Global API Keyは使わない。対象は実際に権威を持つ特定のzoneだけに限定し、全zoneを許可しない。DNS編集と、利用するclientがzone検出に必要とするzone読取を確認する。
|
||||||
|
|
||||||
|
Cloudflare Tokenの典型的な権限は `Zone / DNS / Edit` と `Zone / Zone / Read`。zoneを `anya.jp`へ限定しても、このTokenは `pages.jsb`のレコードだけに限定された権限とは限らない。より狭い委譲が必要なら認証専用zoneへの委譲を別途設計する。cert-managerの設定例をそのままCertbotへ流用しない。[Cloudflare認証設定](https://cert-manager.io/docs/configuration/acme/dns01/cloudflare/)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
install -d -m 700 "$HOME/.config/pageswiki-exhibition"
|
||||||
|
```
|
||||||
|
|
||||||
|
エディタで `$HOME/.config/pageswiki-exhibition/cloudflare.ini` を作成する:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
dns_cloudflare_api_token = REPLACE_WITH_DEDICATED_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod 600 "$HOME/.config/pageswiki-exhibition/cloudflare.ini"
|
||||||
|
export ACME_EMAIL='REPLACE_WITH_YOUR_EMAIL'
|
||||||
|
```
|
||||||
|
|
||||||
|
Tokenをコマンド引数、Git、チャット、一般ログへ書かない。作業端末からCloudflare API・ACMEへのHTTPSと、必要な公開DNS問い合わせが通ることを確認する。
|
||||||
|
|
||||||
|
### 5.3 stagingで確認する
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo certbot certonly \
|
||||||
|
--test-cert \
|
||||||
|
--non-interactive --agree-tos \
|
||||||
|
--email "$ACME_EMAIL" \
|
||||||
|
--cert-name pages-jsb-staging \
|
||||||
|
--dns-cloudflare \
|
||||||
|
--dns-cloudflare-credentials "$HOME/.config/pageswiki-exhibition/cloudflare.ini" \
|
||||||
|
--dns-cloudflare-propagation-seconds 60 \
|
||||||
|
-d 'pages.jsb.anya.jp' \
|
||||||
|
-d '*.pages.jsb.anya.jp'
|
||||||
|
```
|
||||||
|
|
||||||
|
DNS-01のTXT名は `_acme-challenge.pages.jsb.anya.jp`。親名とワイルドカードの認証で、同じ名前に複数TXT値を使う場合がある。clientが作った値を手で上書き・削除しない。propagation待ちは環境に応じて調整する。
|
||||||
|
|
||||||
|
staging証明書はブラウザに信頼されないため、本番用TLS Secretには使わない。
|
||||||
|
|
||||||
|
### 5.4 本番CAで発行する
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo certbot certonly \
|
||||||
|
--non-interactive --agree-tos \
|
||||||
|
--email "$ACME_EMAIL" \
|
||||||
|
--cert-name pages-jsb \
|
||||||
|
--dns-cloudflare \
|
||||||
|
--dns-cloudflare-credentials "$HOME/.config/pageswiki-exhibition/cloudflare.ini" \
|
||||||
|
--dns-cloudflare-propagation-seconds 60 \
|
||||||
|
-d 'pages.jsb.anya.jp' \
|
||||||
|
-d '*.pages.jsb.anya.jp'
|
||||||
|
|
||||||
|
sudo openssl x509 \
|
||||||
|
-in /etc/letsencrypt/live/pages-jsb/fullchain.pem \
|
||||||
|
-noout -subject -issuer -dates -ext subjectAltName
|
||||||
|
```
|
||||||
|
|
||||||
|
CAが発行した実際の有効期限を確認する。固定の日数を前提に展示予定を組まない。失敗時にforce-renewalを連打せず、DNS・CAA・API権限・通信を確認する。
|
||||||
|
|
||||||
|
## 6 PagesWikiを先に内部確認する
|
||||||
|
|
||||||
|
Namespace内にPVC、1 replicaのDeployment、ClusterIP Serviceを配置する。[マニフェストひな形](../../deploy/kubernetes/exhibition/pageswiki.yaml.example)を作業領域の `pageswiki.yaml` にコピーし、`REPLACE_WITH_STORAGE_CLASS`、使用するreleaseタグ、運営指定のUID・Quota等を確認してから適用する。
|
||||||
|
|
||||||
|
| 設定 | 方針 |
|
||||||
|
| --- | --- |
|
||||||
|
| image | 検証済みのreleaseタグまたはdigestで固定。latestを使わない |
|
||||||
|
| 本体 | `replicas: 1`、通常更新は `strategy.type: Recreate` |
|
||||||
|
| port | `3000`。DockerfileのEXPOSEだけを待受の根拠にしない |
|
||||||
|
| env | `PAGESWIKI_DATA_DIR=/data` |
|
||||||
|
| 保存 | `/data`をPVC、必要な一時領域は別途確保 |
|
||||||
|
| health | `/health`にstartup/readiness probe。起動処理中の再起動連発を避ける |
|
||||||
|
| 権限 | 運営の非root・fsGroup等の方針で新規volumeの書き込みを検証する |
|
||||||
|
|
||||||
|
SQLite向け保存のlocking/fsyncを確認する。`ReadWriteOnce`自体は1 Podだけの排他保証ではない。対応CSIならReadWriteOncePodも相談し、いずれも手動の二重writerを作らない。[Volume access modes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl -n "$NS" apply --dry-run=server -f pageswiki.yaml
|
||||||
|
kubectl -n "$NS" apply -f pageswiki.yaml
|
||||||
|
kubectl -n "$NS" rollout status deployment/pageswiki --timeout=10m
|
||||||
|
kubectl -n "$NS" get pods,pvc,svc
|
||||||
|
kubectl -n "$NS" port-forward service/pageswiki 8080:80
|
||||||
|
```
|
||||||
|
|
||||||
|
別ターミナルで `curl http://localhost:8080/health`。ブラウザで `http://localhost:8080/_/auth/login` を開き、初期管理者を作成する。初回画面要求時に生成されるbootstrap tokenは自分だけでログを確認し、貼り付け・共有しない。アカウント作成後はenforcing等の認可設定を確認し、外部公開前にログイン・匿名拒否を試す。
|
||||||
|
|
||||||
|
PagesWikiのCampus FQDNを `pages.jsb.anya.jp`、本体Domainのホスト名を空として、Campus FQDN自身を本体へ対応させる。既存の本番Campusへ参加させない。Wiki名等も展示用にする。FQDN変更後にlocalhostでDomainを解決できなくなる場合は、公開経路または適切なHostを用いて検証する。`PAGESWIKI_INSTANCE_FQDN`はCampus/Domain設定の代わりにはならない。
|
||||||
|
|
||||||
|
## 7 TLS Secretを作成する
|
||||||
|
|
||||||
|
証明書・秘密鍵を持つ管理端末にkubectlと運営用kubeconfigがある場合の例。証明書ファイルだけを保護した一時領域へコピーし、kubectl自体は通常の利用者として実行する。kubeconfigのcontext、Namespaceを必ず確認する。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl config current-context
|
||||||
|
|
||||||
|
# bashのサブシェル内で実行し、終了時に一時コピーを消す
|
||||||
|
(
|
||||||
|
set -euo pipefail
|
||||||
|
TLS_TMP="$(mktemp -d)"
|
||||||
|
chmod 700 "$TLS_TMP"
|
||||||
|
trap 'rm -f "$TLS_TMP/tls.crt" "$TLS_TMP/tls.key"; rmdir "$TLS_TMP"' EXIT
|
||||||
|
sudo install -m 600 -o "$(id -u)" -g "$(id -g)" \
|
||||||
|
/etc/letsencrypt/live/pages-jsb/fullchain.pem "$TLS_TMP/tls.crt"
|
||||||
|
sudo install -m 600 -o "$(id -u)" -g "$(id -g)" \
|
||||||
|
/etc/letsencrypt/live/pages-jsb/privkey.pem "$TLS_TMP/tls.key"
|
||||||
|
kubectl -n "$NS" create secret tls pages-jsb-tls \
|
||||||
|
--cert="$TLS_TMP/tls.crt" --key="$TLS_TMP/tls.key" \
|
||||||
|
--dry-run=client -o yaml | \
|
||||||
|
kubectl -n "$NS" apply --server-side --field-manager=pageswiki-exhibition-tls -f -
|
||||||
|
)
|
||||||
|
|
||||||
|
kubectl -n "$NS" describe secret pages-jsb-tls
|
||||||
|
```
|
||||||
|
|
||||||
|
shellでpipelineを使う作業は `set -o pipefail` を有効にする。上記をログ収集用の `tee` へ流さない。server-side applyは秘密値をlast-applied annotationへ重複保存しないために使う。競合時は所有者を確認し、`--force-conflicts`で他の管理主体を奪わない。運営のRBAC・admissionでこの方法が許可されない場合は、運営指定の秘密投入手順へ切り替える。
|
||||||
|
|
||||||
|
SecretとIngressは同じNamespaceに置く。証明書の公開部分と秘密鍵は用途が異なり、TLS Secret全体のYAMLやbase64値を公開しない。[kubectl create secret tls](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_create/kubectl_create_secret_tls/)
|
||||||
|
|
||||||
|
## 8 Ingressを作成する
|
||||||
|
|
||||||
|
以下を `pageswiki-ingress.yaml` として保存する。`REPLACE_WITH_INGRESS_CLASS`を実際の値へ変更する。運営がIngressを所有する場合、この設定内容を渡して運営に反映を依頼する。Gateway APIの場合は同等のHTTPRouteとTLS設定へ読み替える。
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: Ingress
|
||||||
|
metadata:
|
||||||
|
name: pageswiki
|
||||||
|
spec:
|
||||||
|
ingressClassName: REPLACE_WITH_INGRESS_CLASS
|
||||||
|
tls:
|
||||||
|
- hosts:
|
||||||
|
- pages.jsb.anya.jp
|
||||||
|
- "*.pages.jsb.anya.jp"
|
||||||
|
secretName: pages-jsb-tls
|
||||||
|
rules:
|
||||||
|
- host: pages.jsb.anya.jp
|
||||||
|
http:
|
||||||
|
paths:
|
||||||
|
- path: /
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
service:
|
||||||
|
name: pageswiki
|
||||||
|
port:
|
||||||
|
number: 80
|
||||||
|
- host: "*.pages.jsb.anya.jp"
|
||||||
|
http:
|
||||||
|
paths:
|
||||||
|
- path: /
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
service:
|
||||||
|
name: pageswiki
|
||||||
|
port:
|
||||||
|
number: 80
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl -n "$NS" apply --dry-run=server -f pageswiki-ingress.yaml
|
||||||
|
kubectl -n "$NS" apply -f pageswiki-ingress.yaml
|
||||||
|
kubectl -n "$NS" describe ingress pageswiki
|
||||||
|
```
|
||||||
|
|
||||||
|
ワイルドカードIngressがあっても、未知HostをPagesWikiの本体Domainへフォールバックさせない。`blog`等を使う場合はPagesWiki側でもDomainを作成し、ホスト名を登録する。設定しない子Domainが404等になることは正常な拒否である。
|
||||||
|
|
||||||
|
Ingressでは元のHostを保ち、TLS終端後の `X-Forwarded-Proto: https` 等の扱いを確認する。転送ヘッダは信頼したIngressで上書きし、利用者からの偽装値をそのまま通さない。HTTPS redirect、アップロードサイズ、長い要求、将来のadapter接続はController固有の設定として相談する。
|
||||||
|
|
||||||
|
## 9 会場から検証する
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 実際に利用者が使うDNSの答えと、経路を確認する
|
||||||
|
dig pages.jsb.anya.jp A +short
|
||||||
|
curl -I https://pages.jsb.anya.jp/
|
||||||
|
|
||||||
|
# DNS反映前でも、正しいSNIとHostを維持して入口だけ指定できる
|
||||||
|
export INGRESS_IP='REPLACE_WITH_ASSIGNED_INGRESS_IP'
|
||||||
|
curl --resolve "pages.jsb.anya.jp:443:$INGRESS_IP" \
|
||||||
|
-I https://pages.jsb.anya.jp/
|
||||||
|
|
||||||
|
# 信頼チェーンとホスト名を検証する。検証失敗を-kで隠さない
|
||||||
|
openssl s_client \
|
||||||
|
-connect "$INGRESS_IP:443" \
|
||||||
|
-servername pages.jsb.anya.jp \
|
||||||
|
-verify_hostname pages.jsb.anya.jp \
|
||||||
|
-verify_return_error </dev/null
|
||||||
|
```
|
||||||
|
|
||||||
|
合格条件:展示LANの端末で名前解決とTCP443が通る、SAN・有効期限・信頼チェーンが正しい、ログインとログアウトが動く、非公開文書へ匿名アクセスできない、編集保存とPod再起動後の永続化が動く、必要な追加Domainだけが正しい。会場外から接続不可であることはプライベートIP構成では想定内。
|
||||||
|
|
||||||
|
## 10 更新と撤収
|
||||||
|
|
||||||
|
証明書更新後も、クラスタのTLS Secretは自動的には更新されない。まずstagingで試した後、必要な時期にCertbotの `renew --cert-name pages-jsb` を実施し、手順7で同じSecretへ反映する。Ingress ControllerがSecret更新を取り込んだことを実接続で確認する。自動更新するなら、更新とSecret反映の両方を自分の管理ホストで監視付きに運用する。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo certbot renew --cert-name pages-jsb --dry-run
|
||||||
|
sudo certbot renew --cert-name pages-jsb
|
||||||
|
```
|
||||||
|
|
||||||
|
cert-managerを使う場合は代わりに運営の許可を得て既設controllerを利用する。Namespace内のIssuer、Cloudflare Token Secret、Certificateを同じNamespaceに置き、CertificateのdnsNamesを親名とワイルドカード、secretNameを `pages-jsb-tls` とする。Secretへ手動投入する方式とcert-managerに同じSecretを同時管理させない。ClusterIssuer作成権限やcert-manager新設を要求しない。[Issuerのscope](https://cert-manager.io/docs/concepts/issuer/)、[Certificate](https://cert-manager.io/docs/usage/certificate/)
|
||||||
|
|
||||||
|
ただしAPI Tokenを共有クラスタへ置く権限・影響、Cloudflare/ACMEへの外向き通信、DNS self-checkを事前確認する。外部で発行してTLSだけ持ち込む方式なら、これらをクラスタへ追加する必要はない。
|
||||||
|
|
||||||
|
撤収時は、展示データを整合した手段で保全し、公開経路停止、展示用のAレコード整理、TLS鍵・専用Token・kubeconfigの保持/失効、PVCの保持/削除を運営と合意する。NamespaceやPVCの削除を再起動の代わりに使わない。
|
||||||
|
|
||||||
|
## 参考資料
|
||||||
|
|
||||||
|
- [certbot-dns-cloudflare](https://certbot-dns-cloudflare.readthedocs.io/en/stable/)
|
||||||
|
- [Let's Encryptの認証方式](https://letsencrypt.org/docs/challenge-types/)
|
||||||
|
- [Cloudflare DNS onlyとproxy](https://developers.cloudflare.com/dns/proxy-status/)
|
||||||
|
- [Kubernetes Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/)
|
||||||
|
- [単一インスタンスの配置例](https://kubernetes.io/docs/tasks/run-application/run-single-instance-stateful-application/)
|
||||||
|
- [PagesWikiの運用・保全設計](../design/ja/operations.md)
|
||||||
|
|
||||||
|
公式資料確認日:2026-11-12。記載例は実クラスタへ適用していない。運営指定のClass、証明書終端方式、UID、Quotaが確定してからマニフェストを検証する。
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# 展示環境についてのNOCへの返信案
|
||||||
|
|
||||||
|
> 初期相談時の草案を保存したもの。実際の展示ではPostgreSQLとNOC管理の公開経路を利用し、
|
||||||
|
> 最終指定URLは `https://pages.anya.jisaba.sh/` となった。以下を現在の依頼文として再送しない。
|
||||||
|
> 配置の経緯は [展示運用記録](exhibition-kubernetes-dns-tls.md) を参照。
|
||||||
|
|
||||||
|
ぼいどさん
|
||||||
|
|
||||||
|
ご連絡ありがとうございます。
|
||||||
|
PagesWikiの展示について、Aの運営側で用意されているKubernetes Clusterを利用させていただければと思っています。
|
||||||
|
|
||||||
|
こちらでコンテナイメージとデプロイ用のマニフェストを用意し、割り当ていただいたNamespace内へ配置する想定です。クラスタ全体の管理権限や特権コンテナは必要としない構成で考えています。Kubernetesの利用経験がまだ少ないため、事前に動作確認できる期間をいただけると助かります。
|
||||||
|
|
||||||
|
アプリは現在SQLiteとファイル保存を使う単一writer構成のため、本体は1 replicaとし、永続ボリュームを利用したいです。リソースはひとまず合計CPU 2〜4 vCPU、メモリ4〜8 GiB、永続ストレージ20 GiB程度を目安に相談させてください。展示する機能を絞って検証し、必要量を調整する予定です。
|
||||||
|
|
||||||
|
アクセス先は、こちらで管理する `pages.jsb.anya.jp` を使用したいと考えています。グローバルDNSに、会場ネットワークから到達できるIngress等のローカルIPをAレコードとして登録する想定です。追加のドメイン展示用に `*.pages.jsb.anya.jp` も同じ入口へ向けられると助かります。DNSはCloudflareのDNS onlyとし、Cloudflare経由の通信中継は利用しません。
|
||||||
|
|
||||||
|
証明書はこちらでCloudflareのDNS-01認証を使い、`pages.jsb.anya.jp` と `*.pages.jsb.anya.jp` を含むものを取得する予定です。DNS操作用のAPI Tokenは共有クラスタへ置かず、証明書と秘密鍵だけをTLS Secretとして持ち込み、Ingress側でTLS終端する形を第一案としています。
|
||||||
|
|
||||||
|
以下について教えていただけますでしょうか。
|
||||||
|
|
||||||
|
- Namespaceの割り当てと接続方法、利用できるリソース・権限の範囲
|
||||||
|
- linux/amd64のイメージが動くことと、外部レジストリ `git.anya.jp` からのpull可否
|
||||||
|
- 利用可能なStorageClassと、そのストレージがSQLiteの保存先に適しているか
|
||||||
|
- Ingress等の利用方法と、DNSへ登録できるローカルIP、会場端末からの到達性
|
||||||
|
- 持ち込み証明書によるTLS終端の可否と、Secretの投入・更新方法
|
||||||
|
- 会場DNSで、公開DNSに登録したプライベートIPがリバインディング対策等で遮断されないか
|
||||||
|
- Podの実行権限・ネットワーク等の制約と、事前検証できる期間
|
||||||
|
|
||||||
|
もしストレージや公開経路などの制約でAが難しい場合は、BのVM提供も含めて相談させていただければと思います。
|
||||||
|
|
||||||
|
よろしくお願いいたします。
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
# Pages Machine Learning:内部サービスと運用
|
||||||
|
|
||||||
|
2026-11-17。状態:**開発用の最小サービスとGoクライアントを実装、Pagesの保存処理には未接続**。
|
||||||
|
本番へ自動起動・外部送信・学習を追加しない。予算用migrationは明示適用のみで、本番未適用。MCPも別途未実装。
|
||||||
|
|
||||||
|
2026-11-28:ML-02の設定契約・永続化を追加。`internal/machinelearning/policy.go`で
|
||||||
|
許可prefix/除外prefix、モデル・scope、外部送信同意、batch byte上限を検証する。
|
||||||
|
`internal/store/machine_learning.go`は既存のDomain別configテーブルに
|
||||||
|
`machine_learning_policy_v1`として保存する。設定がなければ無効、壊れていればエラーで拒否。
|
||||||
|
新規テーブル/migrationは追加しない。同日、管理API・設定UIへ接続。イベントworkerにはまだ未接続。
|
||||||
|
|
||||||
|
設定保存は前回のgenerationを条件にした原子的な更新。毎回新しいgenerationを発行し、
|
||||||
|
無効化後に再有効化しても古い処理要求を再利用できない。`Policy.Prepare`は読み直した設定から
|
||||||
|
要求のモデル・scope・外部送信可否を構築する。prefixは文字列前方一致ではなくPath境界で照合し、
|
||||||
|
除外を優先する。入力はデコード済みの論理Pathとし、URL/曖昧なpercent表記/dot-segmentを拒否する。
|
||||||
|
これは文書ACLの代替ではない。管理者認可・文書権限・学習範囲・結果保存時の再検査は呼出側の責務。
|
||||||
|
保存関数は内部用とし、外部からの操作は下記の管理者認可付きAPIを経由する。
|
||||||
|
|
||||||
|
設定画面:`/-/sys/config?panel=machine-learning`(運用 → Machine Learning)。
|
||||||
|
日本語/英語、既存テーマの表組み・トグルで表示する。パネルを開いた時だけ読み込み、
|
||||||
|
保存はパネルを移動しない。競合時は入力を保持し、確認付きの再読込を用意する。
|
||||||
|
|
||||||
|
管理API:`GET /_/api/v1/ml/settings`、`PUT /_/api/v1/ml/settings`。
|
||||||
|
active状態のdomain_adminまたは当該campus管理者のみ。DomainはHostから決定し、
|
||||||
|
要求本文でDomainを指定できない。更新はJSON・同一Origin検査・64KiB上限・未知field拒否。
|
||||||
|
PUT本文は`{base_generation, policy}`で、policy内のgeneration指定は拒否する。
|
||||||
|
競合409、不正設定422、読書き不可503。応答はprivate/no-store、秘密鍵や接続トークンは含めない。
|
||||||
|
設定を保存しても学習/外部送信/ジョブ投入は起きない。
|
||||||
|
|
||||||
|
batch byte上限は一回分の送信量制限で、日次token予算・課金上限ではない。
|
||||||
|
永続的な予算予約とタイムアウト時の扱いは次の追記のとおり実装。worker接続は後続ML-03で実装する。
|
||||||
|
|
||||||
|
2026-11-28追記:日次予約の保存層を実装。設定`daily_input_bytes`はDomain全体・UTC日付単位の
|
||||||
|
入力UTF-8 byte上限で、0(既存設定の既定値を含む)は実行禁止。通貨/正確なtoken予算ではない。
|
||||||
|
モデル・scope・設定世代が変わっても同日の枠は共有する。今回のスライスでworkerへの接続は行わない。
|
||||||
|
|
||||||
|
`EnsureMLBudgetSchema`が専用migration `machine-learning-budget` v1を明示的に適用する。
|
||||||
|
通常起動/設定保存ではまだ呼び出さないため、本番DBは今回変更しない。専用テーブルは
|
||||||
|
`ml_daily_budget`(Domain+UTC日)と`ml_budget_receipts`(Domain+要求UUID)。
|
||||||
|
予約処理は設定行のロック下で現行世代・Path・同意を再検査し、上限確認とreceipt挿入を同一transactionで行う。
|
||||||
|
MLへのHTTP処理はtransaction外で行う必要がある。重複要求IDは成功応答として返さず、再送禁止エラーにする。
|
||||||
|
|
||||||
|
状態はreserved→completed/unknownの一回遷移。成功時のactual_tokensは参考値として保存する。
|
||||||
|
失敗・timeout・プロセス停止でも予約byteを返却せず、当日再送による重複課金の余地を減らす。
|
||||||
|
日付が変わっても同じ要求IDは再利用不可。receiptに本文や秘密情報は保存しない。
|
||||||
|
保持期間・日次集約の削除・receiptのtombstone化は未実装。receiptを削除すると再送防止を失うため、
|
||||||
|
worker接続前に保持方針を確定し、安易な時限削除を行わない。
|
||||||
|
|
||||||
|
## 境界
|
||||||
|
|
||||||
|
| Pages本体 | Pages Machine Learning |
|
||||||
|
| --- | --- |
|
||||||
|
| Domain/利用者/対象prefix/公開範囲の認可 | 認証されたPagesサービスの入力だけを計算 |
|
||||||
|
| HTML抽出、chunk、Revision・権限世代の管理 | OpenAI EmbeddingsまたはDoc2Vecのベクトル化 |
|
||||||
|
| 永続イベントキュー、取消・再試行・予算 | 実行中処理のみ。永続キューや自動retryなし |
|
||||||
|
| ベクトル保存、候補UI、承認、City適用 | 自前生成したモデルの読取。文書URL取得なし |
|
||||||
|
|
||||||
|
MLにはDB資格情報も文書ストレージも渡さない。共有トークンはサービス間専用で、
|
||||||
|
ユーザー認証やDomain認可を代替しない。ブラウザ/pages-cli/MCPからの直接接続は禁止。
|
||||||
|
本番Pagesから呼ぶ前に、対象選定・外部送信許可・予算をサーバー側で検査する。
|
||||||
|
文書が読める利用者だからといって全Domainの学習・送信を許可しない。
|
||||||
|
|
||||||
|
## 内部API v1
|
||||||
|
|
||||||
|
- `GET /healthz`:無認証のlivenessのみ。モデルが配置済み/推論可能とは保証しない。
|
||||||
|
- `POST /v1/embeddings`:`Authorization: Bearer <専用トークン>`、JSON。本文上限128KiB。
|
||||||
|
- それ以外は認証後404。モデルupload/train/任意URLアクセスのHTTP APIはない。
|
||||||
|
|
||||||
|
要求例(すべて合成ID):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"protocol": "1",
|
||||||
|
"domain_uuid": "11111111-1111-4111-8111-111111111111",
|
||||||
|
"scope_uuid": "22222222-2222-4222-8222-222222222222",
|
||||||
|
"provider": "doc2vec",
|
||||||
|
"model": "<学習出力のmodel_sha256:64桁hex>",
|
||||||
|
"dimensions": 128,
|
||||||
|
"allow_external": false,
|
||||||
|
"inputs": [{"id": "page-revision:chunk0", "text": "抽出済みの本文"}]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
1要求1〜16chunk、各6000 UTF-8 bytes、次元1〜1536。`id`は要求内一意。
|
||||||
|
OpenAI初版は`text-embedding-3-small`のみ。入力byte上限をtoken上限より小さく抑えるが、
|
||||||
|
適切な節分割・ドメイン予算はPages側の次段階で実装する。元の長文を黙って切り捨てない。
|
||||||
|
|
||||||
|
応答はprotocol/Domain/scope/provider/model/model_revision/dimensions/tokenizer、
|
||||||
|
`outputs[{id,input_sha256,vector}]`、`usage.total_tokens`。
|
||||||
|
Goクライアントは入力順・ID・SHA256・次元・モデル・有限かつ非ゼロのvectorを検査する。
|
||||||
|
Doc2Vecのmodel_revisionはモデルファイルSHA256。OpenAIは返されたモデル名であり、
|
||||||
|
提供元の重みを固定したsnapshot IDではない。運用側の索引世代を別に持たせる必要がある。
|
||||||
|
|
||||||
|
主な失敗:400入力、401サービス認証、403外部送信OFF、404モデルなし、409モデル不整合、
|
||||||
|
413サイズ、415形式、422既知語なし、429実行中/provider制限、502provider失敗。
|
||||||
|
エラーに入力本文・API鍵・上流response bodyを含めない。Go側もstatus以外の上流本文を返さない。
|
||||||
|
timeoutで請求や実行の有無は確定しない。自動retry/別providerへのfallbackは行わない。
|
||||||
|
|
||||||
|
## Doc2Vecモデル
|
||||||
|
|
||||||
|
Gensim PV-DBOWを固定し、初版はNFKC+casefold+CJK文字bigramの決定的な前処理。
|
||||||
|
これは軽量な比較用baselineであり、高品質な日本語形態素解析や分類精度を保証しない。
|
||||||
|
語彙が全く一致しない入力はランダムな候補を返さず422。学習workers=1、seed=0。
|
||||||
|
推論も入力hashでseedを固定する。同一実行環境での安定性を試験し、異なる依存版/CPUの
|
||||||
|
bit単位一致までは保証しない。前処理や依存版を変える際はモデル・索引世代を更新する。
|
||||||
|
|
||||||
|
保管先:`/models/{domain_uuid}/{scope_uuid}/{model_sha256}/`。
|
||||||
|
scopeは一つの学習許可範囲を表すID。Domain内でも非公開データと公開データを無条件で混ぜない。
|
||||||
|
`manifest.json`と`model.bin`を生成し、APIからはread-only。
|
||||||
|
SHA256は破損検査であり、モデルの安全性を証明する署名ではない。
|
||||||
|
Gensimモデルはpickleを利用するため、**自前で学習した信頼済みモデル以外は配置禁止**。
|
||||||
|
モデルを一般のWikiアップロードやassetsディレクトリから読み込まない。
|
||||||
|
|
||||||
|
学習は管理者のオフラインコマンドのみ。入力は許可済みJSONL(各行`{"text":"…"}`)、
|
||||||
|
最大1万文書/16MiB、文書あたり6000bytes。モデルは別世代のディレクトリへ作り、既存世代を上書きしない。
|
||||||
|
2文書以上で学習できることと分類品質が十分であることは別。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONHASHSEED=0 OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 \
|
||||||
|
python train.py corpus.jsonl --model-dir /models \
|
||||||
|
--domain DOMAIN_UUID --scope SCOPE_UUID --dimensions 128
|
||||||
|
```
|
||||||
|
|
||||||
|
削除/権限変更時はPagesが当該scopeの利用を即座に停止し、再学習後に世代を切り替える設計。
|
||||||
|
モデルファイルだけでなくmanifestを除去すれば、読み込み済みでも次回要求を拒否する。
|
||||||
|
この失効処理のPages接続は未実装。モデルは1世代だけメモリ保持し、別scope要求時に入れ替える。
|
||||||
|
大きな複数モデルを使う場合はインスタンス分離を検討する。
|
||||||
|
|
||||||
|
## 起動と制限
|
||||||
|
|
||||||
|
`services/machine-learning/Dockerfile`、任意overlay `docker-compose.ml.yml` を用意。
|
||||||
|
既存の通常Composeだけでは起動しない。イメージの公開/registry pushはまだ行わない。
|
||||||
|
|
||||||
|
1. 32〜256文字のURL-safeランダムトークンをファイルに保存する。コマンド履歴へ直接入れない。
|
||||||
|
2. `PAGES_ML_TOKEN_PATH`と`PAGES_ML_MODELS_PATH`にホストの絶対パスを指定する。
|
||||||
|
3. コンテナUID/GID `65532:65532` が読める権限を設定する。他ユーザー全員に公開しない。
|
||||||
|
学習出力は作成ユーザー専用ディレクトリなので、別UIDで生成したモデルは専用グループ/所有権を調整する。
|
||||||
|
4. 開発環境で次を実行する(基底Composeの既存必須変数も必要)。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose -f docker-compose.yml -f docker-compose.ml.yml \
|
||||||
|
up -d --build machine-learning
|
||||||
|
```
|
||||||
|
|
||||||
|
ホストport非公開、専用internal bridge `/27`、read-only root、非root、capability削除、
|
||||||
|
1CPU/1GiB/64PID、BLAS 1thread。既存ネットワークと競合すれば`PAGES_ML_FRONT_SUBNET`を変更する。
|
||||||
|
Gunicorn 1worker・2threads、推論は全provider共通で同時1件。混雑は429+Retry-Afterを返す。
|
||||||
|
別プロセス/replicaは別の同時枠なので、将来Pages側でも総同時数・予算を制限する。
|
||||||
|
in-flight要求の厳密な取消は未実装。Goのcontext取消はクライアント待機を止めるが、
|
||||||
|
MLで開始済みの計算・外部請求を取り消すものではない。
|
||||||
|
|
||||||
|
OpenAIは`PAGES_ML_ALLOW_OPENAI=true`、`PAGES_ML_OPENAI_KEY_FILE`への秘密mount、
|
||||||
|
要求内`allow_external:true`の全条件が必要。既定overlayはネットワークも外向き接続を許さない。
|
||||||
|
利用時は管理者がegress経路を別途追加・制限し、固定先`https://api.openai.com/v1/embeddings`を許可する。
|
||||||
|
任意base URL・TLS検証無効・HTTP redirect追従は提供しない。
|
||||||
|
Pages→MLのHTTPは同一の隔離ネットワーク限定。別ホストならHTTPS+ネットワーク認可を設ける。
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
Python 3.12とrequirements.txtを入れた仮想環境で:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONHASHSEED=0 OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 \
|
||||||
|
python -m unittest discover -s services/machine-learning -v
|
||||||
|
go test -race ./internal/machinelearning
|
||||||
|
PYTHONHASHSEED=0 OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 \
|
||||||
|
python services/machine-learning/smoke_test.py
|
||||||
|
```
|
||||||
|
|
||||||
|
smokeは合成文書の学習→一時Gunicorn→Goクライアントまで実行し、終了時に一時データとプロセスを破棄する。
|
||||||
|
実データを使わず、OpenAIはmock契約試験のみ。Doc2Vecの分類品質評価はまだ行っていない。
|
||||||
|
|
||||||
|
## 配布前ゲート
|
||||||
|
|
||||||
|
依存はrequirements.txtで固定。Gensim 4.4.0(LGPL-2.1)、NumPy/SciPy(BSD系、wheel同梱の
|
||||||
|
BLAS等に個別条件)、Gunicorn(MIT)、Python/Debian基底を含むため、イメージ公開前に
|
||||||
|
実際のwheel/基底imageのlicense・notice・対応sourceの提供条件、SBOMと脆弱性検査を整理する。
|
||||||
|
モデル・コーパスはイメージに含めない。Docker contextも許可したソースファイルだけに限定。
|
||||||
|
ライセンス記載だけで再配布条件を満たしたとは扱わない。
|
||||||
|
|
||||||
|
## 次の実装単位
|
||||||
|
|
||||||
|
2026-11-28:ML設定・予算についてSQLite/PostgreSQL 17/MySQL 8.4の実DB共通試験を実施し、
|
||||||
|
3backendとも成功。MySQLはMLだけの限定facadeによるpilotで、Pages本体の起動には未対応。
|
||||||
|
[DB移植計画・実装境界](../design/ja/database-portability.md)を参照。
|
||||||
|
PostgreSQL/MySQLの予約ロックはSELECT FOR UPDATE+READ COMMITTEDへ変更し、
|
||||||
|
同じ値のUPDATEのRowsAffectedに依存しない。MySQL ML schemaはjournal付きの明示migrationへ移行済み。
|
||||||
|
本番適用とPages全体のMySQL migrationは未実施。
|
||||||
|
|
||||||
|
## MySQLのML schema管理
|
||||||
|
|
||||||
|
接続先は専用の空DBを用意し、秘密管理経由で`PAGESWIKI_MYSQL_DSN`環境変数を設定する。
|
||||||
|
DSNは`USER:PASS@tcp(HOST:3306)/DATABASE?tls=true`形式。実際の秘密を履歴や資料に記載しない。
|
||||||
|
このコマンドはML専用であり、実行してもPages全体がMySQLで起動できるようにはならない。
|
||||||
|
既存PagesのDB/他サービスのDBへ試しに適用しない。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pageswiki mysql-ml-schema status
|
||||||
|
pageswiki mysql-ml-schema check
|
||||||
|
pageswiki mysql-ml-schema apply --timeout 2m
|
||||||
|
pageswiki mysql-ml-schema check
|
||||||
|
```
|
||||||
|
|
||||||
|
- `status`:適用数・未適用数・dirty・再開位置をJSONで表示。schema/台帳を作らない。
|
||||||
|
- `check`:同じ検査に加えて、未適用またはdirtyなら非0終了。デプロイ前ゲート用。
|
||||||
|
- `apply`:通常の適用。途中失敗している場合は拒否。既存tableを無断で移行履歴へ取り込まない。
|
||||||
|
- `resume`:原因を調査・修復した後の明示再開。成功済み操作は事後条件で確認し、
|
||||||
|
未完了操作は再実行安全と宣言されたものだけ再試行する。自動rollbackではない。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pageswiki mysql-ml-schema resume --timeout 2m
|
||||||
|
pageswiki mysql-ml-schema check
|
||||||
|
```
|
||||||
|
|
||||||
|
履歴のchecksum不一致や未知版、schema不整合では停止する。台帳の行を削除したり、
|
||||||
|
dirtyを手動でappliedへ書き換えて回避しない。schema変更前にはDBバックアップを取得する。
|
||||||
|
試験専用の`--allow-insecure`は隔離された使い捨てDB以外では使わない。
|
||||||
|
MySQL 8.4の実DB試験でCLI、再開、並行実行、版更新を確認する。
|
||||||
|
SQLite/PostgreSQLの既存起動・migration経路には変更を加えない。
|
||||||
|
|
||||||
|
2026-11-30:共通configのkeyをUnicode/NO PAD対応する版2を追加。
|
||||||
|
版1のchecksumや保存済み値を変更せず更新する。MLのCAS・予算契約も3DBで再検証。
|
||||||
|
名前空間pilot用`mysql-namespace-schema`も追加したが、本体起動対応ではない。
|
||||||
|
適用範囲と依存componentの再開順は[DB移植計画](../design/ja/database-portability.md#namespace-pilotの操作)を参照。
|
||||||
|
|
||||||
|
## 残件
|
||||||
|
|
||||||
|
- [x] ML-01:サービス間認証、provider、オフライン学習、Go契約、合成HTTP結合試験
|
||||||
|
- [x] ML-02a:Domain別設定の内部保存、世代付きCAS、prefix除外、要求生成時の同意・byte上限
|
||||||
|
- [x] ML-02b:管理者API・設定パネル、Origin/不正入力/競合の検証、Chromium読込試験
|
||||||
|
- [x] ML-02c:日次入力byte上限・永続予約・重複拒否・失敗時非返却(worker未接続)
|
||||||
|
- [ ] ML-02:モデル配布・失効、予算使用量の表示、receipt保持方針、監視接続
|
||||||
|
- [ ] ML-03:既存イベントキュー接続、差分抽出、取消・再試行・世代再確認、保存層(両DB)
|
||||||
|
- [ ] ML-04:City候補・根拠・比較UI、手動修正保護、権限付き確認・明示適用
|
||||||
|
- [ ] ML-05:コーパス別精度/負荷計測、同時数調整、配布条件・イメージbuild/本番受入
|
||||||
|
|
||||||
|
Pages接続時は`page.created`/`revision.created`等の既存activity outboxを別consumerで処理する。
|
||||||
|
`city.reconcile`をそのまま重い推論に置き換えない。保存完了を待たせず、処理結果保存前に
|
||||||
|
Revision・scope・設定世代を再確認する。MLエラー時に通常の保存・閲覧を失敗させない。
|
||||||
|
|
||||||
|
参照:[OpenAI Embeddings API](https://developers.openai.com/api/reference/resources/embeddings/methods/create)、
|
||||||
|
[Gensim Doc2Vec](https://radimrehurek.com/gensim/models/doc2vec.html)。
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# PagesWiki v0.19.0
|
||||||
|
|
||||||
|
リリース対象:v0.18.0以降の実装整理。ビルド・タグ昇格・本番配備の結果は別途記録する。
|
||||||
|
|
||||||
|
## 利用者向け変更
|
||||||
|
|
||||||
|
- RSSのX共有をクリック時のポップアップに変更。元ページの遷移と二重オープンを防ぐ。
|
||||||
|
- スライドビューアとエディタプレビューに再生/停止、1〜3600秒の間隔、ループを追加。
|
||||||
|
- Domain管理にMachine Learning設定パネルを追加。設定保存だけでは学習・文書送信は開始しない。
|
||||||
|
|
||||||
|
## 基盤と境界
|
||||||
|
|
||||||
|
- MySQL 8.4向けにML予算、Campus/Domain、ユーザー/グループ、認証情報保存の限定実装を追加。
|
||||||
|
schemaのstatus/check/apply/resumeは明示CLIのみ。本体のMySQL起動は未対応。
|
||||||
|
- Pages Machine Learningは任意の独立サービス。通常の配備には含めず、自動起動しない。
|
||||||
|
- DB検査では未導入のML予算schemaを任意機能として扱う。部分導入・導入後のテーブル欠落は引き続き異常として検出する。
|
||||||
|
- ファイル検査のpolicy/plugin実行基盤は未接続。今回の更新で検査済み保証を追加しない。
|
||||||
|
- CLIスキル初版、展示マニフェスト・合成データ・紹介資料を保存。展示クラスタは配備対象外。
|
||||||
|
|
||||||
|
## データ互換性と配備条件
|
||||||
|
|
||||||
|
今回の機能用ML予算migrationは通常起動に接続していない。MySQLやMLサービスへ本番データを移さない。
|
||||||
|
既存のDB種別・保存先・稼働サービスを維持する。未起動の外部インスタンスを更新の副作用で起動しない。
|
||||||
|
実際の稼働イメージがv0.18.0と同一とは限らないため、旧イメージと停止時点の保存領域・設定を保全する。
|
||||||
|
復旧時は切替後の書込みを保全し、バックアップを稼働中の保存領域へ上書きしない。
|
||||||
|
|
||||||
|
## 検証
|
||||||
|
|
||||||
|
整理時にSQLite/PostgreSQL 17/MySQL 8.4の対象契約をrace付きで確認。
|
||||||
|
RSSとスライドはPC・モバイルのChromium試験、MLは隔離環境の合成データ試験を実施。
|
||||||
|
リリース判定はGiteaの全Goテスト・PostgreSQL試験・4イメージ公開の成功後に行う。
|
||||||
|
任意のMLサービスとGecko relayは本番更新で起動しない。
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Pages / pages-cli 紹介資料
|
||||||
|
|
||||||
|
2026年11月の展示に向けて作った資料を、編集元・図版・配布成果物と一緒に保存する。
|
||||||
|
現行バージョンの対応表ではない。機能の実装状況は [残件台帳](../design/ja/implementation-backlog.md)、
|
||||||
|
DBの対応範囲は [DB移植計画](../design/ja/database-portability.md) を参照する。
|
||||||
|
|
||||||
|
## Pagesのスライド機能用
|
||||||
|
|
||||||
|
| 編集元 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `pages-architecture-ja.md` | 技術説明の詳細な構成案 |
|
||||||
|
| `pages-architecture-5min-ja.md` | 10枚・約5分の紹介。30秒送りを想定 |
|
||||||
|
| `../../static/diagrams/pages-architecture/*.svg` | 5分版で参照する編集可能な構成図 |
|
||||||
|
|
||||||
|
Markdownの `---` をスライド境界として使用する。Pagesへ通常の権限確認・保存を行い、
|
||||||
|
スライドビューアで開く。Gitへの保存だけでは公開Wikiの作成・更新にはならない。
|
||||||
|
図版はアプリと一緒に配信する必要がある。
|
||||||
|
[再生・ループの操作](../design/ja/slideshow.md)も参照。
|
||||||
|
|
||||||
|
## A4配布資料
|
||||||
|
|
||||||
|
`../../output/pdf/` のPDFとSVGは、展示時の配布成果物として意図的にGitへ保存する。
|
||||||
|
レンダリング用PNGや一時ファイルは含めない。ファイル名は既存の配布リンクを維持するため変更しない。
|
||||||
|
|
||||||
|
- `pages-pages-cli-four-sheets-a4-ja.pdf`:技術・思想・画面設計・ディスカッションの4枚組。
|
||||||
|
- `pages-pages-cli-discussion-a4-ja.pdf`:ディスカッション単独版。
|
||||||
|
- `architecture`、`design`、`interface` の単独PDF、および `technical-and-design`、`three-sheets`:
|
||||||
|
段階的に作成した既存配布版。過去の成果物として保持し、4枚組から機械的に切り出したものとは扱わない。
|
||||||
|
- 同ディレクトリのSVG:A4資料の構成図。スライド用SVGとは別の図版。
|
||||||
|
|
||||||
|
`build-pages-onepager.py` が現在生成するPDFは **4枚組とディスカッションの2ファイル**。
|
||||||
|
加えてA4用SVGを出力する。その他の既存PDFは上書き・再生成しない。
|
||||||
|
|
||||||
|
再生成にはPython、ReportLab、DejaVu Sans/Sans MonoとDroidSansFallbackFullのフォントが必要。
|
||||||
|
フォントパスはスクリプト冒頭で指定する。日付・機能記述は展示時点のままなので、
|
||||||
|
現在版へ更新する場合は本文を再確認してから実行する。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 docs/presentations/build-pages-onepager.py
|
||||||
|
# 一時ディレクトリで4ページすべてを描画し、重なり・文字欠けを確認する
|
||||||
|
pdftoppm -png output/pdf/pages-pages-cli-four-sheets-a4-ja.pdf /tmp/pages-handout
|
||||||
|
```
|
||||||
|
|
||||||
|
2026-11-30の整理では既存4枚組を描画確認し、PDF自体は再生成していない。
|
||||||
@@ -0,0 +1,533 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Build the A4 technical handout and its editable vector diagrams.
|
||||||
|
|
||||||
|
Requires reportlab. Source: repository design/operations docs and sibling
|
||||||
|
pages-cli README + docs/neomutt.md, reviewed 2026-11-15.
|
||||||
|
All coordinates are points, measured from the top left. Diagram primitives
|
||||||
|
are emitted to both SVG and PDF so the standalone figures match the handout.
|
||||||
|
"""
|
||||||
|
from pathlib import Path
|
||||||
|
from html import escape
|
||||||
|
import math
|
||||||
|
|
||||||
|
from reportlab.pdfgen import canvas
|
||||||
|
from reportlab.pdfbase import pdfmetrics
|
||||||
|
from reportlab.pdfbase.ttfonts import TTFont
|
||||||
|
from reportlab.lib.colors import HexColor
|
||||||
|
from reportlab.lib.pagesizes import A4
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
OUT = ROOT / "output/pdf"
|
||||||
|
OUT.mkdir(parents=True, exist_ok=True)
|
||||||
|
INK, MUTED, LINE = "#172433", "#526171", "#b6c2cd"
|
||||||
|
ACCENT, PALE, WHITE = "#244d70", "#f1f5f8", "#ffffff"
|
||||||
|
FONT_DIR = Path("/usr/share/fonts/truetype")
|
||||||
|
pdfmetrics.registerFont(TTFont("Latin", str(FONT_DIR / "dejavu/DejaVuSans.ttf")))
|
||||||
|
pdfmetrics.registerFont(TTFont("LatinBold", str(FONT_DIR / "dejavu/DejaVuSans-Bold.ttf")))
|
||||||
|
pdfmetrics.registerFont(TTFont("Mono", str(FONT_DIR / "dejavu/DejaVuSansMono.ttf")))
|
||||||
|
pdfmetrics.registerFont(TTFont("JP", str(FONT_DIR / "droid/DroidSansFallbackFull.ttf")))
|
||||||
|
|
||||||
|
|
||||||
|
def runs(s, bold=False, mono=False):
|
||||||
|
current, buf = None, ""
|
||||||
|
for ch in s:
|
||||||
|
font = "JP" if ord(ch) > 0x2FFF else ("Mono" if mono else "LatinBold" if bold else "Latin")
|
||||||
|
if current is not None and font != current:
|
||||||
|
yield current, buf
|
||||||
|
buf = ""
|
||||||
|
current, buf = font, buf + ch
|
||||||
|
if buf:
|
||||||
|
yield current, buf
|
||||||
|
|
||||||
|
|
||||||
|
def width(s, size, bold=False, mono=False):
|
||||||
|
return sum(pdfmetrics.stringWidth(t, f, size) for f, t in runs(s, bold, mono))
|
||||||
|
|
||||||
|
|
||||||
|
class Drawing:
|
||||||
|
def __init__(self, w, h, title):
|
||||||
|
self.w, self.h, self.title, self.items = w, h, title, []
|
||||||
|
|
||||||
|
def box(self, x, y, w, h, fill=WHITE, stroke=LINE, radius=2):
|
||||||
|
self.items.append(("box", x, y, w, h, fill, stroke, radius))
|
||||||
|
|
||||||
|
def line(self, x1, y1, x2, y2, color=LINE, dashed=False):
|
||||||
|
self.items.append(("line", x1, y1, x2, y2, color, dashed))
|
||||||
|
|
||||||
|
def arrow(self, x1, y1, x2, y2, color=MUTED, dashed=False):
|
||||||
|
self.line(x1, y1, x2, y2, color, dashed)
|
||||||
|
a = math.atan2(y2-y1, x2-x1)
|
||||||
|
for delta in (-0.45, 0.45):
|
||||||
|
self.line(x2, y2, x2-4*math.cos(a+delta), y2-4*math.sin(a+delta), color)
|
||||||
|
|
||||||
|
def text(self, x, y, s, size=9, bold=False, color=INK, align="left", mono=False):
|
||||||
|
self.items.append(("text", x, y, s, size, bold, color, align, mono))
|
||||||
|
|
||||||
|
def pdf(self, c, x=0, y=0):
|
||||||
|
ph = A4[1]
|
||||||
|
for p in self.items:
|
||||||
|
if p[0] == "box":
|
||||||
|
_, bx, by, w, h, fill, stroke, r = p
|
||||||
|
c.setFillColor(HexColor(fill)); c.setStrokeColor(HexColor(stroke)); c.setLineWidth(.6)
|
||||||
|
c.roundRect(x+bx, ph-y-by-h, w, h, r, fill=1, stroke=1)
|
||||||
|
elif p[0] == "line":
|
||||||
|
_, x1,y1,x2,y2,col,dash=p
|
||||||
|
c.setStrokeColor(HexColor(col)); c.setLineWidth(.65); c.setDash([2,2] if dash else [])
|
||||||
|
c.line(x+x1,ph-y-y1,x+x2,ph-y-y2); c.setDash([])
|
||||||
|
else:
|
||||||
|
_, tx,ty,s,size,bold,col,align,mono=p
|
||||||
|
w=width(s,size,bold,mono)
|
||||||
|
tx -= w/2 if align=="center" else w if align=="right" else 0
|
||||||
|
c.setFillColor(HexColor(col))
|
||||||
|
for f,t in runs(s,bold,mono):
|
||||||
|
c.setFont(f,size); c.drawString(x+tx,ph-y-ty,t)
|
||||||
|
tx += pdfmetrics.stringWidth(t,f,size)
|
||||||
|
|
||||||
|
def svg(self, path):
|
||||||
|
a=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{self.w}pt" height="{self.h}pt" viewBox="0 0 {self.w} {self.h}" role="img" aria-labelledby="title">',
|
||||||
|
f'<title id="title">{escape(self.title)}</title>', '<rect width="100%" height="100%" fill="white"/>']
|
||||||
|
for p in self.items:
|
||||||
|
if p[0]=="box":
|
||||||
|
_,x,y,w,h,fill,stroke,r=p
|
||||||
|
a.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{r}" fill="{fill}" stroke="{stroke}" stroke-width="0.6"/>')
|
||||||
|
elif p[0]=="line":
|
||||||
|
_,x1,y1,x2,y2,col,dash=p
|
||||||
|
d=' stroke-dasharray="2 2"' if dash else ''
|
||||||
|
a.append(f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{col}" stroke-width="0.65"{d}/>')
|
||||||
|
else:
|
||||||
|
_,x,y,s,size,bold,col,align,mono=p
|
||||||
|
anchor={"left":"start","center":"middle","right":"end"}[align]
|
||||||
|
family="DejaVu Sans Mono,monospace" if mono else "DejaVu Sans,Noto Sans CJK JP,sans-serif"
|
||||||
|
a.append(f'<text x="{x}" y="{y}" font-family="{family}" font-size="{size}" font-weight="{700 if bold else 400}" text-anchor="{anchor}" fill="{col}">{escape(s)}</text>')
|
||||||
|
path.write_text('\n'.join(a)+"\n</svg>\n",encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def architecture():
|
||||||
|
d=Drawing(535,179,"Pages and pages-cli: application, extensions, APIs and storage")
|
||||||
|
for x,w,title,sub in [(0,163,"Web / PWA","Wiki · City · Organizer"),(186,163,"pages-cli / pages","Shell · $EDITOR · NeoMutt"),(372,163,"DAV clients","CalDAV · CardDAV")]:
|
||||||
|
d.box(x,0,w,32,PALE); d.text(x+8,13,title,9,True); d.text(x+8,25,sub,7.4,color=MUTED)
|
||||||
|
d.arrow(x+w/2,32,x+w/2,55)
|
||||||
|
d.text(91,46,"HTTPS",6.8,color=MUTED)
|
||||||
|
d.text(278,46,"HTTPS / Bearer",6.8,color=MUTED)
|
||||||
|
d.text(465,46,"HTTPS / DAV",6.8,color=MUTED)
|
||||||
|
d.box(0,55,535,70,WHITE,ACCENT)
|
||||||
|
d.text(10,70,"PagesWiki / Go application",10,True,ACCENT)
|
||||||
|
d.text(525,70,"Host-based routing / HTTP API",7.6,color=MUTED,align="right")
|
||||||
|
d.line(10,77,525,77)
|
||||||
|
components=[("Wiki / files","Editor · viewers · City Map"),("System extensions","Tasks · calendar · contacts · RSS"),("Integration / jobs","DAV · plugins · background jobs")]
|
||||||
|
for i,(name,role) in enumerate(components):
|
||||||
|
x=10+i*173; y=84
|
||||||
|
d.box(x,y,169,32,PALE,LINE)
|
||||||
|
d.text(x+7,y+13,name,8.7,True); d.text(x+7,y+25,role,7.1,color=MUTED)
|
||||||
|
d.arrow(130,125,130,145); d.arrow(403,125,403,145)
|
||||||
|
d.box(0,145,260,34,PALE); d.box(275,145,260,34,PALE)
|
||||||
|
d.text(9,159,"SQLite / PostgreSQL 17",9,True)
|
||||||
|
d.text(9,172,"Metadata · revisions · settings · indexes",7.5,color=MUTED)
|
||||||
|
d.text(284,159,"Persistent files",9,True)
|
||||||
|
d.text(284,172,"HTML · attachments · calendar / task data",7.5,color=MUTED)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def domains():
|
||||||
|
d=Drawing(252,92,"Campus manages domains independently of application instances")
|
||||||
|
d.box(0,0,252,23,PALE)
|
||||||
|
d.text(126,15,"Campus / configuration controller",8.4,True,align="center")
|
||||||
|
d.arrow(60,23,60,42,dashed=True); d.arrow(192,23,192,42,dashed=True)
|
||||||
|
for x,label,hosts in [(0,"Instance A",["wiki.example.test","lab.example.test"]),(132,"Instance B",["team.example.test"])]:
|
||||||
|
d.box(x,42,120,49,WHITE,ACCENT); d.text(x+7,55,label,8.3,True)
|
||||||
|
for i,host in enumerate(hosts):
|
||||||
|
d.text(x+7,69+13*i,host,7,mono=True)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def editing():
|
||||||
|
d=Drawing(252,92,"HTML and Markdown editing, conversion and preview")
|
||||||
|
for x,w,title,sub in [(0,76,"Markdown","editing"),(102,64,"HTML","stored content")]:
|
||||||
|
d.box(x,11,w,35,PALE); d.text(x+w/2,25,title,9,True,align="center"); d.text(x+w/2,38,sub,7,color=MUTED,align="center")
|
||||||
|
d.arrow(76,22,102,22); d.arrow(102,35,76,35)
|
||||||
|
d.text(87,7,"convert",6.4,align="center",color=MUTED)
|
||||||
|
d.box(192,11,60,35,PALE); d.text(222,25,"Viewer",8.6,True,align="center"); d.text(222,38,"Preview",7,color=MUTED,align="center")
|
||||||
|
d.arrow(166,29,192,29)
|
||||||
|
d.line(134,46,134,64); d.arrow(134,64,222,64)
|
||||||
|
d.text(0,83,"HTML fragments retained in Markdown",7.2,color=MUTED)
|
||||||
|
d.text(222,76,"Slides",7.7,True,align="center")
|
||||||
|
d.text(222,89,"Reveal.js",7,color=MUTED,align="center")
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def identity():
|
||||||
|
d=Drawing(252,79,"Paths resolve to a stable Page, immutable revisions and content hashes")
|
||||||
|
for y,label in [(0,"/guide/api"),(33,"/project/ref")]:
|
||||||
|
d.box(0,y,66,24,PALE); d.text(33,y+15,label,7,align="center",mono=True)
|
||||||
|
d.box(83,15,49,29,PALE); d.text(107.5,27,"Page",8,True,align="center"); d.text(107.5,38,"UUID",7,color=MUTED,align="center")
|
||||||
|
d.arrow(66,12,83,24); d.arrow(66,45,83,35)
|
||||||
|
d.box(147,15,47,29,PALE); d.text(170.5,27,"Revision",7.2,True,align="center"); d.text(170.5,38,"UUID / lang",6.2,color=MUTED,align="center")
|
||||||
|
d.arrow(132,29,147,29)
|
||||||
|
d.box(209,15,43,29,PALE); d.text(230.5,27,"Document",6.4,True,align="center"); d.text(230.5,38,"SHA-256",6.6,color=MUTED,align="center")
|
||||||
|
d.arrow(194,29,209,29)
|
||||||
|
d.text(0,74,"mutable address",7,color=MUTED)
|
||||||
|
d.text(83,74,"stable identity / immutable history",7,color=MUTED)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def city():
|
||||||
|
d=Drawing(252,79,"Campus and Domain organize Quartier, Street, Spot and Pages")
|
||||||
|
d.text(0,9,"Campus",8.5,True); d.arrow(45,6,60,6); d.text(65,9,"Domain = FQDN / namespace",8.2,True)
|
||||||
|
boxes=[(0,72,"Quartier","/lab"),(90,72,"Street","/lab/web"),(180,72,"Spot","/lab/web/api")]
|
||||||
|
for x,w,title,sub in boxes:
|
||||||
|
d.box(x,24,w,32,PALE); d.text(x+w/2,37,title,8,True,align="center"); d.text(x+w/2,49,sub,6.6,color=MUTED,align="center",mono=True)
|
||||||
|
d.arrow(72,40,90,40); d.arrow(162,40,180,40)
|
||||||
|
d.arrow(216,56,216,66); d.text(216,77,"Pages",8,True,align="center")
|
||||||
|
d.text(0,76,"path boundaries / map navigation",7,color=MUTED)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def body(d,x,y,lines,size=8.7,leading=13):
|
||||||
|
for i,s in enumerate(lines):
|
||||||
|
d.text(x,y+i*leading,s,size)
|
||||||
|
|
||||||
|
|
||||||
|
def section(d,y,number,title):
|
||||||
|
d.text(30,y,number,8.5,True,ACCENT)
|
||||||
|
d.text(51,y,title,10.3,True)
|
||||||
|
|
||||||
|
|
||||||
|
def technical_page():
|
||||||
|
page=Drawing(*A4,"Pages / pages-cli architecture handout")
|
||||||
|
page.text(30,33,"01 / TECHNICAL ARCHITECTURE",8,True,ACCENT)
|
||||||
|
page.text(565,33,"2026-11-15 / PagesWiki v0.18.0",7.6,color=MUTED,align="right")
|
||||||
|
page.text(30,64,"Pages",28,True)
|
||||||
|
page.text(137,64,"/ pages-cli",20,color=MUTED)
|
||||||
|
page.text(30,86,"Wiki・ファイル・タスク・予定を、ブラウザとターミナルで扱う。",10.7)
|
||||||
|
page.line(30,99,565,99,ACCENT)
|
||||||
|
section(page,117,"01","全体構成:Go製サーバー + Python製CLI + 形式別の表示・編集機能")
|
||||||
|
arch=architecture(); domain=domains(); editor=editing()
|
||||||
|
|
||||||
|
section(page,333,"02","ドメイン:サイトと配置先を分ける")
|
||||||
|
page.text(313,333,"03",8.5,True,ACCENT)
|
||||||
|
page.text(334,333,"エディタとトランスパイル",10.3,True)
|
||||||
|
body(page,30,456,["ドメインはFQDNごとのWiki。パス・設定・メンバーを分離。",
|
||||||
|
"キャンパスは複数ドメインと配置先インスタンスを管理。",
|
||||||
|
"一つのインスタンスに複数サイトを収容でき、別配置も可能。",
|
||||||
|
"配信するのは設定であり、記事の複製機能ではない。",
|
||||||
|
"HTTPのHostからサイトを選択。パスの重複はサイト間で許容。",
|
||||||
|
"設定配信は署名付き。配置先は参加・承認済みから選択。"],8.05,12.5)
|
||||||
|
body(page,313,456,["内蔵エディタはHTML/Markdown切替とライブプレビュー。",
|
||||||
|
"Wiki本文はHTMLで保存。編集時にMarkdownへ変換し、",
|
||||||
|
"Markdownで表せない属性・構造はHTMLのまま残す。",
|
||||||
|
"children・CSVマクロは編集時に保持し、表示時に展開。",
|
||||||
|
"同じ文書を通常ページ・印刷・Reveal.jsスライドで表示。",
|
||||||
|
"外部編集にはcode-server連携。vim.wasmは改善保留。"],8.05,12.5)
|
||||||
|
|
||||||
|
page.line(30,535,565,535)
|
||||||
|
section(page,556,"04","プラグイン:文書操作と機能追加")
|
||||||
|
page.text(313,556,"05",8.5,True,ACCENT)
|
||||||
|
page.text(334,556,"pages-cli:端末からの操作",10.3,True)
|
||||||
|
page.text(30,578,"表示・編集アダプタ",9,True,ACCENT)
|
||||||
|
body(page,30,595,["MIME・拡張子からビューア/エディタを選択する。",
|
||||||
|
"CSV・PDF・画像・動画・アーカイブ・Excalidraw等に対応。",
|
||||||
|
"外部エディタは別コンテナで動作し、ゲートウェイ経由で",
|
||||||
|
"ファイルを受け渡す。保存結果はWikiの履歴へ追加。"],8.05,12.5)
|
||||||
|
page.text(30,660,"システム拡張",9,True,ACCENT)
|
||||||
|
body(page,30,677,["タスク・カレンダー・連絡先・ブログ・日記・RSSを提供。",
|
||||||
|
"例:RSS記事をWiki/タスクへ、予定・連絡先をDAVで同期。",
|
||||||
|
"設定画面で有効/無効を切替。外部表示・編集サービスは",
|
||||||
|
"URL登録で追加できる。任意コードの動的ロードは未対応。"],8.05,12.5)
|
||||||
|
body(page,313,578,["独立リポジトリで配布するHTTPクライアント。実行名 pages。",
|
||||||
|
"対話シェル、$EDITOR/$PAGER、言語指定、OIDC承認。",
|
||||||
|
"タスクの作成・計画・作業時間記録・レポート、連絡先検索。",
|
||||||
|
"NeoMuttから本文をWikiへ保存し、関連タスクを作成する。"],8.05,12.5)
|
||||||
|
page.box(313,631,252,89,PALE)
|
||||||
|
for y,s in [(646,"pages login --oidc --no-browser"),(662,"pages edit /lab/guide --lang ja"),(678,"pages task from-mail < message.eml"),(694,"pages task start TASK_UUID"),(710,"pages task stop")]:
|
||||||
|
page.text(322,y,s,7.3,mono=True)
|
||||||
|
|
||||||
|
page.line(30,738,565,738)
|
||||||
|
page.text(30,755,"現行の制約",8.2,True,ACCENT)
|
||||||
|
body(page,30,770,["v0.18.0は単一書込インスタンス構成。PostgreSQL版は本文全文検索・外部エディタ連携・Web Push等が未対応。",
|
||||||
|
"内蔵エディタとInboxは利用可能。プラグインの利用可否はDB構成・追加サービスの配置に依存する。"],7.8,12)
|
||||||
|
page.line(30,798,565,798)
|
||||||
|
page.text(30,812,"設計資料:docs/design/ja/{campus-federation,viewer-editor,editor-resilience,extensions}.md",6.8,color=MUTED)
|
||||||
|
page.text(30,824,"構成制約:docs/operations/postgresql-migration.md | CLI:git.anya.jp/anya/pages-cli",6.8,color=MUTED)
|
||||||
|
|
||||||
|
for name,d in [("pages-system-architecture",arch),("pages-domain-deployment",domain),("pages-editor-conversion",editor)]:
|
||||||
|
d.svg(OUT/(name+".svg"))
|
||||||
|
return [(page,0,0),(arch,30,130),(domain,30,346),(editor,313,346)]
|
||||||
|
|
||||||
|
|
||||||
|
def city_navigation():
|
||||||
|
d=Drawing(535,128,"URL hierarchy as districts, streets and places: conceptual navigation")
|
||||||
|
d.box(0,0,535,127,WHITE,ACCENT)
|
||||||
|
d.text(12,17,"wiki.example.test",10,True)
|
||||||
|
d.text(523,17,"One domain / one city",8,color=MUTED,align="right")
|
||||||
|
for x,title,path,street,spot in [(12,"Research","/lab","/lab/web","/lab/web/api"),(187,"Operations","/ops","/ops/network","/ops/network/dns"),(362,"Projects","/projects","/projects/wiki","/projects/wiki/editor")]:
|
||||||
|
d.box(x,29,161,86,PALE)
|
||||||
|
d.text(x+9,44,title,9,True); d.text(x+152,44,path,7.2,align="right",mono=True)
|
||||||
|
d.line(x+10,62,x+151,62,LINE)
|
||||||
|
d.text(x+9,57,street,7.1,mono=True)
|
||||||
|
d.line(x+26,62,x+26,78,ACCENT)
|
||||||
|
d.box(x+11,79,139,25,WHITE)
|
||||||
|
d.text(x+80.5,95,spot,7,align="center",mono=True)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def work_connections():
|
||||||
|
d=Drawing(252,79,"Email and RSS connect to Wiki, tasks and work records")
|
||||||
|
for x,title,sub in [(0,"Mail / RSS","capture"),(90,"Wiki + task","link"),(180,"Work log","report")]:
|
||||||
|
d.box(x,16,72,37,PALE)
|
||||||
|
d.text(x+36,31,title,8,True,align="center")
|
||||||
|
d.text(x+36,44,sub,7,color=MUTED,align="center")
|
||||||
|
d.arrow(72,34,90,34); d.arrow(162,34,180,34)
|
||||||
|
d.text(0,74,"NeoMutt / pages-cli / Web dashboard",7.2,color=MUTED)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def multiple_contexts():
|
||||||
|
d=Drawing(252,79,"Two navigation paths open the same page")
|
||||||
|
for y,path in [(0,"/guide/api"),(35,"/project/ref")]:
|
||||||
|
d.box(0,y,83,26,PALE)
|
||||||
|
d.text(41.5,y+17,path,8,align="center",mono=True)
|
||||||
|
d.box(119,10,133,42,PALE)
|
||||||
|
d.text(185.5,28,"One page",10,True,align="center")
|
||||||
|
d.text(185.5,43,"Shared content / history",7,align="center",color=MUTED)
|
||||||
|
d.arrow(83,13,119,22); d.arrow(83,48,119,40)
|
||||||
|
d.text(0,76,"Multiple paths, no document copies",7.4,color=MUTED)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def design_page():
|
||||||
|
p=Drawing(*A4,"Pages / pages-cli design choices")
|
||||||
|
p.text(30,33,"02 / DESIGN CONCEPT",8,True,ACCENT)
|
||||||
|
p.text(565,33,"2026-11-15 / PagesWiki",7.6,color=MUTED,align="right")
|
||||||
|
p.text(30,64,"Pages",28,True); p.text(137,64,"/ pages-cli",20,color=MUTED)
|
||||||
|
p.text(30,86,"URLの階層を街の案内図に。文書を日々の作業につなぐ。",10.7)
|
||||||
|
p.line(30,99,565,99,ACCENT)
|
||||||
|
section(p,117,"01","フォルダの階層に、地図という入口を重ねる")
|
||||||
|
town=city_navigation(); ident=multiple_contexts(); work=work_connections()
|
||||||
|
body(p,30,278,["Knowledge City Modelは、ドメインを街、URLの配下を街区(Quartier)・通り(Street)・拠点(Spot)として扱う。",
|
||||||
|
"検索語が浮かばないときも、分野や周辺のページから探せる。地図・ツリー・検索は同じ文書群の別の入口。",
|
||||||
|
"URLからの自動分類を起点に、名前や範囲を調整する。地図のためだけに別の分類体系を作り直さない。",
|
||||||
|
"用途や公開範囲が異なるサイトはドメインを分け、各サイトの設定・メンバーを個別に管理する。"],8.4,13)
|
||||||
|
p.text(565,263,"図は階層の概念図。実際のCity Map画面ではない。",6.6,color=MUTED,align="right")
|
||||||
|
|
||||||
|
section(p,337,"02","一つのページを複数の文脈に置く")
|
||||||
|
p.text(313,337,"03",8.5,True,ACCENT); p.text(334,337,"文書を作業の流れへ組み込む",10.3,True)
|
||||||
|
body(p,30,444,["手順書を「技術分野」と「プロジェクト」の両方から参照。",
|
||||||
|
"コピーではなく、複数のパスで同じページを指す。",
|
||||||
|
"内容を更新すれば、どちらの入口からも同じ版を読める。",
|
||||||
|
"「分類し直す」と「別の文書を作る」を分けることで、",
|
||||||
|
"整理のための複製や、コピー先だけの更新漏れを減らす。"],8.05,13)
|
||||||
|
body(p,313,444,["メールやRSSを読んだ場所から、Wiki保存とタスク化へ。",
|
||||||
|
"タスクから関連メモを開き、作業時間や予定と結び付ける。",
|
||||||
|
"予定・連絡先はCalDAV/CardDAVで既存アプリとも接続。",
|
||||||
|
"Webでは一覧・カレンダー・ウィジェット、端末では短い",
|
||||||
|
"コマンドを使い、作業環境に合わせて入口を選ぶ。"],8.05,13)
|
||||||
|
p.line(30,512,565,512)
|
||||||
|
section(p,534,"04","文書形式と、使う道具を固定しない")
|
||||||
|
p.text(30,558,"編集はMarkdown、表示は用途に合わせる",9.2,True,ACCENT)
|
||||||
|
body(p,30,578,["Wiki本文の保存形式はHTML。Markdownで書き、必要な部分はHTMLを残して編集できる。",
|
||||||
|
"文書をページ・印刷・スライドとして使い分ける。CSVや図は専用の表示・編集機能で扱う。"],8.6,14)
|
||||||
|
p.text(30,618,"プラグインは二つの役割に分ける",9.2,True,ACCENT)
|
||||||
|
p.box(30,631,252,61,PALE); p.box(313,631,252,61,PALE)
|
||||||
|
p.text(41,648,"文書の表示・編集",9,True)
|
||||||
|
body(p,41,665,["CSV表、Excalidraw、Reveal.js、外部エディタ。",
|
||||||
|
"同じ内容を、その形式に向いた道具で扱う。"],8.1,13)
|
||||||
|
p.text(324,648,"アプリケーション機能の追加",9,True)
|
||||||
|
body(p,324,665,["タスク、カレンダー、連絡先、ブログ、日記、RSS。",
|
||||||
|
"文書以外の画面・操作・設定を追加する。"],8.1,13)
|
||||||
|
body(p,30,715,["内蔵エディタで完結する使い方も、code-serverやpages-cliの $EDITOR を使う選択肢も用意する。",
|
||||||
|
"必要な機能を有効にして使う。外部サービスの配置・DB構成による対応範囲は技術編に記載。"],8.4,14)
|
||||||
|
p.line(30,748,565,748)
|
||||||
|
p.text(30,766,"デザインの軸",8.5,True,ACCENT)
|
||||||
|
p.text(112,766,"街として探す / コピーせず参照する / 作業につなぐ / 道具を選ぶ",9.4,True)
|
||||||
|
p.line(30,798,565,798)
|
||||||
|
p.text(30,812,"設計資料:docs/design/ja/{principles,campus-federation,viewer-editor,extensions}.md / pages-cli README",6.8,color=MUTED)
|
||||||
|
p.text(30,824,"Knowledge City Model:『とある科学の超電磁砲』の学舎の園に着想。構成・実装制約は別紙「技術編」を参照。",6.8,color=MUTED)
|
||||||
|
for name,d in [("pages-design-city-navigation",town),("pages-design-multiple-paths",ident),("pages-design-workflow",work)]:
|
||||||
|
d.svg(OUT/(name+".svg"))
|
||||||
|
return [(p,0,0),(town,30,130),(ident,30,350),(work,313,350)]
|
||||||
|
|
||||||
|
|
||||||
|
def export_pdf(path, pages, title):
|
||||||
|
c=canvas.Canvas(str(path),pagesize=A4,pageCompression=1)
|
||||||
|
c.setTitle(title); c.setAuthor("PagesWiki project")
|
||||||
|
c.setSubject("Pages / pages-cli:技術構成とデザインの説明資料")
|
||||||
|
for drawings in pages:
|
||||||
|
for d,x,y in drawings:
|
||||||
|
d.pdf(c,x,y)
|
||||||
|
c.showPage()
|
||||||
|
c.save()
|
||||||
|
print(path)
|
||||||
|
|
||||||
|
|
||||||
|
def screen_layout():
|
||||||
|
d=Drawing(535,144,"Desktop information density and mobile touch layout: conceptual wireframes")
|
||||||
|
d.box(0,0,350,143,WHITE,ACCENT)
|
||||||
|
d.box(0,0,350,24,PALE,LINE)
|
||||||
|
d.text(8,16,"Pages",9,True)
|
||||||
|
d.box(54,5,140,14,WHITE)
|
||||||
|
d.text(61,15,"Search / command",7,color=MUTED)
|
||||||
|
d.text(341,15,"Plan Inbox Theme User",7,align="right")
|
||||||
|
d.box(7,31,70,104,PALE)
|
||||||
|
d.text(13,44,"Projects",8,True)
|
||||||
|
for i,s in enumerate(["All tasks","Wiki","Exhibition","Personal"]):
|
||||||
|
if i==2: d.box(11,76,61,16,"#dce8f0",LINE)
|
||||||
|
d.text(14,61+i*15,s,7.2)
|
||||||
|
d.text(87,43,"Status / Subject",7.5,True)
|
||||||
|
d.text(340,43,"Due / Wiki",7.5,True,align="right")
|
||||||
|
for i,(s,date) in enumerate([("Review API design","11-15"),("Prepare exhibit","11-16"),("Write deployment notes","11-17"),("Update diagrams","11-18")]):
|
||||||
|
y=50+i*20
|
||||||
|
if i==1: d.box(83,y,259,20,"#dce8f0",LINE)
|
||||||
|
d.text(88,y+13,s,7.4); d.text(337,y+13,date,7.2,align="right")
|
||||||
|
d.line(83,y+20,342,y+20)
|
||||||
|
d.box(374,0,161,143,WHITE,ACCENT)
|
||||||
|
d.box(374,0,161,24,PALE)
|
||||||
|
d.text(383,16,"Pages / Tasks",8.5,True)
|
||||||
|
for i,(s,sub) in enumerate([("Review API design","In progress / Nov 15"),("Prepare exhibit","To do / Nov 16")]):
|
||||||
|
y=32+i*52
|
||||||
|
d.box(382,y,145,44,PALE)
|
||||||
|
d.text(389,y+14,s,8,True); d.text(389,y+28,sub,7,color=MUTED)
|
||||||
|
d.text(389,y+39,"Edit Date Wiki",7)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def theme_variants():
|
||||||
|
d=Drawing(535,70,"Same layout with light, dark and wallpaper-derived colors; illustrative palettes")
|
||||||
|
for x,label,bg,fg,accent in [(0,"LIGHT","#f1f5f8","#172433","#dce8f0"),(186,"DARK","#26303d","#e3eaf1","#405569"),(372,"WALLPAPER COLOR","#f0ebe5","#42392e","#d3c2ac")]:
|
||||||
|
d.box(x,0,163,69,bg)
|
||||||
|
d.text(x+8,14,label,7.5,True,fg)
|
||||||
|
d.box(x+8,22,147,15,accent,accent)
|
||||||
|
d.text(x+14,32,"Search / command",7,color=fg)
|
||||||
|
d.line(x+8,45,x+155,45,fg); d.line(x+8,54,x+109,54,fg)
|
||||||
|
d.text(x+8,64,"Same controls / layout",6.6,color=fg)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def screen_page():
|
||||||
|
p=Drawing(*A4,"Pages / pages-cli screen and interaction design")
|
||||||
|
p.text(30,33,"03 / INTERFACE & INTERACTION",8,True,ACCENT)
|
||||||
|
p.text(565,33,"2026-11-15 / PagesWiki",7.6,color=MUTED,align="right")
|
||||||
|
p.text(30,64,"Pages",28,True); p.text(137,64,"/ pages-cli",20,color=MUTED)
|
||||||
|
p.text(30,86,"一覧で見渡し、キーで動かす。配色と入口は使う人に合わせる。",10.7)
|
||||||
|
p.line(30,99,565,99,ACCENT)
|
||||||
|
section(p,117,"01","デスクトップは一覧密度、モバイルはタッチ操作を優先")
|
||||||
|
layout=screen_layout(); themes=theme_variants()
|
||||||
|
p.text(30,285,"デスクトップ:プロジェクト+表形式の一覧",7.5,color=MUTED)
|
||||||
|
p.text(404,285,"モバイル:カード型の操作領域",7.5,color=MUTED)
|
||||||
|
body(p,30,304,["タスクは1行ずつ比較し、通常一覧では件名・状態・日付をその場で編集。キーボード一覧は別表示として用意。",
|
||||||
|
"設定・詳細だけをダイアログへ。ダッシュボードはウィジェットを並べ替え、サイズを変更できる。"],8.3,13)
|
||||||
|
|
||||||
|
section(p,343,"02","ショートカット:画面ごとの操作")
|
||||||
|
p.text(313,343,"03",8.5,True,ACCENT); p.text(334,343,"検索欄をコマンドの入口にも",10.3,True)
|
||||||
|
for i,(key,label) in enumerate([
|
||||||
|
("/ e ?","閲覧:検索 / 編集 / ヘルプ"),
|
||||||
|
("Ctrl+↑ / ↓","閲覧:親パス / 子ページ一覧"),
|
||||||
|
("j / k","タスク:次行 / 前行"),
|
||||||
|
("Ctrl+j / k","タスク:プロジェクト移動"),
|
||||||
|
("o / O / l","タスク:ソート / 逆順 / 絞込"),
|
||||||
|
("d / s","タスク:完了 / Pomodoro"),
|
||||||
|
("c / m / w","タスク:作成 / 編集 / Wiki")]):
|
||||||
|
y=363+18*i
|
||||||
|
p.box(30,y-10,80,15,PALE)
|
||||||
|
p.text(36,y,key,8,mono=True)
|
||||||
|
p.text(118,y,label,8.2)
|
||||||
|
p.text(30,492,"タスクの操作表は /v/plan/tasks/index が対象。",7.2,color=MUTED)
|
||||||
|
p.box(313,354,252,69,PALE)
|
||||||
|
for y,s in [(370,'add task "設計レビュー"'),(385,' project:Wiki cost:2h'),(406,'add cal 会議 from:... to:...')]:
|
||||||
|
p.text(322,y,s,8,mono=True)
|
||||||
|
body(p,313,442,["トップの検索候補からページへ直接移動。",
|
||||||
|
"add task / add cal でタスク・予定を作成する。",
|
||||||
|
"project: にはプロジェクト候補、cost: には見積時間。",
|
||||||
|
"予定は from: / to: に日時を入力する。"],8.1,13)
|
||||||
|
|
||||||
|
section(p,523,"04","テーマ:画面内で切替、トップの外観は個別に調整")
|
||||||
|
body(p,30,626,["ナビバーのテーマ選択は再読み込み不要。選択はブラウザに保持し、配色を変えても操作の配置は維持する。",
|
||||||
|
"トップの歯車から、壁紙のパス・濃さ、グラス効果の透明度を個人設定として変更できる。",
|
||||||
|
"壁紙の色から配色を調整するモードと強度も用意。配色と透明度はプレビューしてから保存する。"],8.4,14)
|
||||||
|
p.text(565,613,"配色比較は概念図。特定テーマのスクリーンショットではない。",6.7,color=MUTED,align="right")
|
||||||
|
|
||||||
|
section(p,695,"05","操作を切り替えても、入力の流れを保つ")
|
||||||
|
body(p,30,716,["内蔵エディタは本文とプレビューを並べ、非表示時は編集領域を広げる。タッチ端末ではVimモードを解除。",
|
||||||
|
"単キー操作は入力欄や開いたダイアログでは抑止。タスク一覧は ? から、その画面のキー操作を確認できる。",
|
||||||
|
"ターミナルでは pages の対話シェル・Tab補完・$EDITOR を利用。Webの短い操作とCLIのコマンドを併用する。"],8.2,14)
|
||||||
|
p.text(30,772,"図は画面構成の説明用。キーの役割は画面に依存し、ブラウザ/OSのキー割り当てと競合する場合がある。",7.3,color=MUTED)
|
||||||
|
p.line(30,798,565,798)
|
||||||
|
p.text(30,812,"実装参照:static/js/{viewer-shortcuts,task-index,home-command-parser,theme-picker,home-appearance}.js",6.7,color=MUTED)
|
||||||
|
p.text(30,824,"設計資料:docs/design/ja/{organizer-dashboard,calendar-mobile,editor-resilience}.md / pages-cli README",6.7,color=MUTED)
|
||||||
|
layout.svg(OUT/"pages-interface-layout.svg"); themes.svg(OUT/"pages-interface-themes.svg")
|
||||||
|
return [(p,0,0),(layout,30,130),(themes,30,537)]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
tech=technical_page(); design=design_page(); interface=screen_page(); discussion=discussion_page()
|
||||||
|
export_pdf(OUT/"pages-pages-cli-discussion-a4-ja.pdf",[discussion],"Pages / pages-cli - ディスカッション")
|
||||||
|
export_pdf(OUT/"pages-pages-cli-four-sheets-a4-ja.pdf",[tech,design,interface,discussion],"Pages / pages-cli - 技術・デザイン・画面設計・ディスカッション")
|
||||||
|
|
||||||
|
|
||||||
|
def discussion_page():
|
||||||
|
p=Drawing(*A4,"Discussion: what else do you want from a Wiki?")
|
||||||
|
p.text(30,33,"04 / DISCUSSION",8,True,ACCENT)
|
||||||
|
p.text(565,33,"2026-11-15 / PagesWiki",7.6,color=MUTED,align="right")
|
||||||
|
p.text(30,64,"Pages",28,True); p.text(137,64,"/ pages-cli",20,color=MUTED)
|
||||||
|
p.text(30,91,"あなたはWikiに、あと何が欲しいですか?",17,True)
|
||||||
|
p.line(30,105,565,105,ACCENT)
|
||||||
|
p.text(30,123,"気になる機能に○を。機能の追加だけでなく、使いにくさ・不要な機能の意見も歓迎。",9)
|
||||||
|
p.box(30,138,252,28,PALE)
|
||||||
|
p.box(313,138,252,28,PALE)
|
||||||
|
p.text(41,157,"追加している機能",11,True,ACCENT)
|
||||||
|
p.text(271,157,"実装あり",7.5,color=MUTED,align="right")
|
||||||
|
p.text(324,157,"追加予定・検討中",11,True,ACCENT)
|
||||||
|
p.text(554,157,"時期未定",7.5,color=MUTED,align="right")
|
||||||
|
existing=[
|
||||||
|
("文書の編集","HTML/Markdown、下書き、履歴復元、言語別編集"),
|
||||||
|
("探す・整理する","検索、ツリー、City Map、ブックマーク"),
|
||||||
|
("ファイルを扱う","CSV表編集、PDF・画像・動画・アーカイブ閲覧"),
|
||||||
|
("図・発表資料","Excalidraw表示、Reveal.jsスライド・プレビュー"),
|
||||||
|
("タスクと作業記録","親子タスク、日別計画、Pomodoro、実績集計"),
|
||||||
|
("予定と連絡先","カレンダー、アドレス帳、CalDAV/CardDAV"),
|
||||||
|
("情報収集・発信","RSS/FreshRSS連携、ブログ・日記、記事のRSS配信"),
|
||||||
|
("端末・メールとの接続","pages-cli、$EDITOR、NeoMuttからWiki保存・タスク化"),
|
||||||
|
("画面のカスタマイズ","テーマ、壁紙、ショートカット、ウィジェット配置"),
|
||||||
|
("サイト管理・ログイン","複数ドメイン、グループ、公開設定、OIDC/LDAP"),
|
||||||
|
]
|
||||||
|
planned=[
|
||||||
|
("コメント・評価","インラインコメント、スレッド、いいね、品質評価"),
|
||||||
|
("共同編集・編集体験","同時編集、見たまま編集の検討(現在は保留)"),
|
||||||
|
("共有・公開の拡充","期限付き共有URL、承認UI、権限の一覧表示"),
|
||||||
|
("図表・記法の追加","Draw.io、nwdiag、ODS、他Wiki記法の取り込み"),
|
||||||
|
("チームの仕事管理","共有タスク、日課、チケット管理、共有アドレス帳"),
|
||||||
|
("さらに情報を集める","IMAP取り込み、他Wiki・外部検索、Linkding連携"),
|
||||||
|
("外部ストレージ","S3互換、WebDAV、SSHFS等との連携"),
|
||||||
|
("用途別の管理機能","料理レシピ、IPアドレス、DNS、資産管理"),
|
||||||
|
("プラグイン・運用の拡充","第三者プラグイン実行、冗長化、自動切替、監視"),
|
||||||
|
("既存機能をもっと使いやすく","検索・大容量データ・同期互換性・モバイルの改善"),
|
||||||
|
]
|
||||||
|
for x,items in [(30,existing),(313,planned)]:
|
||||||
|
for i,(title,detail) in enumerate(items):
|
||||||
|
y=184+i*31
|
||||||
|
p.box(x+2,y-7,6,6,WHITE,LINE,0)
|
||||||
|
p.text(x+16,y,title,9,True)
|
||||||
|
p.text(x+16,y+13,detail,7.8)
|
||||||
|
if i<9: p.line(x,y+20,x+252,y+20,"#e1e7ec")
|
||||||
|
body(p,30,498,["左欄は一部機能を含む実装一覧で、全環境での提供を保証するものではありません。DB構成による制約は技術編へ。",
|
||||||
|
"右欄は設計TODO・既存機能の拡充候補です。実装や提供時期の確約ではなく、優先順位を議論するための一覧です。"],7.2,11)
|
||||||
|
p.line(30,521,565,521)
|
||||||
|
section(p,542,"01","どんな場面で使いたい?")
|
||||||
|
p.text(30,562,"個人メモ / チームの手順書 / プロジェクト / 調査・学習 / 公開ブログ / その他",9)
|
||||||
|
p.text(30,581,"今使っているツールと、そこで困っていることは?",8.6,color=MUTED)
|
||||||
|
p.line(30,601,565,601,LINE)
|
||||||
|
section(p,626,"02","一覧にないものは? 逆に、いらないものは?")
|
||||||
|
p.text(30,646,"外せない機能、つなぎたいサービス、変えたい操作、Wikiに持たせたくない役割。",9)
|
||||||
|
p.line(30,670,565,670,LINE)
|
||||||
|
p.line(30,691,565,691,LINE)
|
||||||
|
section(p,717,"03","一つだけ先に実装するなら?")
|
||||||
|
p.text(30,739,"欲しい機能:",9,True); p.line(91,743,282,743,LINE)
|
||||||
|
p.text(313,739,"解決したい困りごと:",9,True); p.line(408,743,565,743,LINE)
|
||||||
|
p.text(30,771,"機能名だけでなく、「誰が・いつ・何に困るか」を教えてください。",10,True,ACCENT)
|
||||||
|
p.line(30,798,565,798)
|
||||||
|
p.text(30,812,"参照:docs/design/ja/implementation-backlog.md、extensions.md、organizer-dashboard.md、各機能設計書",6.7,color=MUTED)
|
||||||
|
p.text(30,824,"展示・対話用シート。予定には未着手・保留を含みます。一般的なWikiへの要望も、Pages固有の要望も歓迎します。",6.7,color=MUTED)
|
||||||
|
return [(p,0,0)]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# pages
|
||||||
|
|
||||||
|
## 知識の住所と実体を分ける
|
||||||
|
|
||||||
|
Knowledge City Model を持つ知識管理基盤
|
||||||
|
|
||||||
|
技術者向け 5分
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 全体構成
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
単一writerを基本に、保存・表示・外部連携の責務を分ける。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 住所が変わっても同じ知識
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Path、Page UUID、Revision UUID、Document SHA-256は別の役割。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Knowledge Cityによる案内
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
街区から探索し、同じPageを複数の拠点から参照する。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 保存の順序が履歴を守る
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
復元も新しい版として追記する。過去の内容を上書きしない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 同じ知識を複数の形式で利用
|
||||||
|
|
||||||
|
| 正本・状態 | 利用するProjection |
|
||||||
|
| --- | --- |
|
||||||
|
| HTML文書と不変Revision | 閲覧・Markdown編集・印刷・このスライド |
|
||||||
|
| PDF・画像・CSV等の固有形式 | MIMEに応じたビューア・編集アダプタ |
|
||||||
|
| Macro宣言 | 表示時だけ認可済みの一覧や表を展開 |
|
||||||
|
|
||||||
|
表示結果を別の正本にしない。変換で表現できないHTMLは保持する。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 認証と権限を表示まで貫く
|
||||||
|
|
||||||
|
| 判断するもの | 境界 |
|
||||||
|
| --- | --- |
|
||||||
|
| 誰か | OIDC・LDAP・パスワード等でPrincipalを識別 |
|
||||||
|
| 何ができるか | Domain・グループ・Path・Localityの権限 |
|
||||||
|
| 何を公開するか | 上位の公開上限とRevision・範囲ごとの公開 |
|
||||||
|
| 何を実行するか | sanitizer・CSP・sandboxで制限 |
|
||||||
|
|
||||||
|
UUIDやhashを知っていても権限は得られない。検索・City・cacheも認可対象。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Wikiを日々の作業へ接続
|
||||||
|
|
||||||
|
| 入口 | Wikiとの接続 |
|
||||||
|
| --- | --- |
|
||||||
|
| タスク・プロジェクト | 関連Page、作業記録、Pomodoro |
|
||||||
|
| カレンダー・連絡先 | CalDAV・CardDAVの実装プロファイル |
|
||||||
|
| RSS・メール | 明示的なWiki保存・タスク化 |
|
||||||
|
| Web・pages-cli | 同じ業務データを異なる操作環境で利用 |
|
||||||
|
|
||||||
|
外部原本とローカル正本、再取得できるcacheを区別する。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 重い処理と復旧の境界
|
||||||
|
|
||||||
|
- previewや同期は背景キューへ送り、閲覧を優先する
|
||||||
|
- Campusは署名付き設定manifestを配信する。記事複製とは別
|
||||||
|
- 現行基盤はSQLiteとローカル保存、単一writer
|
||||||
|
- 自動HA・外部保存・任意プラグイン実行は後続課題
|
||||||
|
|
||||||
|
現行DRは停止snapshotと、外部fenceを前提とした手動昇格。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## pages の設計上の特色
|
||||||
|
|
||||||
|
**住所が変わっても、知識の実体と履歴を保つ。**
|
||||||
|
|
||||||
|
**街の案内図と多重参照で、複数の文脈から同じ知識へ到達する。**
|
||||||
|
|
||||||
|
**正本・派生データ・権限の境界を、表示や外部連携にも適用する。**
|
||||||
|
|
||||||
|
[設計資料](/lab/pageswiki-dev) [詳細版](/lab/pageswiki-dev/architecture-slides)
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
# pages のアーキテクチャと特色
|
||||||
|
|
||||||
|
Knowledge City Model を持つ知識管理基盤
|
||||||
|
|
||||||
|
技術者向け構成案 2026年11月
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1 扱う課題と設計方針
|
||||||
|
|
||||||
|
- 文書の移動や分類変更で、知識の実体と履歴を分断しない
|
||||||
|
- 同じ知識を、複数の場所・言語・表示形式から利用する
|
||||||
|
- Wikiと日々のタスク・予定・受信情報を関連付ける
|
||||||
|
- 認可、正本、派生データの境界を機能追加後も維持する
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2 論理モデルの全体像
|
||||||
|
|
||||||
|
| 層 | 責務 |
|
||||||
|
| --- | --- |
|
||||||
|
| Campus / Domain | 管理・配置とFQDN・Path名前空間 |
|
||||||
|
| Quartier / Street / Spot | 知識の整理、案内、管理範囲 |
|
||||||
|
| Page / Revision | 安定した実体と不変の履歴 |
|
||||||
|
| Document | SHA-256で識別する内容バイト列 |
|
||||||
|
| Projection | 閲覧、編集、検索、印刷、スライド |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3 住所と実体と内容の分離
|
||||||
|
|
||||||
|
| 識別子 | 意味 | 変更との関係 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Domain + Path | 人が使う住所 | rename・別名追加が可能 |
|
||||||
|
| Page UUID | 知識の実体 | 移動後も維持 |
|
||||||
|
| Revision UUID | 言語を持つ特定の版 | 新しい版を追記 |
|
||||||
|
| Document SHA-256 | 内容の同一性 | 同じバイト列を識別 |
|
||||||
|
|
||||||
|
ハッシュやUUIDを知っていることは、閲覧権限の根拠にならない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4 Knowledge City Model
|
||||||
|
|
||||||
|
Domainを一つの街として扱う。
|
||||||
|
|
||||||
|
| 単位 | 知識の配置例 |
|
||||||
|
| --- | --- |
|
||||||
|
| Quartier 学区・街区 | `/engineering` |
|
||||||
|
| Street 通り | `/engineering/network` |
|
||||||
|
| Spot 拠点 | `/engineering/network/dns` |
|
||||||
|
| Page 文書 | `/engineering/network/dns/runbook` |
|
||||||
|
|
||||||
|
子のPath境界は親の厳密な子孫。同階層のprimary境界は重複を制限する。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5 階層による案内と多重参照
|
||||||
|
|
||||||
|
- primary所属はPath境界から決定する
|
||||||
|
- 同じPageを別のSpotからも参照できる
|
||||||
|
- 参照を追加しても本文・Revision履歴は複製しない
|
||||||
|
- Spotへの所属と、そのPageを読む権限は別に評価する
|
||||||
|
|
||||||
|
例:運用手順を「DNS」と「障害対応」の両方から紹介する。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6 City Mapによる探索
|
||||||
|
|
||||||
|
- Domain全体の街からQuartier・Street・Spotへ拡大する
|
||||||
|
- Spotの周囲にPageを配置し、拠点と文書の関係を示す
|
||||||
|
- Page数を街の規模に反映し、未整理Pageは個別のポイントにする
|
||||||
|
- 検索・Tree・Browserと併用し、地図だけに到達経路を限定しない
|
||||||
|
|
||||||
|
自動整理には手動編集の保護、再試行時の収束、大規模化の残件がある。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7 実行時の構成
|
||||||
|
|
||||||
|
| 実行単位 | 主な役割 |
|
||||||
|
| --- | --- |
|
||||||
|
| Goアプリケーション | HTTP、認証・認可、保存、検索、ジョブ実行 |
|
||||||
|
| SQLite | identity、Revision参照、権限、設定、キュー等 |
|
||||||
|
| ローカルDocument Store | 不変の内容と拡張ごとのファイル正本 |
|
||||||
|
| Adapter Gateway | ホスト型エディタ等への接続 |
|
||||||
|
| 必要な外部サービス | code-server、Excalidraw、Kroki等 |
|
||||||
|
|
||||||
|
内部パッケージの分離は、マイクロサービスへの分割を意味しない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8 文書保存の整合性
|
||||||
|
|
||||||
|
1. 対象・言語・形式と書き込み権限を検証する
|
||||||
|
2. 内容のSHA-256を計算し、Documentを先に永続化する
|
||||||
|
3. DBで期待Revisionと照合し、Revisionと必要な参照を確定する
|
||||||
|
4. 接続済みの変更経路ではoutboxを同じtransactionに記録する
|
||||||
|
|
||||||
|
DBの競合で未参照blobが残る場合はある。内容が存在しないRevisionは確定させない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9 文書とアセットの履歴
|
||||||
|
|
||||||
|
- Revisionは不変。復元も新しいRevisionの追加として扱う
|
||||||
|
- Asset名は編集用の可変HEADとして扱う
|
||||||
|
- 文書保存時にAsset参照を固定ハッシュへ解決する
|
||||||
|
- 過去Revisionの表示を、最新Asset HEADへ追従させない
|
||||||
|
|
||||||
|
GCには現在参照だけでなく、履歴・依存物・保全中データの保護が必要。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10 言語とProjection
|
||||||
|
|
||||||
|
- 言語はRevisionの属性。通常Pathに言語別階層を強制しない
|
||||||
|
- 閲覧時は要求言語とフォールバック方針から版を選ぶ
|
||||||
|
- 編集時は対象言語を明示し、別言語の本文を暗黙に上書きしない
|
||||||
|
- 同じPageを通常表示・RAW・印刷・スライド等で利用する
|
||||||
|
|
||||||
|
文章の正本はHTML。PDFや画像、CSV等の固有形式は元の形式を保持する。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11 エディタの保存と情報保全
|
||||||
|
|
||||||
|
- HTMLとMarkdownを切り替え、プレビューは表示用Projectionを使う
|
||||||
|
- 往復変換で保持できないHTMLは保護ブロックに残す
|
||||||
|
- Macroは編集時に宣言を保持し、表示時に認可済み結果を展開する
|
||||||
|
- 下書き、認証・通信失敗の検知、条件付き保存、競合確認を扱う
|
||||||
|
|
||||||
|
保存時の競合対策と、リアルタイム共同編集は別。共有presence・CRDTは後続課題。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12 認証と認可の境界
|
||||||
|
|
||||||
|
認証器でPrincipalを識別し、Domain membershipと対象操作の権限を別途評価する。
|
||||||
|
|
||||||
|
- パスワード・TOTP、OIDC、LDAP、SMTPマジックリンク
|
||||||
|
- ブラウザCookie、API Bearer、DAV資格情報の用途を分離
|
||||||
|
- グループ・capability・Path・Localityの上限制約を組み合わせる
|
||||||
|
- 閲覧、更新、削除、公開、管理を同一権限として扱わない
|
||||||
|
|
||||||
|
キャッシュやUUID経由の取得でも認可を省略しない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13 公開範囲と匿名ナビゲーション
|
||||||
|
|
||||||
|
- 上位管理者が公開可能な上限を設定し、下位管理者は狭められる
|
||||||
|
- 特定Revisionの公開と、確認済み範囲の自動公開を区別する
|
||||||
|
- children・Tree・Cityも現在読めるPageで絞る
|
||||||
|
- 公開停止や権限失効後に、古いキャッシュから情報を復活させない
|
||||||
|
|
||||||
|
承認運用の完成、依存物の全影響レビュー、期限付き共有URL管理は残件。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14 保存HTMLと実行可能コンテンツ
|
||||||
|
|
||||||
|
- 保存したHTMLを、そのままアプリの権限で実行しない
|
||||||
|
- Viewer・履歴・印刷・Previewに共通の許可リストとCSPを適用する
|
||||||
|
- 外部画像・CSS・JavaScriptは管理方針による明示的な許可を必要とする
|
||||||
|
- スライドやホスト型ツールは、用途ごとのsandbox・sessionで扱う
|
||||||
|
|
||||||
|
原文の保存、閲覧の許可、スクリプトの実行許可は異なる判断。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15 アダプタとシステム拡張
|
||||||
|
|
||||||
|
| 種別 | 対象 | 例 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 連携アダプタ | Documentを開く・編集する | PDF、CSV、Excalidraw、code-server |
|
||||||
|
| システム拡張 | 状態と業務処理を持つ | タスク、予定、RSS、通知 |
|
||||||
|
|
||||||
|
有効化・無効化をデータ削除と分離する。
|
||||||
|
|
||||||
|
現行は信頼済みビルトインが中心。任意の第三者コードを安全に実行する基盤は未完成。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16 Wikiとオーガナイザーの接続
|
||||||
|
|
||||||
|
- タスク・プロジェクトをWiki Pageへ関連付ける
|
||||||
|
- 予定・タスクは共通CalDAV入口、連絡先はCardDAVで外部クライアントと接続する
|
||||||
|
- RSS・メールから、明示的にWikiへ保存・タスク化する
|
||||||
|
- Webとpages-cliで操作し、作業記録や日次メール、ダッシュボードを利用する
|
||||||
|
|
||||||
|
外部サービスの原本、Pages内の正本、表示用cacheを区別する。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 17 拡張ごとの正本
|
||||||
|
|
||||||
|
| 対象 | 正本・権威の所在 |
|
||||||
|
| --- | --- |
|
||||||
|
| Wiki本文 | 不変DocumentとRevision等のDBメタデータ |
|
||||||
|
| カレンダー | manifestと月別ICS。DBは再構築可能な索引 |
|
||||||
|
| FreshRSS連携 | FreshRSS。Pagesはクライアントと表示用cache |
|
||||||
|
| 内蔵RSS | Pagesの購読・既読等の状態 |
|
||||||
|
|
||||||
|
CalDAV・CardDAVは実装プロファイルに制限があり、全クライアントへの完全互換は保証しない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 18 背景処理と前景の優先
|
||||||
|
|
||||||
|
- サムネイル、PDF情報、同期、City再整理等を永続キューで処理する
|
||||||
|
- 優先度、同時実行数、入力・出力、実行時間、再試行を制限する
|
||||||
|
- outboxとconsumer checkpointで接続済みの変更処理を配送する
|
||||||
|
- CPU・メモリ・I/O履歴と実行中ジョブを運用画面で確認する
|
||||||
|
|
||||||
|
配送はat-least-onceを前提とする。分散lease・重み付き予算・全書込経路の接続は残件。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 19 Campusによる設定連携
|
||||||
|
|
||||||
|
- CampusがDomainの配置と管理情報を持つ
|
||||||
|
- DomainのFQDNと配置先インスタンスを分離する
|
||||||
|
- 参加トークンと承認済みインスタンスidentityを使う
|
||||||
|
- 署名・単調sequence付きmanifestを受信側で原子的に適用する
|
||||||
|
|
||||||
|
設定配信は記事の複製・バックアップ・HAではない。Domain間の任意の権限同期も別契約。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 20 運用上の制約と拡張順序
|
||||||
|
|
||||||
|
- 現行の基本はSQLiteとローカル保存、単一writer運用
|
||||||
|
- 複数インスタンスを配置しても共有writerのHAにはならない
|
||||||
|
- DR初版は停止snapshot、検証付き復元、外部fenceを前提とする手動昇格
|
||||||
|
- 次段階は局所取得・索引改善、認可の一貫性、lease、外部保存・HAの順に境界を固める
|
||||||
|
|
||||||
|
RPO・RTO、無停止更新、無損失切替は、復旧訓練と運用条件なしに保証しない。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 補足A 内部コンポーネント
|
||||||
|
|
||||||
|
| 部品 | 役割 |
|
||||||
|
| --- | --- |
|
||||||
|
| Grammaratur | 文書形式変換・情報保全 |
|
||||||
|
| Geduldh | 不変Documentの保存と取得 |
|
||||||
|
| Mestionora | 検索と索引 |
|
||||||
|
| Schutzaria | 権限・公開ポリシー評価 |
|
||||||
|
| Dregarnuhr | ジョブ実行制御 |
|
||||||
|
| Ordoschnellic | 通知配送 |
|
||||||
|
| Kunstzeal | Projection選択と描画provider |
|
||||||
|
| Seheweit | リソース収集と観測 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 補足B 説明時に区別する実装状態
|
||||||
|
|
||||||
|
| 初期実装あり | 設計・後続実装 |
|
||||||
|
| --- | --- |
|
||||||
|
| City Map、URL境界、複数参照 | 全自動整理の整合性と大規模化 |
|
||||||
|
| エディタの下書き・CAS・履歴 | 共有presence・リアルタイム共同編集 |
|
||||||
|
| ビルトイン拡張・ホスト型エディタ | 任意プラグインの隔離実行 |
|
||||||
|
| 匿名表示・公開ルール | 承認フロー全体・Macaroon共有 |
|
||||||
|
| ローカル保存・停止snapshot | S3等の外部保存・自動HA |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 補足C 設計資料
|
||||||
|
|
||||||
|
- [設計思想と責務の分離](/lab/pageswiki-dev/principles)
|
||||||
|
- [アドレス・保存・アセット](/lab/pageswiki-dev/address-storage)
|
||||||
|
- [Knowledge City](/lab/pageswiki-dev/knowledge-city)
|
||||||
|
- [認証・権限と公開](/lab/pageswiki-dev/auth-permissions)
|
||||||
|
- [イベント・リソース監視](/lab/pageswiki-dev/scheduler-resources)
|
||||||
|
- [運用・外部保存・HAとDR](/lab/pageswiki-dev/operations)
|
||||||
|
|
||||||
|
技術詳細と実装残件の索引:`docs/design/ja/index.md`
|
||||||
@@ -14,6 +14,8 @@ require (
|
|||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
filippo.io/edwards25519 v1.1.0 // indirect
|
||||||
|
github.com/go-sql-driver/mysql v1.9.3
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||||
github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=
|
github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=
|
||||||
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||||
@@ -23,6 +25,8 @@ github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoM
|
|||||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||||
github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ=
|
github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ=
|
||||||
github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk=
|
github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk=
|
||||||
|
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
|
||||||
|
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||||
github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df h1:Mwihr/o+v4L5h56rwHLOE20+hh7Okhwno5BHz3zDuao=
|
github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df h1:Mwihr/o+v4L5h56rwHLOE20+hh7Okhwno5BHz3zDuao=
|
||||||
|
|||||||
@@ -28,6 +28,13 @@ type MigrationInspection struct {
|
|||||||
// Pending definitions are a plan, not a successful rehearsal: data-dependent
|
// Pending definitions are a plan, not a successful rehearsal: data-dependent
|
||||||
// DDL and assertions on not-yet-created objects require a disposable DB copy.
|
// DDL and assertions on not-yet-created objects require a disposable DB copy.
|
||||||
func InspectSQLiteMigrations(ctx context.Context, database *sql.DB, plans map[string][]SQLMigration) ([]MigrationInspection, error) {
|
func InspectSQLiteMigrations(ctx context.Context, database *sql.DB, plans map[string][]SQLMigration) ([]MigrationInspection, error) {
|
||||||
|
return InspectSQLiteMigrationsWithOptional(ctx, database, plans, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional components are omitted only when neither a migration record nor any
|
||||||
|
// owned schema object exists. Detection and inspection share one read snapshot;
|
||||||
|
// partial installation or a missing table after installation is never ignored.
|
||||||
|
func InspectSQLiteMigrationsWithOptional(ctx context.Context, database *sql.DB, plans map[string][]SQLMigration, optional map[string][]string) ([]MigrationInspection, error) {
|
||||||
tx, err := database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
tx, err := database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -80,6 +87,19 @@ func InspectSQLiteMigrations(ctx context.Context, database *sql.DB, plans map[st
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
steps, known := plans[name]
|
steps, known := plans[name]
|
||||||
|
if objects, opt := optional[name]; opt && len(history[name]) == 0 && len(objects) > 0 {
|
||||||
|
present := false
|
||||||
|
for _, object := range objects {
|
||||||
|
var exists bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name=?)`, object).Scan(&exists); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
present = present || exists
|
||||||
|
}
|
||||||
|
if !present {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
item := MigrationInspection{Component: name, State: "current", LatestVersion: len(steps)}
|
item := MigrationInspection{Component: name, State: "current", LatestVersion: len(steps)}
|
||||||
for i, step := range steps {
|
for i, step := range steps {
|
||||||
if step.Version != i+1 || step.Name == "" || (len(step.Statements) == 0 && len(step.AddColumns) == 0 && len(step.Assertions) == 0) {
|
if step.Version != i+1 || step.Name == "" || (len(step.Statements) == 0 && len(step.AddColumns) == 0 && len(step.Assertions) == 0) {
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-sql-driver/mysql"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MySQL is currently a component-pilot backend, not a Pages serving backend.
|
||||||
|
// Credentials are instance configuration and must never be logged.
|
||||||
|
type MySQLOptions struct {
|
||||||
|
DSN string
|
||||||
|
AllowInsecure bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func OpenMySQL(ctx context.Context, options MySQLOptions) (*sql.DB, error) {
|
||||||
|
c, e := mysql.ParseDSN(options.DSN)
|
||||||
|
if e != nil || options.DSN == "" {
|
||||||
|
return nil, errors.New("invalid MySQL configuration")
|
||||||
|
}
|
||||||
|
if c.DBName == "" || c.Net != "tcp" || c.MultiStatements || c.AllowAllFiles || c.AllowCleartextPasswords || c.AllowFallbackToPlaintext || len(c.Params) != 0 {
|
||||||
|
return nil, errors.New("unsupported MySQL configuration")
|
||||||
|
}
|
||||||
|
if !options.AllowInsecure && c.TLSConfig != "true" {
|
||||||
|
return nil, errors.New("MySQL requires verified TLS (tls=true)")
|
||||||
|
}
|
||||||
|
c.Timeout = 10 * time.Second
|
||||||
|
c.ReadTimeout = 30 * time.Second
|
||||||
|
c.WriteTimeout = 30 * time.Second
|
||||||
|
c.Collation = "utf8mb4_bin"
|
||||||
|
// Set on EVERY new pooled connection. Relying on a server's permissive
|
||||||
|
// sql_mode can silently truncate identifiers or coerce invalid values.
|
||||||
|
// User-supplied session variables remain rejected above.
|
||||||
|
c.Params = map[string]string{"sql_mode": "'STRICT_ALL_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"}
|
||||||
|
c.Logger = log.New(io.Discard, "", 0)
|
||||||
|
connector, e := mysql.NewConnector(c)
|
||||||
|
if e != nil {
|
||||||
|
return nil, errors.New("invalid MySQL connector configuration")
|
||||||
|
}
|
||||||
|
database := sql.OpenDB(connector)
|
||||||
|
database.SetMaxOpenConns(8)
|
||||||
|
database.SetMaxIdleConns(2)
|
||||||
|
database.SetConnMaxLifetime(10 * time.Minute)
|
||||||
|
ping, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if e = database.PingContext(ping); e != nil {
|
||||||
|
database.Close()
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
return nil, errors.New("MySQL connection failed")
|
||||||
|
}
|
||||||
|
return database, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MySQLOperation is owned SQL, never user input. Check must return exactly one
|
||||||
|
// boolean describing the operation's postcondition. ReplaySafe permits explicit
|
||||||
|
// resume when Check is false; never mark non-idempotent data updates replay-safe.
|
||||||
|
type MySQLOperation struct {
|
||||||
|
SQL, Check string
|
||||||
|
ReplaySafe bool
|
||||||
|
}
|
||||||
|
type MySQLMigration struct {
|
||||||
|
Version int
|
||||||
|
Name string
|
||||||
|
Operations []MySQLOperation
|
||||||
|
Assertions []string
|
||||||
|
}
|
||||||
|
type MySQLMigrationStatus struct {
|
||||||
|
Applied int `json:"applied"`
|
||||||
|
Pending int `json:"pending"`
|
||||||
|
Dirty bool `json:"dirty"`
|
||||||
|
NextOperation int `json:"next_operation"`
|
||||||
|
DirtyComponent string `json:"dirty_component,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var ErrMySQLMigrationDirty = errors.New("MySQL migration interrupted; inspect and explicitly resume")
|
||||||
|
var ErrMySQLMigrationMismatch = errors.New("MySQL migration history or schema mismatch")
|
||||||
|
|
||||||
|
func mysqlMigrationHash(m MySQLMigration) string {
|
||||||
|
b, _ := json.Marshal(m)
|
||||||
|
h := sha256.Sum256(b)
|
||||||
|
return hex.EncodeToString(h[:])
|
||||||
|
}
|
||||||
|
func validateMySQLPlan(component string, steps []MySQLMigration) error {
|
||||||
|
if !regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`).MatchString(component) {
|
||||||
|
return errors.New("invalid MySQL migration component")
|
||||||
|
}
|
||||||
|
for i, s := range steps {
|
||||||
|
if s.Version != i+1 || s.Name == "" || len(s.Name) > 128 || len(s.Operations) == 0 || len(s.Assertions) == 0 {
|
||||||
|
return errors.New("invalid MySQL migration plan")
|
||||||
|
}
|
||||||
|
for _, op := range s.Operations {
|
||||||
|
if strings.TrimSpace(op.SQL) == "" || strings.TrimSpace(op.Check) == "" {
|
||||||
|
return errors.New("missing MySQL operation postcondition")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, assertion := range s.Assertions {
|
||||||
|
if strings.TrimSpace(assertion) == "" {
|
||||||
|
return errors.New("missing MySQL schema assertion")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every operation, including GET_LOCK/RELEASE_LOCK, uses this one connection.
|
||||||
|
// MySQL DDL commits implicitly: a transaction cannot replace this lock/journal.
|
||||||
|
func mysqlMigrationConnection(ctx context.Context, database *sql.DB) (*sql.Conn, func(), error) {
|
||||||
|
c, e := database.Conn(ctx)
|
||||||
|
if e != nil {
|
||||||
|
return nil, nil, errors.New("MySQL migration connection failed")
|
||||||
|
}
|
||||||
|
var name string
|
||||||
|
if e = c.QueryRowContext(ctx, `SELECT DATABASE()`).Scan(&name); e != nil || name == "" {
|
||||||
|
c.Close()
|
||||||
|
return nil, nil, errors.New("MySQL migration database required")
|
||||||
|
}
|
||||||
|
h := sha256.Sum256([]byte(name))
|
||||||
|
key := "pages:migration:" + hex.EncodeToString(h[:20])
|
||||||
|
var locked sql.NullInt64
|
||||||
|
if e = c.QueryRowContext(ctx, `SELECT GET_LOCK(?,10)`, key).Scan(&locked); e != nil || !locked.Valid || locked.Int64 != 1 {
|
||||||
|
// An interrupted lock request may have acquired the session lock.
|
||||||
|
_ = c.Raw(func(any) error { return driver.ErrBadConn })
|
||||||
|
c.Close()
|
||||||
|
return nil, nil, errors.New("MySQL migration lock unavailable")
|
||||||
|
}
|
||||||
|
release := func() {
|
||||||
|
releaseCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
var released sql.NullInt64
|
||||||
|
if e := c.QueryRowContext(releaseCtx, `SELECT RELEASE_LOCK(?)`, key).Scan(&released); e != nil || !released.Valid || released.Int64 != 1 {
|
||||||
|
_ = c.Raw(func(any) error { return driver.ErrBadConn })
|
||||||
|
}
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
return c, release, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mysqlCheck(ctx context.Context, c *sql.Conn, q string) (bool, error) {
|
||||||
|
rows, e := c.QueryContext(ctx, q)
|
||||||
|
if e != nil {
|
||||||
|
return false, errors.New("MySQL schema check failed")
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var yes bool
|
||||||
|
if !rows.Next() {
|
||||||
|
return false, errors.New("MySQL schema check returned no result")
|
||||||
|
}
|
||||||
|
if rows.Scan(&yes) != nil || rows.Next() || rows.Err() != nil {
|
||||||
|
return false, errors.New("invalid MySQL schema check result")
|
||||||
|
}
|
||||||
|
return yes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func inspectMySQLLocked(ctx context.Context, c *sql.Conn, component string, steps []MySQLMigration) (MySQLMigrationStatus, error) {
|
||||||
|
status := MySQLMigrationStatus{Pending: len(steps)}
|
||||||
|
var exists int
|
||||||
|
if e := c.QueryRowContext(ctx, `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations'`).Scan(&exists); e != nil {
|
||||||
|
return status, errors.New("MySQL migration inspection failed")
|
||||||
|
}
|
||||||
|
if exists == 0 {
|
||||||
|
return status, nil
|
||||||
|
}
|
||||||
|
// The journal itself must remain durable and uniquely keyed. Do not repair
|
||||||
|
// a damaged journal automatically, or trust history read from a view.
|
||||||
|
valid, e := mysqlCheck(ctx, c, `SELECT
|
||||||
|
(SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND engine='InnoDB' AND table_type='BASE TABLE')=1
|
||||||
|
AND COALESCE((SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index SEPARATOR ',') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND index_name='PRIMARY'),'')='component,version'
|
||||||
|
AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND is_nullable='NO' AND column_name IN ('component','version','name','checksum','state','next_operation','updated_ms'))=7`)
|
||||||
|
if e != nil {
|
||||||
|
return status, e
|
||||||
|
}
|
||||||
|
if !valid {
|
||||||
|
return status, ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
rows, e := c.QueryContext(ctx, `SELECT version,name,checksum,state,next_operation FROM schema_mysql_migrations WHERE component=? ORDER BY version`, component)
|
||||||
|
if e != nil {
|
||||||
|
return status, errors.New("MySQL migration history unavailable")
|
||||||
|
}
|
||||||
|
seen := 0
|
||||||
|
for rows.Next() {
|
||||||
|
var version, next int
|
||||||
|
var name, hash, state string
|
||||||
|
if rows.Scan(&version, &name, &hash, &state, &next) != nil {
|
||||||
|
rows.Close()
|
||||||
|
return status, ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
if version != seen+1 || version > len(steps) || status.Dirty {
|
||||||
|
rows.Close()
|
||||||
|
return status, ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
s := steps[version-1]
|
||||||
|
if name != s.Name || hash != mysqlMigrationHash(s) || next < 0 || next > len(s.Operations) {
|
||||||
|
rows.Close()
|
||||||
|
return status, ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
switch state {
|
||||||
|
case "applied":
|
||||||
|
if next != len(s.Operations) {
|
||||||
|
rows.Close()
|
||||||
|
return status, ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
status.Applied++
|
||||||
|
case "running":
|
||||||
|
status.Dirty = true
|
||||||
|
status.DirtyComponent = component
|
||||||
|
status.NextOperation = next
|
||||||
|
default:
|
||||||
|
rows.Close()
|
||||||
|
return status, ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
seen++
|
||||||
|
}
|
||||||
|
e = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if e != nil {
|
||||||
|
return status, errors.New("MySQL migration history read failed")
|
||||||
|
}
|
||||||
|
status.Pending = len(steps) - status.Applied
|
||||||
|
// Later migrations may intentionally replace an older schema. Validate only
|
||||||
|
// the latest clean contract, not intermediate versions of a dirty migration.
|
||||||
|
if !status.Dirty && status.Applied > 0 {
|
||||||
|
for _, q := range steps[status.Applied-1].Assertions {
|
||||||
|
ok, e := mysqlCheck(ctx, c, q)
|
||||||
|
if e != nil {
|
||||||
|
return status, e
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return status, ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return status, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inspect is read-only: it never creates the ledger or adopts an existing table.
|
||||||
|
func InspectMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) (MySQLMigrationStatus, error) {
|
||||||
|
if e := validateMySQLPlan(component, steps); e != nil {
|
||||||
|
return MySQLMigrationStatus{}, e
|
||||||
|
}
|
||||||
|
c, release, e := mysqlMigrationConnection(ctx, database)
|
||||||
|
if e != nil {
|
||||||
|
return MySQLMigrationStatus{}, e
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
return inspectMySQLLocked(ctx, c, component, steps)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ApplyMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) error {
|
||||||
|
return applyMySQLMigrations(ctx, database, component, steps, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resume is explicitly separate from normal startup. It does not blindly repeat
|
||||||
|
// a statement: the postcondition must prove success, or ReplaySafe must be set.
|
||||||
|
func ResumeMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) error {
|
||||||
|
return applyMySQLMigrations(ctx, database, component, steps, true)
|
||||||
|
}
|
||||||
|
func applyMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration, resume bool) error {
|
||||||
|
if e := validateMySQLPlan(component, steps); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
c, release, e := mysqlMigrationConnection(ctx, database)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
status, e := inspectMySQLLocked(ctx, c, component, steps)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if status.Dirty && !resume {
|
||||||
|
return ErrMySQLMigrationDirty
|
||||||
|
}
|
||||||
|
_, e = c.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_mysql_migrations(component VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,version BIGINT NOT NULL,name VARCHAR(128) NOT NULL,checksum CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,state VARCHAR(16) NOT NULL,next_operation BIGINT NOT NULL,updated_ms BIGINT NOT NULL,PRIMARY KEY(component,version)) ENGINE=InnoDB`)
|
||||||
|
if e != nil {
|
||||||
|
return errors.New("MySQL migration ledger creation failed")
|
||||||
|
}
|
||||||
|
for _, s := range steps[status.Applied:] {
|
||||||
|
resuming := status.Dirty
|
||||||
|
cursor := 0
|
||||||
|
if resuming {
|
||||||
|
cursor = status.NextOperation
|
||||||
|
} else {
|
||||||
|
// Do not implicitly adopt an already-existing schema with no history.
|
||||||
|
for _, op := range s.Operations {
|
||||||
|
ok, e := mysqlCheck(ctx, c, op.Check)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
return ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, e = c.ExecContext(ctx, `INSERT INTO schema_mysql_migrations(component,version,name,checksum,state,next_operation,updated_ms) VALUES(?,?,?,?,'running',0,?)`, component, s.Version, s.Name, mysqlMigrationHash(s), time.Now().UnixMilli())
|
||||||
|
if e != nil {
|
||||||
|
return errors.New("MySQL migration journal failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := cursor; i < len(s.Operations); i++ {
|
||||||
|
op := s.Operations[i]
|
||||||
|
ok, e := mysqlCheck(ctx, c, op.Check)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
if resuming && i == cursor && !op.ReplaySafe {
|
||||||
|
return ErrMySQLMigrationDirty
|
||||||
|
}
|
||||||
|
if _, e = c.ExecContext(ctx, op.SQL); e != nil {
|
||||||
|
return fmt.Errorf("MySQL migration operation %d failed; journal retained", i+1)
|
||||||
|
}
|
||||||
|
ok, e = mysqlCheck(ctx, c, op.Check)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, e = c.ExecContext(ctx, `UPDATE schema_mysql_migrations SET next_operation=?,updated_ms=? WHERE component=? AND version=?`, i+1, time.Now().UnixMilli(), component, s.Version)
|
||||||
|
if e != nil {
|
||||||
|
return errors.New("MySQL migration progress failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, q := range s.Assertions {
|
||||||
|
ok, e := mysqlCheck(ctx, c, q)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, e = c.ExecContext(ctx, `UPDATE schema_mysql_migrations SET state='applied',updated_ms=? WHERE component=? AND version=?`, time.Now().UnixMilli(), component, s.Version)
|
||||||
|
if e != nil {
|
||||||
|
return errors.New("MySQL migration completion failed")
|
||||||
|
}
|
||||||
|
status.Dirty = false
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestMySQLMigrationPlanValidation(t *testing.T) {
|
||||||
|
valid := func() MySQLMigration {
|
||||||
|
return MySQLMigration{Version: 1, Name: "initial", Operations: []MySQLOperation{{SQL: "CREATE TABLE example(id BIGINT)", Check: "SELECT 0", ReplaySafe: true}}, Assertions: []string{"SELECT 1"}}
|
||||||
|
}
|
||||||
|
if e := validateMySQLPlan("machine-learning", []MySQLMigration{valid()}); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for _, component := range []string{"", "../schema", "has space", "MixedCase"} {
|
||||||
|
if e := validateMySQLPlan(component, []MySQLMigration{valid()}); e == nil {
|
||||||
|
t.Fatal("invalid component accepted", component)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, mutate := range []func(*MySQLMigration){
|
||||||
|
func(m *MySQLMigration) { m.Version = 2 },
|
||||||
|
func(m *MySQLMigration) { m.Name = "" },
|
||||||
|
func(m *MySQLMigration) { m.Operations = nil },
|
||||||
|
func(m *MySQLMigration) { m.Operations[0].SQL = " " },
|
||||||
|
func(m *MySQLMigration) { m.Operations[0].Check = " " },
|
||||||
|
func(m *MySQLMigration) { m.Assertions = nil },
|
||||||
|
func(m *MySQLMigration) { m.Assertions[0] = " " },
|
||||||
|
} {
|
||||||
|
m := valid()
|
||||||
|
mutate(&m)
|
||||||
|
if e := validateMySQLPlan("test", []MySQLMigration{m}); e == nil {
|
||||||
|
t.Fatal("invalid plan accepted", m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
before := valid()
|
||||||
|
after := valid()
|
||||||
|
after.Operations[0].ReplaySafe = false
|
||||||
|
if mysqlMigrationHash(before) == mysqlMigrationHash(after) {
|
||||||
|
t.Fatal("replay policy not covered by checksum")
|
||||||
|
}
|
||||||
|
if mysqlMigrationHash(before) != mysqlMigrationHash(valid()) {
|
||||||
|
t.Fatal("unstable checksum")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMySQLRejectsUnsafeConfiguration(t *testing.T) {
|
||||||
|
for _, dsn := range []string{"", "private-secret@bad", "u:private-secret@tcp(localhost:3306)/pages", "u:p@tcp(localhost:3306)/pages?tls=skip-verify", "u:p@tcp(localhost:3306)/pages?tls=preferred", "u:p@tcp(localhost:3306)/pages?tls=true&multiStatements=true", "u:p@tcp(localhost:3306)/pages?tls=true&allowAllFiles=true", "u:p@tcp(localhost:3306)/pages?tls=true&sql_mode=bad"} {
|
||||||
|
connection, err := OpenMySQL(context.Background(), MySQLOptions{DSN: dsn})
|
||||||
|
if connection != nil {
|
||||||
|
connection.Close()
|
||||||
|
t.Fatal("unexpected connection")
|
||||||
|
}
|
||||||
|
if err == nil || strings.Contains(err.Error(), "private-secret") {
|
||||||
|
t.Fatalf("configuration not safely rejected: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
// Package inspection implements file inspection contracts, not authorization
|
||||||
|
// or a malware scanner. No HTTP route, worker or external service is enabled
|
||||||
|
// by importing it. Callers must load complete, trusted policy snapshots.
|
||||||
|
package inspection
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"path"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrPolicy = errors.New("invalid inspection policy")
|
||||||
|
|
||||||
|
type Mode string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Inherit Mode = "inherit"
|
||||||
|
Disabled Mode = "disabled"
|
||||||
|
Monitor Mode = "monitor"
|
||||||
|
Required Mode = "required"
|
||||||
|
)
|
||||||
|
|
||||||
|
type State string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Pending State = "pending"
|
||||||
|
Clean State = "clean"
|
||||||
|
Suspicious State = "suspicious"
|
||||||
|
Malicious State = "malicious"
|
||||||
|
Error State = "error"
|
||||||
|
Expired State = "expired"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Engine identifies both the executable and its signature/model definitions.
|
||||||
|
// Definitions must change when the engine's detection data changes.
|
||||||
|
type Engine struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
Definitions string `json:"definitions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Engine) valid() bool {
|
||||||
|
return label(e.ID) && label(e.Version) && label(e.Definitions)
|
||||||
|
}
|
||||||
|
func label(s string) bool {
|
||||||
|
return s != "" && len(s) <= 128 && utf8.ValidString(s) && strings.TrimSpace(s) == s && strings.IndexFunc(s, unicode.IsControl) < 0
|
||||||
|
}
|
||||||
|
func validUUID(s string) bool {
|
||||||
|
id, err := uuid.Parse(s)
|
||||||
|
return err == nil && id.String() == s && id != uuid.Nil
|
||||||
|
}
|
||||||
|
func validHash(s string) bool {
|
||||||
|
if len(s) != 64 || strings.ToLower(s) != s {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, err := hex.DecodeString(s)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paths are already-decoded semantic Paths. Literal '%' and '+' are valid;
|
||||||
|
// never percent-decode a second time. Scope tests use segment boundaries.
|
||||||
|
func canonical(p string) bool {
|
||||||
|
return utf8.ValidString(p) && len(p) <= 4096 && strings.HasPrefix(p, "/") && path.Clean(p) == p && !strings.Contains(p, "\\") && strings.IndexFunc(p, unicode.IsControl) < 0
|
||||||
|
}
|
||||||
|
func under(p, root string) bool {
|
||||||
|
return root == "/" || p == root || strings.HasPrefix(p, root+"/")
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rule struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Mode Mode `json:"mode"`
|
||||||
|
Engines []Engine `json:"engines"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Policy is a Domain-local snapshot. Generation must change on policy OR
|
||||||
|
// relevant topology/engine-enable changes. Rules come from authorized locality settings,
|
||||||
|
// not from uploader-controlled data. External consent is Domain-admin owned.
|
||||||
|
type Policy struct {
|
||||||
|
Domain string `json:"domain"`
|
||||||
|
Generation string `json:"generation"`
|
||||||
|
AllowExternal bool `json:"allow_external"`
|
||||||
|
Rules []Rule `json:"rules"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Effective struct {
|
||||||
|
Domain string
|
||||||
|
Generation string
|
||||||
|
Mode Mode
|
||||||
|
AllowExternal bool
|
||||||
|
Engines []Engine
|
||||||
|
}
|
||||||
|
|
||||||
|
func rank(m Mode) int {
|
||||||
|
switch m {
|
||||||
|
case Inherit, Disabled:
|
||||||
|
return 0
|
||||||
|
case Monitor:
|
||||||
|
return 1
|
||||||
|
case Required:
|
||||||
|
return 2
|
||||||
|
default:
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve never weakens an ancestor's mode or drops ancestor engines. A lower
|
||||||
|
// rule can add engines but cannot replace an inherited engine's version.
|
||||||
|
func (p Policy) Resolve(logicalPath string) (Effective, error) {
|
||||||
|
out := Effective{Domain: p.Domain, Generation: p.Generation, Mode: Disabled, AllowExternal: p.AllowExternal}
|
||||||
|
if !validUUID(p.Domain) || !validUUID(p.Generation) || !canonical(logicalPath) || len(p.Rules) > 128 {
|
||||||
|
return Effective{}, ErrPolicy
|
||||||
|
}
|
||||||
|
rules := append([]Rule(nil), p.Rules...)
|
||||||
|
sort.Slice(rules, func(i, j int) bool { return len(rules[i].Path) < len(rules[j].Path) })
|
||||||
|
seen := map[string]bool{}
|
||||||
|
engines := map[string]Engine{}
|
||||||
|
for _, r := range rules {
|
||||||
|
if !canonical(r.Path) || seen[r.Path] || rank(r.Mode) < 0 || len(r.Engines) > 16 || ((r.Mode == Inherit || r.Mode == Disabled) && len(r.Engines) > 0) {
|
||||||
|
return Effective{}, ErrPolicy
|
||||||
|
}
|
||||||
|
seen[r.Path] = true
|
||||||
|
local := map[string]bool{}
|
||||||
|
for _, e := range r.Engines {
|
||||||
|
if !e.valid() || local[e.ID] {
|
||||||
|
return Effective{}, ErrPolicy
|
||||||
|
}
|
||||||
|
local[e.ID] = true
|
||||||
|
}
|
||||||
|
if !under(logicalPath, r.Path) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if rank(r.Mode) > rank(out.Mode) {
|
||||||
|
out.Mode = r.Mode
|
||||||
|
}
|
||||||
|
for _, e := range r.Engines {
|
||||||
|
if old, ok := engines[e.ID]; ok && old != e {
|
||||||
|
return Effective{}, ErrPolicy
|
||||||
|
}
|
||||||
|
engines[e.ID] = e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(engines) > 16 || (out.Mode != Disabled && len(engines) == 0) {
|
||||||
|
return Effective{}, ErrPolicy
|
||||||
|
}
|
||||||
|
for _, e := range engines {
|
||||||
|
out.Engines = append(out.Engines, e)
|
||||||
|
}
|
||||||
|
sort.Slice(out.Engines, func(i, j int) bool { return out.Engines[i].ID < out.Engines[j].ID })
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Key is the minimum cache/job identity. Never reuse a result across Domains,
|
||||||
|
// policy generations, content hashes, or engine/definition versions.
|
||||||
|
type Key struct {
|
||||||
|
Domain string `json:"domain"`
|
||||||
|
Generation string `json:"generation"`
|
||||||
|
Hash string `json:"sha256"`
|
||||||
|
Engine Engine `json:"engine"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (k Key) valid() bool {
|
||||||
|
return validUUID(k.Domain) && validUUID(k.Generation) && validHash(k.Hash) && k.Engine.valid()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Report is trusted worker output, never supplied by an uploader. Publication
|
||||||
|
// must additionally CAS the job lease/generation when persisting this record.
|
||||||
|
type Report struct {
|
||||||
|
Key Key
|
||||||
|
State State
|
||||||
|
Finished time.Time
|
||||||
|
Expires time.Time
|
||||||
|
}
|
||||||
|
type Decision struct {
|
||||||
|
Allowed bool
|
||||||
|
State State
|
||||||
|
Reason string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decide is an ADDITIONAL gate. accessAllowed is the application's existing
|
||||||
|
// ACL/publication decision; an inspection result can never grant that access.
|
||||||
|
// active is a fresh snapshot of enabled engines, not the queued job's snapshot.
|
||||||
|
func Decide(accessAllowed bool, p Effective, hash string, reports []Report, active []Engine, now time.Time) Decision {
|
||||||
|
if !accessAllowed {
|
||||||
|
return Decision{Reason: "access_denied"}
|
||||||
|
}
|
||||||
|
if !validUUID(p.Domain) || !validUUID(p.Generation) || !validHash(hash) || now.IsZero() || rank(p.Mode) < 0 || p.Mode == Inherit || len(p.Engines) > 16 || len(reports) > 64 || len(active) > 64 {
|
||||||
|
return Decision{State: Error, Reason: "invalid_policy"}
|
||||||
|
}
|
||||||
|
if p.Mode == Disabled {
|
||||||
|
return Decision{Allowed: true, Reason: "inspection_disabled"}
|
||||||
|
}
|
||||||
|
if len(p.Engines) == 0 {
|
||||||
|
return Decision{State: Error, Reason: "missing_engine"}
|
||||||
|
}
|
||||||
|
status, reason := Clean, "inspection_clean"
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, e := range p.Engines {
|
||||||
|
if !e.valid() || seen[e.ID] {
|
||||||
|
return Decision{State: Error, Reason: "invalid_policy"}
|
||||||
|
}
|
||||||
|
seen[e.ID] = true
|
||||||
|
key := Key{p.Domain, p.Generation, hash, e}
|
||||||
|
state, why := Pending, "inspection_pending"
|
||||||
|
enabled := false
|
||||||
|
for _, a := range active {
|
||||||
|
if a == e {
|
||||||
|
enabled = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var matches []Report
|
||||||
|
for _, r := range reports {
|
||||||
|
if r.Key == key {
|
||||||
|
matches = append(matches, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !enabled {
|
||||||
|
state, why = Error, "engine_unavailable"
|
||||||
|
} else if len(matches) > 1 {
|
||||||
|
state, why = Error, "ambiguous_result"
|
||||||
|
} else if len(matches) == 1 {
|
||||||
|
r := matches[0]
|
||||||
|
switch r.State {
|
||||||
|
case Pending, Error, Expired:
|
||||||
|
state, why = r.State, "inspection_"+string(r.State)
|
||||||
|
case Clean, Suspicious, Malicious:
|
||||||
|
if r.Finished.IsZero() || r.Finished.After(now) || !r.Expires.After(r.Finished) {
|
||||||
|
state, why = Error, "invalid_result"
|
||||||
|
} else if !r.Expires.After(now) {
|
||||||
|
state, why = Expired, "inspection_expired"
|
||||||
|
} else {
|
||||||
|
state, why = r.State, "inspection_"+string(r.State)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
state, why = Error, "invalid_result"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if severity(state) > severity(status) {
|
||||||
|
status, reason = state, why
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Decision{Allowed: p.Mode == Monitor || status == Clean, State: status, Reason: reason}
|
||||||
|
}
|
||||||
|
func severity(s State) int {
|
||||||
|
switch s {
|
||||||
|
case Clean:
|
||||||
|
return 0
|
||||||
|
case Pending:
|
||||||
|
return 1
|
||||||
|
case Expired:
|
||||||
|
return 2
|
||||||
|
case Error:
|
||||||
|
return 3
|
||||||
|
case Suspicious:
|
||||||
|
return 4
|
||||||
|
case Malicious:
|
||||||
|
return 5
|
||||||
|
}
|
||||||
|
return 3
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecidePaths evaluates all supplied current bindings, not just the requested
|
||||||
|
// alias. The caller must load a complete Domain-local binding snapshot, including
|
||||||
|
// source/dependency policy when appropriate. An empty/truncated set cannot stand
|
||||||
|
// for an unrestricted UUID/Asset. Cross-Domain bindings need a separate decision
|
||||||
|
// per Domain. This method performs no lookup and is not a routing middleware.
|
||||||
|
func DecidePaths(accessAllowed bool, p Policy, bindings []string, hash string, reports []Report, active []Engine, now time.Time) Decision {
|
||||||
|
if !accessAllowed {
|
||||||
|
return Decision{Reason: "access_denied"}
|
||||||
|
}
|
||||||
|
if len(bindings) == 0 || len(bindings) > 128 {
|
||||||
|
return Decision{State: Error, Reason: "incomplete_bindings"}
|
||||||
|
}
|
||||||
|
decision := Decision{Allowed: true, Reason: "inspection_disabled"}
|
||||||
|
for _, binding := range bindings {
|
||||||
|
effective, err := p.Resolve(binding)
|
||||||
|
if err != nil {
|
||||||
|
return Decision{State: Error, Reason: "invalid_policy"}
|
||||||
|
}
|
||||||
|
next := Decide(true, effective, hash, reports, active, now)
|
||||||
|
if !next.Allowed {
|
||||||
|
return next
|
||||||
|
}
|
||||||
|
if next.State != "" && (decision.State == "" || severity(next.State) > severity(decision.State)) {
|
||||||
|
decision = next
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return decision
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package inspection
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const domain = "00000000-0000-4000-8000-000000000001"
|
||||||
|
const generation = "00000000-0000-4000-8000-000000000002"
|
||||||
|
|
||||||
|
var engine = Engine{"test.local", "1", "definitions-1"}
|
||||||
|
|
||||||
|
func TestPolicyInheritance(t *testing.T) {
|
||||||
|
p := Policy{Domain: domain, Generation: generation, Rules: []Rule{
|
||||||
|
{Path: "/private", Mode: Required, Engines: []Engine{engine}},
|
||||||
|
{Path: "/private/child", Mode: Disabled},
|
||||||
|
{Path: "/private/child/deep", Mode: Inherit},
|
||||||
|
}}
|
||||||
|
for _, path := range []string{"/private", "/private/child", "/private/child/deep/page"} {
|
||||||
|
e, err := p.Resolve(path)
|
||||||
|
if err != nil || e.Mode != Required || len(e.Engines) != 1 || e.Engines[0] != engine {
|
||||||
|
t.Fatalf("inherit %q: %+v %v", path, e, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, path := range []string{"/", "/private2/page", "/private_%/page"} {
|
||||||
|
e, err := p.Resolve(path)
|
||||||
|
if err != nil || e.Mode != Disabled {
|
||||||
|
t.Fatalf("scope %q: %+v %v", path, e, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.Rules = append(p.Rules, Rule{Path: "/private/child/deep/page", Mode: Required, Engines: []Engine{{"test.second", "1", "defs"}}})
|
||||||
|
e, err := p.Resolve("/private/child/deep/page")
|
||||||
|
if err != nil || len(e.Engines) != 2 {
|
||||||
|
t.Fatal("child dropped ancestor engine", e, err)
|
||||||
|
}
|
||||||
|
p.Rules[3].Engines = []Engine{{engine.ID, "2", engine.Definitions}}
|
||||||
|
if _, err := p.Resolve("/private/child/deep/page"); err == nil {
|
||||||
|
t.Fatal("child replaced required engine")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPolicyValidationAndExactPaths(t *testing.T) {
|
||||||
|
for _, path := range []string{"/日本語/100%+完了", "/a/%2e%2e/b", "/a_b/page"} {
|
||||||
|
p := Policy{Domain: domain, Generation: generation, Rules: []Rule{{Path: path, Mode: Required, Engines: []Engine{engine}}}}
|
||||||
|
if e, err := p.Resolve(path + "/child"); err != nil || e.Mode != Required {
|
||||||
|
t.Fatal(path, e, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, path := range []string{"", "relative", "/a/../b", "/a//b", "/a/", "/a\\b", "/a\x00b", "/\xff", "/" + strings.Repeat("a", 4096)} {
|
||||||
|
if _, err := (Policy{Domain: domain, Generation: generation}).Resolve(path); err == nil {
|
||||||
|
t.Fatalf("invalid path %q", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, rules := range [][]Rule{
|
||||||
|
{{Path: "/", Mode: "unknown"}},
|
||||||
|
{{Path: "/", Mode: Required}},
|
||||||
|
{{Path: "/", Mode: Inherit, Engines: []Engine{engine}}},
|
||||||
|
{{Path: "/", Mode: Monitor, Engines: []Engine{engine, engine}}},
|
||||||
|
{{Path: "/", Mode: Disabled}, {Path: "/", Mode: Disabled}},
|
||||||
|
} {
|
||||||
|
if _, err := (Policy{Domain: domain, Generation: generation, Rules: rules}).Resolve("/p"); err == nil {
|
||||||
|
t.Fatal("invalid policy accepted", rules)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := (Policy{}).Resolve("/"); err == nil {
|
||||||
|
t.Fatal("missing snapshot accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecisionCannotGrantAccess(t *testing.T) {
|
||||||
|
p := Effective{Domain: domain, Generation: generation, Mode: Required, Engines: []Engine{engine}}
|
||||||
|
hash := strings.Repeat("a", 64)
|
||||||
|
now := time.Unix(1000, 0)
|
||||||
|
good := Report{Key: Key{domain, generation, hash, engine}, State: Clean, Finished: now.Add(-time.Second), Expires: now.Add(time.Hour)}
|
||||||
|
for _, mode := range []Mode{Disabled, Monitor, Required} {
|
||||||
|
p.Mode = mode
|
||||||
|
if d := Decide(false, p, hash, []Report{good}, []Engine{engine}, now); d.Allowed || d.Reason != "access_denied" {
|
||||||
|
t.Fatal(d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.Mode = Required
|
||||||
|
if d := Decide(true, p, hash, []Report{good}, []Engine{engine}, now); !d.Allowed || d.State != Clean {
|
||||||
|
t.Fatal(d)
|
||||||
|
}
|
||||||
|
for _, state := range []State{Pending, Suspicious, Malicious, Error, Expired, "unknown"} {
|
||||||
|
r := good
|
||||||
|
r.State = state
|
||||||
|
if d := Decide(true, p, hash, []Report{r}, []Engine{engine}, now); d.Allowed {
|
||||||
|
t.Fatal(state, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, mutate := range []func(*Report){
|
||||||
|
func(r *Report) { r.Key.Domain = generation },
|
||||||
|
func(r *Report) { r.Key.Generation = domain },
|
||||||
|
func(r *Report) { r.Key.Hash = strings.Repeat("b", 64) },
|
||||||
|
func(r *Report) { r.Key.Engine.Definitions = "new" },
|
||||||
|
func(r *Report) { r.Expires = now },
|
||||||
|
func(r *Report) { r.Finished = now.Add(time.Hour) },
|
||||||
|
} {
|
||||||
|
r := good
|
||||||
|
mutate(&r)
|
||||||
|
if d := Decide(true, p, hash, []Report{r}, []Engine{engine}, now); d.Allowed {
|
||||||
|
t.Fatal("stale/wrong evidence accepted", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d := Decide(true, p, hash, []Report{good}, nil, now); d.Allowed || d.Reason != "engine_unavailable" {
|
||||||
|
t.Fatal(d)
|
||||||
|
}
|
||||||
|
if d := Decide(true, p, hash, []Report{good, good}, []Engine{engine}, now); d.Allowed {
|
||||||
|
t.Fatal("ambiguous evidence", d)
|
||||||
|
}
|
||||||
|
p.Mode = Monitor
|
||||||
|
bad := good
|
||||||
|
bad.State = Malicious
|
||||||
|
if d := Decide(true, p, hash, []Report{bad}, []Engine{engine}, now); !d.Allowed || d.State != Malicious {
|
||||||
|
t.Fatal("monitor changed access or hid verdict", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEveryRequiredEngineMustPass(t *testing.T) {
|
||||||
|
second := Engine{"test.second", "1", "defs"}
|
||||||
|
now := time.Now()
|
||||||
|
hash := strings.Repeat("b", 64)
|
||||||
|
p := Effective{Domain: domain, Generation: generation, Mode: Required, Engines: []Engine{engine, second}}
|
||||||
|
r := Report{Key: Key{domain, generation, hash, engine}, State: Clean, Finished: now.Add(-time.Second), Expires: now.Add(time.Minute)}
|
||||||
|
if d := Decide(true, p, hash, []Report{r}, []Engine{engine, second}, now); d.Allowed {
|
||||||
|
t.Fatal(d)
|
||||||
|
}
|
||||||
|
r2 := r
|
||||||
|
r2.Key.Engine = second
|
||||||
|
if d := Decide(true, p, hash, []Report{r, r2}, []Engine{engine, second}, now); !d.Allowed {
|
||||||
|
t.Fatal(d)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
package inspection
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/geduldh"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUnavailable = errors.New("inspection engine unavailable or changed")
|
||||||
|
ErrExternal = errors.New("external inspection is not permitted")
|
||||||
|
ErrBusy = errors.New("inspection capacity exhausted")
|
||||||
|
ErrInput = errors.New("inspection input invalid or too large")
|
||||||
|
ErrEngine = errors.New("inspection engine failed")
|
||||||
|
)
|
||||||
|
|
||||||
|
type Manifest struct {
|
||||||
|
Engine Engine
|
||||||
|
External bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scanner implementations are trusted, registered by application code. A
|
||||||
|
// manifest is not permission to run a command, import code or connect a URL.
|
||||||
|
// Inspect must honor ctx; in-process plugins are NOT a process sandbox.
|
||||||
|
// The reader is valid only during Inspect and contains no Path or credential.
|
||||||
|
type Scanner interface {
|
||||||
|
Inspect(context.Context, io.Reader) (State, error)
|
||||||
|
}
|
||||||
|
type registration struct {
|
||||||
|
manifest Manifest
|
||||||
|
scanner Scanner
|
||||||
|
enabled bool
|
||||||
|
epoch uint64
|
||||||
|
}
|
||||||
|
type Registry struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
entries map[string]registration
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRegistry() *Registry { return &Registry{entries: map[string]registration{}} }
|
||||||
|
|
||||||
|
// Register always starts disabled. Changing a definition version requires a
|
||||||
|
// new registry registration/application lifecycle, never an in-place mutation.
|
||||||
|
func (r *Registry) Register(m Manifest, scanner Scanner) error {
|
||||||
|
if !m.Engine.valid() || scanner == nil {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
if _, ok := r.entries[m.Engine.ID]; ok {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
if len(r.entries) >= 64 {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
if r.entries == nil {
|
||||||
|
r.entries = map[string]registration{}
|
||||||
|
}
|
||||||
|
r.entries[m.Engine.ID] = registration{manifest: m, scanner: scanner}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (r *Registry) SetEnabled(id string, enabled bool) error {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
e, ok := r.entries[id]
|
||||||
|
if !ok {
|
||||||
|
return ErrUnavailable
|
||||||
|
}
|
||||||
|
if e.enabled != enabled {
|
||||||
|
e.epoch++
|
||||||
|
e.enabled = enabled
|
||||||
|
r.entries[id] = e
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (r *Registry) Active() []Engine {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
var out []Engine
|
||||||
|
for _, e := range r.entries {
|
||||||
|
if e.enabled {
|
||||||
|
out = append(out, e.manifest.Engine)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
func (r *Registry) acquire(engine Engine) (registration, error) {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
e, ok := r.entries[engine.ID]
|
||||||
|
if !ok || !e.enabled || e.manifest.Engine != engine {
|
||||||
|
return registration{}, ErrUnavailable
|
||||||
|
}
|
||||||
|
return e, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type Limits struct {
|
||||||
|
Workers int
|
||||||
|
MaxBytes int64
|
||||||
|
Timeout time.Duration
|
||||||
|
ResultTTL time.Duration
|
||||||
|
}
|
||||||
|
type Metrics struct {
|
||||||
|
Running int64
|
||||||
|
Completed uint64
|
||||||
|
Failed uint64
|
||||||
|
BytesVerified uint64
|
||||||
|
DurationNS uint64
|
||||||
|
}
|
||||||
|
type Runner struct {
|
||||||
|
registry *Registry
|
||||||
|
limits Limits
|
||||||
|
slots chan struct{}
|
||||||
|
running atomic.Int64
|
||||||
|
completed atomic.Uint64
|
||||||
|
failed atomic.Uint64
|
||||||
|
bytes atomic.Uint64
|
||||||
|
duration atomic.Uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRunner(registry *Registry, limits Limits) (*Runner, error) {
|
||||||
|
if registry == nil || limits.Workers < 1 || limits.Workers > 4 || limits.MaxBytes < 1 || limits.MaxBytes > 256<<20 || limits.Timeout <= 0 || limits.Timeout > time.Minute || limits.ResultTTL <= 0 || limits.ResultTTL > 24*time.Hour {
|
||||||
|
return nil, ErrPolicy
|
||||||
|
}
|
||||||
|
return &Runner{registry: registry, limits: limits, slots: make(chan struct{}, limits.Workers)}, nil
|
||||||
|
}
|
||||||
|
func (r *Runner) Metrics() Metrics {
|
||||||
|
return Metrics{r.running.Load(), r.completed.Load(), r.failed.Load(), r.bytes.Load(), r.duration.Load()}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recheck reloads current job ownership, policy generation, topology and
|
||||||
|
// external-transmission consent. It runs before opening bytes and again before
|
||||||
|
// returning a report. The persistence layer must still CAS the lease/generation
|
||||||
|
// on commit; this callback is not an atomic database transaction.
|
||||||
|
type Recheck func(context.Context, Key) error
|
||||||
|
|
||||||
|
// Run is for a background worker, never a synchronous HTTP request. Capacity
|
||||||
|
// exhaustion returns immediately so the existing scheduler can defer the job.
|
||||||
|
// Documents must satisfy Geduldh's immutable Store contract. Verify before
|
||||||
|
// handing bytes to a scanner (especially an external service).
|
||||||
|
func (r *Runner) Run(ctx context.Context, documents geduldh.Store, key Key, allowExternal bool, recheck Recheck) (report Report, err error) {
|
||||||
|
if !key.valid() || documents == nil || recheck == nil {
|
||||||
|
return Report{}, ErrInput
|
||||||
|
}
|
||||||
|
if err = ctx.Err(); err != nil {
|
||||||
|
return Report{}, err
|
||||||
|
}
|
||||||
|
entry, err := r.registry.acquire(key.Engine)
|
||||||
|
if err != nil {
|
||||||
|
return Report{}, err
|
||||||
|
}
|
||||||
|
if entry.manifest.External && !allowExternal {
|
||||||
|
return Report{}, ErrExternal
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case r.slots <- struct{}{}:
|
||||||
|
default:
|
||||||
|
return Report{}, ErrBusy
|
||||||
|
}
|
||||||
|
start := time.Now()
|
||||||
|
r.running.Add(1)
|
||||||
|
defer func() {
|
||||||
|
// Never leak a plugin panic or diagnostic (which may contain payloads).
|
||||||
|
if recover() != nil {
|
||||||
|
report = Report{}
|
||||||
|
err = ErrEngine
|
||||||
|
}
|
||||||
|
r.running.Add(-1)
|
||||||
|
<-r.slots
|
||||||
|
r.duration.Add(uint64(time.Since(start)))
|
||||||
|
if err != nil {
|
||||||
|
report = Report{}
|
||||||
|
r.failed.Add(1)
|
||||||
|
} else {
|
||||||
|
r.completed.Add(1)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, r.limits.Timeout)
|
||||||
|
defer cancel()
|
||||||
|
check := func() error {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
current, err := r.registry.acquire(key.Engine)
|
||||||
|
if err != nil || current.epoch != entry.epoch {
|
||||||
|
return ErrUnavailable
|
||||||
|
}
|
||||||
|
if recheck(ctx, key) != nil {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return ErrUnavailable
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err = check(); err != nil {
|
||||||
|
return Report{}, err
|
||||||
|
}
|
||||||
|
info, err := documents.Stat(ctx, key.Hash)
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return Report{}, ctx.Err()
|
||||||
|
}
|
||||||
|
if err != nil || info.Hash != key.Hash || info.Size < 0 || info.Size > r.limits.MaxBytes {
|
||||||
|
return Report{}, ErrInput
|
||||||
|
}
|
||||||
|
reader, err := documents.Open(ctx, key.Hash)
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return Report{}, ctx.Err()
|
||||||
|
}
|
||||||
|
return Report{}, ErrInput
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
hash := sha256.New()
|
||||||
|
n, err := io.Copy(hash, io.LimitReader(contextReader{ctx, reader}, info.Size+1))
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return Report{}, ctx.Err()
|
||||||
|
}
|
||||||
|
return Report{}, ErrInput
|
||||||
|
}
|
||||||
|
if n != info.Size || hex.EncodeToString(hash.Sum(nil)) != key.Hash {
|
||||||
|
return Report{}, ErrInput
|
||||||
|
}
|
||||||
|
r.bytes.Add(uint64(n))
|
||||||
|
if _, err = reader.Seek(0, io.SeekStart); err != nil {
|
||||||
|
return Report{}, ErrInput
|
||||||
|
}
|
||||||
|
if err = check(); err != nil {
|
||||||
|
return Report{}, err
|
||||||
|
}
|
||||||
|
state, err := entry.scanner.Inspect(ctx, io.LimitReader(contextReader{ctx, reader}, info.Size))
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return Report{}, ctx.Err()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return Report{}, ErrEngine
|
||||||
|
}
|
||||||
|
if state != Clean && state != Suspicious && state != Malicious {
|
||||||
|
return Report{}, ErrEngine
|
||||||
|
}
|
||||||
|
if err = check(); err != nil {
|
||||||
|
return Report{}, err
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
return Report{Key: key, State: state, Finished: now, Expires: now.Add(r.limits.ResultTTL)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type contextReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
reader io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r contextReader) Read(b []byte) (int, error) {
|
||||||
|
if err := r.ctx.Err(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return r.reader.Read(b)
|
||||||
|
}
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
package inspection
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"pageswiki/internal/geduldh"
|
||||||
|
)
|
||||||
|
|
||||||
|
type scanFunc func(context.Context, io.Reader) (State, error)
|
||||||
|
|
||||||
|
func (f scanFunc) Inspect(ctx context.Context, r io.Reader) (State, error) { return f(ctx, r) }
|
||||||
|
|
||||||
|
type testReader struct{ *bytes.Reader }
|
||||||
|
|
||||||
|
func (*testReader) Close() error { return nil }
|
||||||
|
|
||||||
|
type testDocuments struct {
|
||||||
|
payload []byte
|
||||||
|
size int64
|
||||||
|
opens atomic.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *testDocuments) Stat(_ context.Context, h string) (geduldh.Info, error) {
|
||||||
|
return geduldh.Info{Hash: h, Size: d.size}, nil
|
||||||
|
}
|
||||||
|
func (d *testDocuments) Open(context.Context, string) (geduldh.Reader, error) {
|
||||||
|
d.opens.Add(1)
|
||||||
|
return &testReader{bytes.NewReader(d.payload)}, nil
|
||||||
|
}
|
||||||
|
func (*testDocuments) Verify(context.Context, string) error {
|
||||||
|
panic("runner must verify the bytes itself")
|
||||||
|
}
|
||||||
|
func (*testDocuments) PutIfAbsent(context.Context, string, int64, io.Reader) error {
|
||||||
|
panic("runner must never modify documents")
|
||||||
|
}
|
||||||
|
func fixture(t *testing.T, external bool, fn scanFunc) (*Runner, *Registry, *testDocuments, Key) {
|
||||||
|
t.Helper()
|
||||||
|
reg := NewRegistry()
|
||||||
|
if err := reg.Register(Manifest{engine, external}, fn); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r, err := NewRunner(reg, Limits{Workers: 1, MaxBytes: 1024, Timeout: time.Second, ResultTTL: time.Hour})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body := []byte("synthetic input, not a real user document")
|
||||||
|
sum := sha256.Sum256(body)
|
||||||
|
return r, reg, &testDocuments{payload: body, size: int64(len(body))}, Key{domain, generation, hex.EncodeToString(sum[:]), engine}
|
||||||
|
}
|
||||||
|
func current(context.Context, Key) error { return nil }
|
||||||
|
|
||||||
|
func TestRunnerDisabledExternalAndHashGates(t *testing.T) {
|
||||||
|
var calls atomic.Int64
|
||||||
|
r, reg, docs, key := fixture(t, true, func(ctx context.Context, reader io.Reader) (State, error) {
|
||||||
|
calls.Add(1)
|
||||||
|
_, err := io.Copy(io.Discard, reader)
|
||||||
|
return Clean, err
|
||||||
|
})
|
||||||
|
if _, err := r.Run(context.Background(), docs, key, true, current); !errors.Is(err, ErrUnavailable) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := reg.SetEnabled(engine.ID, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.Run(context.Background(), docs, key, false, current); !errors.Is(err, ErrExternal) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if docs.opens.Load() != 0 || calls.Load() != 0 {
|
||||||
|
t.Fatal("read before consent")
|
||||||
|
}
|
||||||
|
bad := key
|
||||||
|
bad.Hash = strings.Repeat("a", 64)
|
||||||
|
if _, err := r.Run(context.Background(), docs, bad, true, current); !errors.Is(err, ErrInput) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if calls.Load() != 0 {
|
||||||
|
t.Fatal("corrupt content sent to plugin")
|
||||||
|
}
|
||||||
|
report, err := r.Run(context.Background(), docs, key, true, current)
|
||||||
|
if err != nil || report.State != Clean || report.Key != key || calls.Load() != 1 || !report.Expires.After(report.Finished) {
|
||||||
|
t.Fatal(report, err)
|
||||||
|
}
|
||||||
|
m := r.Metrics()
|
||||||
|
if m.Completed != 1 || m.Failed != 1 || m.Running != 0 || m.BytesVerified != uint64(docs.size) {
|
||||||
|
t.Fatal(m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunnerCapacityAndDisableDuringScan(t *testing.T) {
|
||||||
|
started, release := make(chan struct{}), make(chan struct{})
|
||||||
|
r, reg, docs, key := fixture(t, false, func(ctx context.Context, reader io.Reader) (State, error) {
|
||||||
|
close(started)
|
||||||
|
<-release
|
||||||
|
return Clean, nil
|
||||||
|
})
|
||||||
|
if err := reg.SetEnabled(engine.ID, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { _, err := r.Run(context.Background(), docs, key, false, current); done <- err }()
|
||||||
|
<-started
|
||||||
|
_, busy := r.Run(context.Background(), docs, key, false, current)
|
||||||
|
_ = reg.SetEnabled(engine.ID, false)
|
||||||
|
_ = reg.SetEnabled(engine.ID, true) // Even an immediate toggle invalidates this run.
|
||||||
|
close(release)
|
||||||
|
err := <-done
|
||||||
|
if !errors.Is(busy, ErrBusy) || !errors.Is(err, ErrUnavailable) {
|
||||||
|
t.Fatal(busy, err)
|
||||||
|
}
|
||||||
|
if m := r.Metrics(); m.Running != 0 || m.Completed != 0 || m.Failed != 1 {
|
||||||
|
t.Fatal(m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunnerBoundedFailureAndRecheck(t *testing.T) {
|
||||||
|
for _, kind := range []string{"panic", "error", "invalid", "timeout", "stale", "oversize", "wrong-size"} {
|
||||||
|
t.Run(kind, func(t *testing.T) {
|
||||||
|
var calls atomic.Int64
|
||||||
|
r, reg, docs, key := fixture(t, false, func(ctx context.Context, _ io.Reader) (State, error) {
|
||||||
|
calls.Add(1)
|
||||||
|
switch kind {
|
||||||
|
case "panic":
|
||||||
|
panic("private document text")
|
||||||
|
case "error":
|
||||||
|
return Clean, errors.New("private text")
|
||||||
|
case "invalid":
|
||||||
|
return Pending, nil
|
||||||
|
case "timeout":
|
||||||
|
<-ctx.Done()
|
||||||
|
return Clean, nil
|
||||||
|
}
|
||||||
|
return Clean, nil
|
||||||
|
})
|
||||||
|
_ = reg.SetEnabled(engine.ID, true)
|
||||||
|
if kind == "oversize" {
|
||||||
|
docs.size = 1025
|
||||||
|
}
|
||||||
|
if kind == "wrong-size" {
|
||||||
|
docs.size--
|
||||||
|
}
|
||||||
|
if kind == "timeout" {
|
||||||
|
r.limits.Timeout = 10 * time.Millisecond
|
||||||
|
}
|
||||||
|
checks := 0
|
||||||
|
recheck := func(context.Context, Key) error {
|
||||||
|
checks++
|
||||||
|
if kind == "stale" && checks == 3 {
|
||||||
|
return errors.New("private policy")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
report, err := r.Run(context.Background(), docs, key, false, recheck)
|
||||||
|
if err == nil || strings.Contains(err.Error(), "private") || report != (Report{}) {
|
||||||
|
t.Fatal(report, err)
|
||||||
|
}
|
||||||
|
if (kind == "oversize" || kind == "wrong-size") && calls.Load() != 0 {
|
||||||
|
t.Fatal("invalid data reached plugin")
|
||||||
|
}
|
||||||
|
if kind == "timeout" && !errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if r.Metrics().Running != 0 {
|
||||||
|
t.Fatal("worker slot leaked")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunnerRequiresFreshSnapshot(t *testing.T) {
|
||||||
|
r, reg, docs, key := fixture(t, false, func(context.Context, io.Reader) (State, error) { t.Fatal("plugin called"); return Clean, nil })
|
||||||
|
_ = reg.SetEnabled(engine.ID, true)
|
||||||
|
if _, err := r.Run(context.Background(), docs, key, false, nil); !errors.Is(err, ErrInput) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.Run(context.Background(), docs, key, false, func(context.Context, Key) error { return ErrPolicy }); !errors.Is(err, ErrUnavailable) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if _, err := r.Run(ctx, docs, key, false, current); !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if docs.opens.Load() != 0 {
|
||||||
|
t.Fatal("stale job opened payload")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInspectionLifecycleDoesNotPublishOrBypassAliases(t *testing.T) {
|
||||||
|
r, registry, docs, key := fixture(t, false, func(_ context.Context, reader io.Reader) (State, error) {
|
||||||
|
_, err := io.Copy(io.Discard, reader)
|
||||||
|
return Clean, err
|
||||||
|
})
|
||||||
|
p := Policy{Domain: domain, Generation: generation, Rules: []Rule{{Path: "/private", Mode: Required, Engines: []Engine{engine}}}}
|
||||||
|
bindings := []string{"/open/alias", "/private/source"}
|
||||||
|
gate := func(acl bool, reports []Report) Decision {
|
||||||
|
return DecidePaths(acl, p, bindings, key.Hash, reports, registry.Active(), time.Now())
|
||||||
|
}
|
||||||
|
_ = registry.SetEnabled(engine.ID, true)
|
||||||
|
if d := gate(true, nil); d.Allowed || d.State != Pending {
|
||||||
|
t.Fatal("unscanned alias allowed", d)
|
||||||
|
}
|
||||||
|
report, err := r.Run(context.Background(), docs, key, false, current)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if d := gate(true, []Report{report}); !d.Allowed {
|
||||||
|
t.Fatal(d)
|
||||||
|
}
|
||||||
|
if d := gate(false, []Report{report}); d.Allowed {
|
||||||
|
t.Fatal("scan published private file", d)
|
||||||
|
}
|
||||||
|
_ = registry.SetEnabled(engine.ID, false)
|
||||||
|
if d := gate(true, []Report{report}); d.Allowed {
|
||||||
|
t.Fatal("disabled plugin bypass", d)
|
||||||
|
}
|
||||||
|
_ = registry.SetEnabled(engine.ID, true)
|
||||||
|
p.Generation = "00000000-0000-4000-8000-000000000003"
|
||||||
|
if d := gate(true, []Report{report}); d.Allowed {
|
||||||
|
t.Fatal("stale policy result", d)
|
||||||
|
}
|
||||||
|
if d := DecidePaths(true, p, nil, key.Hash, nil, registry.Active(), time.Now()); d.Allowed {
|
||||||
|
t.Fatal("missing bindings accepted", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
// Package machinelearning implements the private Pages Machine Learning v1
|
||||||
|
// transport. Callers must authorize corpus scope and external transmission,
|
||||||
|
// enqueue work, and recheck revision/policy generations before persisting results.
|
||||||
|
// This package does not discover documents, retry requests, or change City paths.
|
||||||
|
package machinelearning
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxBody = 128 * 1024
|
||||||
|
const maxResponse = 2 * 1024 * 1024
|
||||||
|
|
||||||
|
var safeToken = regexp.MustCompile(`^[A-Za-z0-9_-]{32,256}$`)
|
||||||
|
var safeID = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`)
|
||||||
|
var modelHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
||||||
|
|
||||||
|
type Input struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
Protocol string `json:"protocol"`
|
||||||
|
DomainUUID string `json:"domain_uuid"`
|
||||||
|
ScopeUUID string `json:"scope_uuid"`
|
||||||
|
Provider string `json:"provider"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
Dimensions int `json:"dimensions"`
|
||||||
|
Inputs []Input `json:"inputs"`
|
||||||
|
AllowExternal bool `json:"allow_external"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Output struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
InputSHA256 string `json:"input_sha256"`
|
||||||
|
Vector []float64 `json:"vector"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Protocol string `json:"protocol"`
|
||||||
|
DomainUUID string `json:"domain_uuid"`
|
||||||
|
ScopeUUID string `json:"scope_uuid"`
|
||||||
|
Provider string `json:"provider"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
ModelRevision string `json:"model_revision"`
|
||||||
|
Dimensions int `json:"dimensions"`
|
||||||
|
Tokenizer string `json:"tokenizer"`
|
||||||
|
Outputs []Output `json:"outputs"`
|
||||||
|
Usage struct {
|
||||||
|
TotalTokens int64 `json:"total_tokens"`
|
||||||
|
} `json:"usage"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StatusError intentionally excludes the remote response body and request URL.
|
||||||
|
// Retry scheduling belongs to Pages; failures can include uncertain API charges.
|
||||||
|
type StatusError struct{ Status int }
|
||||||
|
|
||||||
|
func (e *StatusError) Error() string { return fmt.Sprintf("machine learning HTTP status %d", e.Status) }
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
endpoint string
|
||||||
|
token string
|
||||||
|
http *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewClient accepts an operator-configured private service origin, never a
|
||||||
|
// document-provided URL. HTTP is for an isolated local network only; use HTTPS
|
||||||
|
// and network access control for remote hosts. There is no insecure TLS option.
|
||||||
|
func NewClient(origin, token string) (*Client, error) {
|
||||||
|
u, err := url.Parse(origin)
|
||||||
|
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || !safeToken.MatchString(token) {
|
||||||
|
return nil, errors.New("invalid machine learning service configuration")
|
||||||
|
}
|
||||||
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||||
|
transport.Proxy = nil // Do not leak the private shared token to an env proxy.
|
||||||
|
return &Client{endpoint: strings.TrimSuffix(origin, "/") + "/v1/embeddings", token: token,
|
||||||
|
http: &http.Client{Transport: transport, Timeout: 40 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validUUID(s string) bool { id, err := uuid.Parse(s); return err == nil && id.String() == s }
|
||||||
|
|
||||||
|
func validate(req Request) error {
|
||||||
|
if req.Protocol != "1" || !validUUID(req.DomainUUID) || !validUUID(req.ScopeUUID) || req.Dimensions < 1 || req.Dimensions > 1536 || len(req.Inputs) < 1 || len(req.Inputs) > 16 {
|
||||||
|
return errors.New("invalid machine learning request")
|
||||||
|
}
|
||||||
|
if req.Provider == "openai" {
|
||||||
|
if !req.AllowExternal || req.Model != "text-embedding-3-small" {
|
||||||
|
return errors.New("external embeddings not permitted or unsupported model")
|
||||||
|
}
|
||||||
|
} else if req.Provider != "doc2vec" || !modelHash.MatchString(req.Model) {
|
||||||
|
return errors.New("invalid machine learning provider/model")
|
||||||
|
}
|
||||||
|
seen := make(map[string]bool)
|
||||||
|
for _, input := range req.Inputs {
|
||||||
|
if !safeID.MatchString(input.ID) || seen[input.ID] || strings.TrimSpace(input.Text) == "" || !utf8.ValidString(input.Text) || len(input.Text) > 6000 {
|
||||||
|
return errors.New("invalid machine learning input")
|
||||||
|
}
|
||||||
|
seen[input.ID] = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Embed(ctx context.Context, input Request) (*Result, error) {
|
||||||
|
if err := validate(input); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(input)
|
||||||
|
if err != nil || len(body) > maxBody {
|
||||||
|
return nil, errors.New("machine learning input too large")
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("machine learning request failed")
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||||
|
response, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
return nil, errors.New("machine learning transport failed")
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return nil, &StatusError{Status: response.StatusCode}
|
||||||
|
}
|
||||||
|
raw, err := io.ReadAll(io.LimitReader(response.Body, maxResponse+1))
|
||||||
|
if err != nil || len(raw) > maxResponse {
|
||||||
|
return nil, errors.New("invalid machine learning response")
|
||||||
|
}
|
||||||
|
var result Result
|
||||||
|
if json.Unmarshal(raw, &result) != nil || result.Protocol != input.Protocol || result.DomainUUID != input.DomainUUID || result.ScopeUUID != input.ScopeUUID || result.Provider != input.Provider || result.Model != input.Model || result.ModelRevision != input.Model || result.Dimensions != input.Dimensions || len(result.Outputs) != len(input.Inputs) || result.Usage.TotalTokens < 0 {
|
||||||
|
return nil, errors.New("machine learning result metadata mismatch")
|
||||||
|
}
|
||||||
|
expectedTokenizer := "provider"
|
||||||
|
if input.Provider == "doc2vec" {
|
||||||
|
expectedTokenizer = "unicode-cjk-bigram-v1"
|
||||||
|
}
|
||||||
|
if result.Tokenizer != expectedTokenizer {
|
||||||
|
return nil, errors.New("machine learning tokenizer mismatch")
|
||||||
|
}
|
||||||
|
for i, output := range result.Outputs {
|
||||||
|
hash := sha256.Sum256([]byte(input.Inputs[i].Text))
|
||||||
|
if output.ID != input.Inputs[i].ID || output.InputSHA256 != hex.EncodeToString(hash[:]) || len(output.Vector) != input.Dimensions {
|
||||||
|
return nil, errors.New("machine learning output mismatch")
|
||||||
|
}
|
||||||
|
nonzero := false
|
||||||
|
for _, value := range output.Vector {
|
||||||
|
if math.IsNaN(value) || math.IsInf(value, 0) {
|
||||||
|
return nil, errors.New("non-finite machine learning vector")
|
||||||
|
}
|
||||||
|
nonzero = nonzero || value != 0
|
||||||
|
}
|
||||||
|
if !nonzero {
|
||||||
|
return nil, errors.New("empty machine learning vector")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &result, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package machinelearning
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func fixture() Request {
|
||||||
|
return Request{Protocol: "1", DomainUUID: "11111111-1111-4111-8111-111111111111", ScopeUUID: "22222222-2222-4222-8222-222222222222", Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 2, Inputs: []Input{{ID: "page:chunk0", Text: "合成文書 library books"}}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resultFor(req Request) Result {
|
||||||
|
r := Result{Protocol: req.Protocol, DomainUUID: req.DomainUUID, ScopeUUID: req.ScopeUUID, Provider: req.Provider, Model: req.Model, ModelRevision: req.Model, Dimensions: req.Dimensions, Tokenizer: "unicode-cjk-bigram-v1"}
|
||||||
|
for _, item := range req.Inputs {
|
||||||
|
hash := sha256.Sum256([]byte(item.Text))
|
||||||
|
r.Outputs = append(r.Outputs, Output{ID: item.ID, InputSHA256: hex.EncodeToString(hash[:]), Vector: []float64{0.5, -0.2}})
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClient(t *testing.T) {
|
||||||
|
req := fixture()
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
mutate func(*Result)
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"valid", func(*Result) {}, false},
|
||||||
|
{"wrong-domain", func(r *Result) { r.DomainUUID = req.ScopeUUID }, true},
|
||||||
|
{"wrong-scope", func(r *Result) { r.ScopeUUID = req.DomainUUID }, true},
|
||||||
|
{"wrong-hash", func(r *Result) { r.Outputs[0].InputSHA256 = "wrong" }, true},
|
||||||
|
{"wrong-dimensions", func(r *Result) { r.Outputs[0].Vector = []float64{1} }, true},
|
||||||
|
{"wrong-model", func(r *Result) { r.ModelRevision = "other" }, true},
|
||||||
|
{"wrong-tokenizer", func(r *Result) { r.Tokenizer = "other" }, true},
|
||||||
|
{"zero", func(r *Result) { r.Outputs[0].Vector = []float64{0, 0} }, true},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/v1/embeddings" || r.Method != "POST" || r.Header.Get("Authorization") != "Bearer "+strings.Repeat("t", 40) {
|
||||||
|
t.Error("request contract")
|
||||||
|
}
|
||||||
|
var sent Request
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&sent); err != nil || sent.Inputs[0].Text != req.Inputs[0].Text {
|
||||||
|
t.Error("input changed")
|
||||||
|
}
|
||||||
|
result := resultFor(req)
|
||||||
|
test.mutate(&result)
|
||||||
|
_ = json.NewEncoder(w).Encode(result)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
client, err := NewClient(server.URL, strings.Repeat("t", 40))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = client.Embed(context.Background(), req)
|
||||||
|
if (err != nil) != test.wantErr {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNoRedirectRetryOrSecretErrors(t *testing.T) {
|
||||||
|
calls := 0
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls++
|
||||||
|
w.Header().Set("Location", "/secret")
|
||||||
|
w.WriteHeader(307)
|
||||||
|
_, _ = w.Write([]byte("secret provider body"))
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
client, _ := NewClient(server.URL, strings.Repeat("t", 40))
|
||||||
|
_, err := client.Embed(context.Background(), fixture())
|
||||||
|
var status *StatusError
|
||||||
|
if !errors.As(err, &status) || status.Status != 307 || calls != 1 || strings.Contains(err.Error(), "secret") {
|
||||||
|
t.Fatalf("redirect/error handling: %v calls=%d", err, calls)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
_, err = client.Embed(ctx, fixture())
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequestValidation(t *testing.T) {
|
||||||
|
for _, mutate := range []func(*Request){
|
||||||
|
func(r *Request) { r.DomainUUID = "../" }, func(r *Request) { r.Inputs[0].Text = strings.Repeat("x", 6001) },
|
||||||
|
func(r *Request) { r.Provider = "openai"; r.Model = "text-embedding-3-small" },
|
||||||
|
func(r *Request) { r.Inputs = append(r.Inputs, r.Inputs[0]) }, func(r *Request) { r.Dimensions = 1537 },
|
||||||
|
} {
|
||||||
|
req := fixture()
|
||||||
|
mutate(&req)
|
||||||
|
if validate(req) == nil {
|
||||||
|
t.Fatal("accepted invalid request")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, origin := range []string{"file:///tmp/x", "http://user:pass@localhost", "https://ml.invalid/path", "https://ml.invalid?x=1"} {
|
||||||
|
if _, err := NewClient(origin, strings.Repeat("t", 40)); err == nil {
|
||||||
|
t.Fatal("accepted origin", origin)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Optional end-to-end contract test against a local synthetic fixture service.
|
||||||
|
// No real Pages documents, credentials, or paid OpenAI requests are used.
|
||||||
|
func TestLocalDoc2VecService(t *testing.T) {
|
||||||
|
origin := os.Getenv("PAGES_ML_TEST_ORIGIN")
|
||||||
|
if origin == "" {
|
||||||
|
t.Skip("set PAGES_ML_TEST_ORIGIN for synthetic service integration")
|
||||||
|
}
|
||||||
|
client, err := NewClient(origin, strings.Repeat("t", 40))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req := fixture()
|
||||||
|
req.Model = os.Getenv("PAGES_ML_TEST_MODEL")
|
||||||
|
req.Dimensions = 8
|
||||||
|
result, err := client.Embed(context.Background(), req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(result.Outputs) != 1 || len(result.Outputs[0].Vector) != 8 {
|
||||||
|
t.Fatal("wrong result shape")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package machinelearning
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrPolicy = errors.New("invalid machine learning policy")
|
||||||
|
var ErrNotAllowed = errors.New("machine learning scope is disabled, stale or excluded")
|
||||||
|
|
||||||
|
// Policy contains no credentials. Generation changes on every saved update,
|
||||||
|
// including disable/re-enable, so queued work cannot reuse old consent.
|
||||||
|
type Policy struct {
|
||||||
|
Generation string `json:"generation"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
ScopeUUID string `json:"scope_uuid"`
|
||||||
|
Provider string `json:"provider"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
Dimensions int `json:"dimensions"`
|
||||||
|
Prefixes []string `json:"prefixes"`
|
||||||
|
Exclude []string `json:"exclude"`
|
||||||
|
AllowExternal bool `json:"allow_external"`
|
||||||
|
MaxBatchBytes int `json:"max_batch_bytes"`
|
||||||
|
DailyInputBytes int64 `json:"daily_input_bytes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Canonical paths are decoded logical Wiki paths, not URLs or raw request URIs.
|
||||||
|
// Reject ambiguous encodings instead of silently broadening a configured scope.
|
||||||
|
func canonicalPath(p string) bool {
|
||||||
|
return utf8.ValidString(p) && len(p) <= 4096 && strings.HasPrefix(p, "/") && path.Clean(p) == p &&
|
||||||
|
!strings.ContainsAny(p, "%?#\\") && strings.IndexFunc(p, unicode.IsControl) < 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Policy) Validate() error {
|
||||||
|
if p.DailyInputBytes < 0 || p.DailyInputBytes > 1000000000 {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
if !validUUID(p.Generation) {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
// A new disabled configuration may have no model yet.
|
||||||
|
if !p.Enabled && p.Provider == "" && p.ScopeUUID == "" && p.Model == "" && p.Dimensions == 0 && len(p.Prefixes) == 0 && len(p.Exclude) == 0 && !p.AllowExternal && p.MaxBatchBytes == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !validUUID(p.ScopeUUID) || p.Dimensions < 1 || p.Dimensions > 1536 || len(p.Prefixes) < 1 || len(p.Prefixes) > 64 || len(p.Exclude) > 64 || p.MaxBatchBytes < 1 || p.MaxBatchBytes > 96000 {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
switch p.Provider {
|
||||||
|
case "doc2vec":
|
||||||
|
if !modelHash.MatchString(p.Model) || p.AllowExternal {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
case "openai":
|
||||||
|
if p.Model != "text-embedding-3-small" || (p.Enabled && !p.AllowExternal) {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
for _, paths := range [][]string{p.Prefixes, p.Exclude} {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, prefix := range paths {
|
||||||
|
if !canonicalPath(prefix) || seen[prefix] {
|
||||||
|
return ErrPolicy
|
||||||
|
}
|
||||||
|
seen[prefix] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func under(p, prefix string) bool {
|
||||||
|
return prefix == "/" || p == prefix || strings.HasPrefix(p, prefix+"/")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allows is an additional scope check, NOT document authorization. Callers must
|
||||||
|
// still check the current principal, revision, and learning cohort membership.
|
||||||
|
func (p Policy) Allows(logicalPath, generation string) bool {
|
||||||
|
if p.Validate() != nil || !p.Enabled || generation != p.Generation || !canonicalPath(logicalPath) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, prefix := range p.Exclude {
|
||||||
|
if under(logicalPath, prefix) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, prefix := range p.Prefixes {
|
||||||
|
if under(logicalPath, prefix) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare binds model and consent to a freshly loaded policy rather than to
|
||||||
|
// caller-provided JSON. Inputs must be authorized chunks of this one document.
|
||||||
|
// The batch limit is not a daily budget or a monetary cost ceiling.
|
||||||
|
func (p Policy) Prepare(domain, logicalPath, generation string, inputs []Input) (Request, error) {
|
||||||
|
if !p.Allows(logicalPath, generation) {
|
||||||
|
return Request{}, ErrNotAllowed
|
||||||
|
}
|
||||||
|
bytes := 0
|
||||||
|
for _, input := range inputs {
|
||||||
|
bytes += len(input.Text)
|
||||||
|
if bytes > p.MaxBatchBytes {
|
||||||
|
return Request{}, ErrNotAllowed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
req := Request{Protocol: "1", DomainUUID: domain, ScopeUUID: p.ScopeUUID, Provider: p.Provider, Model: p.Model, Dimensions: p.Dimensions, Inputs: inputs, AllowExternal: p.AllowExternal}
|
||||||
|
if err := validate(req); err != nil {
|
||||||
|
return Request{}, err
|
||||||
|
}
|
||||||
|
// Do not retain caller-owned slice memory across a queued operation.
|
||||||
|
req.Inputs = append([]Input(nil), inputs...)
|
||||||
|
return req, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package machinelearning
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func policyFixture() Policy {
|
||||||
|
return Policy{Generation: "33333333-3333-4333-8333-333333333333", Enabled: true, ScopeUUID: fixture().ScopeUUID, Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, Exclude: []string{"/lab/private"}, MaxBatchBytes: 12000}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPolicyPaths(t *testing.T) {
|
||||||
|
p := policyFixture()
|
||||||
|
for _, tc := range []struct {
|
||||||
|
path string
|
||||||
|
allow bool
|
||||||
|
}{
|
||||||
|
{"/lab", true}, {"/lab/文書", true}, {"/labs", false}, {"/lab/private", false}, {"/lab/private/child", false},
|
||||||
|
{"/lab/private-other", true}, {"/lab/../secret", false}, {"/lab/%70rivate", false}, {"/lab//a", false}, {"https://example.com/lab", false}, {"/lab/a?b", false},
|
||||||
|
} {
|
||||||
|
if p.Allows(tc.path, p.Generation) != tc.allow {
|
||||||
|
t.Errorf("path %q", tc.path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.Prefixes = []string{"/"}
|
||||||
|
if !p.Allows("/other", p.Generation) || p.Allows("/lab/private/x", p.Generation) {
|
||||||
|
t.Fatal("root/exclusion")
|
||||||
|
}
|
||||||
|
if p.Allows("/lab", "stale") {
|
||||||
|
t.Fatal("stale generation accepted")
|
||||||
|
}
|
||||||
|
p.Enabled = false
|
||||||
|
if p.Allows("/lab", p.Generation) {
|
||||||
|
t.Fatal("disabled scope accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPolicyValidationAndPrepare(t *testing.T) {
|
||||||
|
for _, mutate := range []func(*Policy){
|
||||||
|
func(p *Policy) { p.Prefixes = []string{"/lab/"} }, func(p *Policy) { p.Exclude = []string{"relative"} },
|
||||||
|
func(p *Policy) { p.AllowExternal = true }, func(p *Policy) { p.MaxBatchBytes = 0 },
|
||||||
|
func(p *Policy) { p.Provider = "openai"; p.Model = "text-embedding-3-small" },
|
||||||
|
} {
|
||||||
|
p := policyFixture()
|
||||||
|
mutate(&p)
|
||||||
|
if p.Validate() == nil {
|
||||||
|
t.Fatal("invalid policy accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p := policyFixture()
|
||||||
|
inputs := []Input{{ID: "chunk:0", Text: "合成文書"}}
|
||||||
|
req, err := p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
inputs[0].Text = "changed"
|
||||||
|
if req.Inputs[0].Text == "changed" || req.AllowExternal {
|
||||||
|
t.Fatal("input/consent binding")
|
||||||
|
}
|
||||||
|
p.MaxBatchBytes = 2
|
||||||
|
if _, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs); err == nil {
|
||||||
|
t.Fatal("batch budget")
|
||||||
|
}
|
||||||
|
p = policyFixture()
|
||||||
|
p.Provider = "openai"
|
||||||
|
p.Model = "text-embedding-3-small"
|
||||||
|
p.AllowExternal = true
|
||||||
|
req, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs)
|
||||||
|
if err != nil || !req.AllowExternal {
|
||||||
|
t.Fatalf("explicit external policy: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ func configPanelGroups(locale string, plugins []adapterPlugin) []configPanelGrou
|
|||||||
for _, plugin := range plugins {
|
for _, plugin := range plugins {
|
||||||
groups[4].Panels = append(groups[4].Panels, configPanelLink{"adapter-" + plugin.ID, plugin.Name})
|
groups[4].Panels = append(groups[4].Panels, configPanelLink{"adapter-" + plugin.ID, plugin.Name})
|
||||||
}
|
}
|
||||||
|
groups[5].Panels = append(groups[5].Panels, configPanelLink{"machine-learning", "Machine Learning"})
|
||||||
groups = append(groups, configPanelGroup{"extensions", translate(locale, "extension.title"), []configPanelLink{link("extensions", "extension.catalog"), link("diary", "periodical.diary"), link("blog", "periodical.blog")}})
|
groups = append(groups, configPanelGroup{"extensions", translate(locale, "extension.title"), []configPanelLink{link("extensions", "extension.catalog"), link("diary", "periodical.diary"), link("blog", "periodical.blog")}})
|
||||||
groups = append(groups, configPanelGroup{"organizer", translate(locale, "organizer.title"), []configPanelLink{link("organizer", "organizer.settings")}})
|
groups = append(groups, configPanelGroup{"organizer", translate(locale, "organizer.title"), []configPanelLink{link("organizer", "organizer.settings")}})
|
||||||
return groups
|
return groups
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ func configFixture(t *testing.T) (*Server, string, string) {
|
|||||||
s.mux.HandleFunc("/-/sys/config/auth", s.handleAuthAdmin)
|
s.mux.HandleFunc("/-/sys/config/auth", s.handleAuthAdmin)
|
||||||
s.mux.HandleFunc("/-/sys/config/adapters", s.handleAdapterPluginConfig)
|
s.mux.HandleFunc("/-/sys/config/adapters", s.handleAdapterPluginConfig)
|
||||||
s.mux.HandleFunc("/_/api/v1/assets", s.handleAssetsAPI)
|
s.mux.HandleFunc("/_/api/v1/assets", s.handleAssetsAPI)
|
||||||
|
s.mux.HandleFunc("/_/api/v1/ml/settings", s.handleMachineLearningSettings)
|
||||||
s.mux.HandleFunc("/_/api/v1/adapter", s.handleAdapterAPI)
|
s.mux.HandleFunc("/_/api/v1/adapter", s.handleAdapterAPI)
|
||||||
s.mux.HandleFunc("/_/api/v1/queue", s.handleQueueAPI)
|
s.mux.HandleFunc("/_/api/v1/queue", s.handleQueueAPI)
|
||||||
s.mux.HandleFunc("/_/api/v1/queue/", s.handleQueueAPI)
|
s.mux.HandleFunc("/_/api/v1/queue/", s.handleQueueAPI)
|
||||||
@@ -313,7 +314,7 @@ func TestConfigChromiumSmoke(t *testing.T) {
|
|||||||
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
}))
|
}))
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
for _, panel := range []string{"assets", "events", "queue", "scheduler", "logs", "resources", "bookmarks", "adapter-hosted.test", "extensions"} {
|
for _, panel := range []string{"assets", "events", "queue", "scheduler", "logs", "resources", "bookmarks", "adapter-hosted.test", "extensions", "machine-learning"} {
|
||||||
t.Run(panel, func(t *testing.T) {
|
t.Run(panel, func(t *testing.T) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -339,6 +340,9 @@ func TestConfigChromiumSmoke(t *testing.T) {
|
|||||||
if panel == "assets" && !strings.Contains(body, `data-asset-copy-hash=`) {
|
if panel == "assets" && !strings.Contains(body, `data-asset-copy-hash=`) {
|
||||||
t.Fatalf("assets did not load: %s", body)
|
t.Fatalf("assets did not load: %s", body)
|
||||||
}
|
}
|
||||||
|
if panel == "machine-learning" && !strings.Contains(body, `id="ml-scope_uuid"`) {
|
||||||
|
t.Fatalf("ML settings did not load: %s", body)
|
||||||
|
}
|
||||||
if panel == "resources" && !strings.Contains(body, `class="chart-line"`) {
|
if panel == "resources" && !strings.Contains(body, `class="chart-line"`) {
|
||||||
t.Fatalf("resource chart did not load: %s", body)
|
t.Fatalf("resource chart did not load: %s", body)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,6 +70,8 @@ var endpointPolicies = map[string]endpointPolicy{
|
|||||||
"POST /_/api/v1/gc/zombies/purge": {Name: "gc.purge", Capability: "delete", Target: targetDomain},
|
"POST /_/api/v1/gc/zombies/purge": {Name: "gc.purge", Capability: "delete", Target: targetDomain},
|
||||||
"POST /v/upload": {Name: "document.upload", Capability: "upload", Target: targetDomain, Resolver: resolveHandler},
|
"POST /v/upload": {Name: "document.upload", Capability: "upload", Target: targetDomain, Resolver: resolveHandler},
|
||||||
"GET /_/api/v1/assets": {Name: "asset.list", Capability: "manage", Target: targetDomain, Resolver: resolveHandler},
|
"GET /_/api/v1/assets": {Name: "asset.list", Capability: "manage", Target: targetDomain, Resolver: resolveHandler},
|
||||||
|
"GET /_/api/v1/ml/settings": {Name: "ml.settings.read", Capability: "manage", Target: targetDomain, Resolver: resolveHandler},
|
||||||
|
"PUT /_/api/v1/ml/settings": {Name: "ml.settings.write", Capability: "manage", Target: targetDomain, Resolver: resolveHandler},
|
||||||
"POST /_/api/v1/assets": {Name: "asset.create", Capability: "manage", Target: targetDomain, Resolver: resolveHandler},
|
"POST /_/api/v1/assets": {Name: "asset.create", Capability: "manage", Target: targetDomain, Resolver: resolveHandler},
|
||||||
"DELETE /_/api/v1/assets": {Name: "asset.delete", Capability: "manage", Target: targetDomain, Resolver: resolveHandler},
|
"DELETE /_/api/v1/assets": {Name: "asset.delete", Capability: "manage", Target: targetDomain, Resolver: resolveHandler},
|
||||||
"GET /_/api/v1/notifications": {Name: "notifications.list", Capability: "read", Target: targetDomain, Resolver: resolveHandler},
|
"GET /_/api/v1/notifications": {Name: "notifications.list", Capability: "read", Target: targetDomain, Resolver: resolveHandler},
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"pageswiki/internal/machinelearning"
|
||||||
|
"pageswiki/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Server) handleMachineLearningSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
domain := s.domainForRequest(r)
|
||||||
|
principal := s.requestPrincipal(r)
|
||||||
|
if domain == nil || principal == nil || principal.State != "active" ||
|
||||||
|
(!s.store.IsBuiltinGroupAdmin(domain.UUID, principal.UUID, "domain_admin") && !s.store.IsCampusAdmin(domain.CampusUUID, principal.UUID)) {
|
||||||
|
writeEventJSON(w, 403, map[string]string{"error": "domain_admin_required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method == http.MethodGet {
|
||||||
|
p, err := s.store.MachineLearningPolicy(r.Context(), domain.UUID)
|
||||||
|
if err != nil {
|
||||||
|
writeEventJSON(w, 503, map[string]string{"error": "ml_settings_unavailable"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeEventJSON(w, 200, p)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Method != http.MethodPut {
|
||||||
|
w.Header().Set("Allow", "GET, PUT")
|
||||||
|
writeEventJSON(w, 405, map[string]string{"error": "method_not_allowed"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !validBrowserMutationOrigin(r) {
|
||||||
|
rejectBrowserMutation(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
contentType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if err != nil || contentType != "application/json" {
|
||||||
|
writeEventJSON(w, 415, map[string]string{"error": "json_required"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request struct {
|
||||||
|
BaseGeneration string `json:"base_generation"`
|
||||||
|
Policy machinelearning.Policy `json:"policy"`
|
||||||
|
}
|
||||||
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10))
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF {
|
||||||
|
writeEventJSON(w, 400, map[string]string{"error": "ml_invalid_settings"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// The store assigns the new generation; do not accept an ambiguous second base.
|
||||||
|
if request.Policy.Generation != "" {
|
||||||
|
writeEventJSON(w, 400, map[string]string{"error": "ml_invalid_settings"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p, err := s.store.SaveMachineLearningPolicy(r.Context(), domain.UUID, request.BaseGeneration, request.Policy)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, store.ErrMachineLearningConflict):
|
||||||
|
writeEventJSON(w, 409, map[string]string{"error": "ml_settings_conflict"})
|
||||||
|
case errors.Is(err, machinelearning.ErrPolicy):
|
||||||
|
writeEventJSON(w, 422, map[string]string{"error": "ml_invalid_settings"})
|
||||||
|
case err != nil:
|
||||||
|
writeEventJSON(w, 503, map[string]string{"error": "ml_settings_unavailable"})
|
||||||
|
default:
|
||||||
|
writeEventJSON(w, 200, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"pageswiki/internal/machinelearning"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMachineLearningSettingsAPI(t *testing.T) {
|
||||||
|
s, token, domain := configFixture(t)
|
||||||
|
call := func(auth, method, body, origin string) *httptest.ResponseRecorder {
|
||||||
|
r := httptest.NewRequest(method, "http://localhost/_/api/v1/ml/settings", strings.NewReader(body))
|
||||||
|
if auth != "" {
|
||||||
|
r.Header.Set("Authorization", "Bearer "+auth)
|
||||||
|
}
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
if origin != "" {
|
||||||
|
r.Header.Set("Origin", origin)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
w := call(token, "GET", "", "")
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatalf("read: %d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(w.Header().Get("Cache-Control"), "no-store") {
|
||||||
|
t.Fatal("cacheable settings")
|
||||||
|
}
|
||||||
|
p := machinelearning.Policy{Enabled: true, ScopeUUID: "22222222-2222-4222-8222-222222222222", Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 128, Prefixes: []string{"/lab"}, MaxBatchBytes: 6000}
|
||||||
|
encode := func(base string) string {
|
||||||
|
b, e := json.Marshal(map[string]any{"base_generation": base, "policy": p})
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
body := encode("")
|
||||||
|
if w = call(token, "PUT", body, "https://attacker.example"); w.Code != 403 {
|
||||||
|
t.Fatal("cross origin", w.Code)
|
||||||
|
}
|
||||||
|
user, e := s.store.CreatePasswordAccount(domain, "ml-user", "synthetic long password", "User", "")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
userToken, e := s.store.CreateAuthSession(domain, user.UUID)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for _, method := range []string{"GET", "PUT"} {
|
||||||
|
if w = call(userToken, method, body, ""); w.Code != 403 {
|
||||||
|
t.Fatal("non admin", method, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if w = call("", "GET", "", ""); w.Code == 200 {
|
||||||
|
t.Fatal("anonymous read")
|
||||||
|
}
|
||||||
|
w = call(token, "PUT", body, "")
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatalf("save: %d %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
var saved machinelearning.Policy
|
||||||
|
if json.Unmarshal(w.Body.Bytes(), &saved) != nil || saved.Generation == "" {
|
||||||
|
t.Fatal("missing generation")
|
||||||
|
}
|
||||||
|
if w = call(token, "PUT", body, ""); w.Code != 409 {
|
||||||
|
t.Fatal("stale save", w.Code)
|
||||||
|
}
|
||||||
|
if w = call(token, "PUT", encode(saved.Generation)+" {}", ""); w.Code != 400 {
|
||||||
|
t.Fatal("trailing JSON", w.Code)
|
||||||
|
}
|
||||||
|
p.Enabled = false
|
||||||
|
w = call(token, "PUT", encode(saved.Generation), "")
|
||||||
|
if w.Code != 200 {
|
||||||
|
t.Fatal("disable", w.Code)
|
||||||
|
}
|
||||||
|
if json.Unmarshal(w.Body.Bytes(), &saved) != nil {
|
||||||
|
t.Fatal("response")
|
||||||
|
}
|
||||||
|
p.Enabled = true
|
||||||
|
p.Provider = "openai"
|
||||||
|
p.Model = "text-embedding-3-small"
|
||||||
|
if w = call(token, "PUT", encode(saved.Generation), ""); w.Code != 422 {
|
||||||
|
t.Fatal("external consent bypass", w.Code)
|
||||||
|
}
|
||||||
|
page := configRequest(s, token, http.MethodGet, "/-/sys/config?panel=machine-learning", nil)
|
||||||
|
if page.Code != 200 || !strings.Contains(page.Body.String(), `id="panel-machine-learning"`) || !strings.Contains(page.Body.String(), "ml-settings.js") {
|
||||||
|
t.Fatal("settings panel missing", page.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -252,6 +252,7 @@ func (s *Server) registerRoutes() {
|
|||||||
s.mux.HandleFunc("/_/obj/", s.handleImmutableObject)
|
s.mux.HandleFunc("/_/obj/", s.handleImmutableObject)
|
||||||
s.mux.HandleFunc("/v/json/", s.handleJSONStructure)
|
s.mux.HandleFunc("/v/json/", s.handleJSONStructure)
|
||||||
s.mux.HandleFunc("/_/api/v1/assets", s.handleAssetsAPI)
|
s.mux.HandleFunc("/_/api/v1/assets", s.handleAssetsAPI)
|
||||||
|
s.mux.HandleFunc("/_/api/v1/ml/settings", s.handleMachineLearningSettings)
|
||||||
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
s.mux.HandleFunc("/_/api/v1/path-picker", s.handlePathPickerAPI)
|
||||||
s.mux.HandleFunc("/_/api/v1/browser/navigation", s.handleBrowserNavigationAPI)
|
s.mux.HandleFunc("/_/api/v1/browser/navigation", s.handleBrowserNavigationAPI)
|
||||||
s.mux.HandleFunc("/u/", s.handleUserProfile)
|
s.mux.HandleFunc("/u/", s.handleUserProfile)
|
||||||
|
|||||||
@@ -16,6 +16,20 @@
|
|||||||
d.getElementById('feed-rows').focus();d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'j',bubbles:true}));
|
d.getElementById('feed-rows').focus();d.dispatchEvent(new w.KeyboardEvent('keydown',{key:'j',bubbles:true}));
|
||||||
await wait(()=>d.querySelector('#feed-reader .feed-body'));const html=d.querySelector('#feed-reader .feed-body').shadowRoot;assert(html?.querySelector('h2')&&html.querySelector('table')&&html.querySelector('strong'),'HTML not rendered');assert(!html.querySelector('script,img,iframe,form'),'Active article HTML');assert(!w.rssAttack,'Script executed');assert(html.querySelector('a').target==='_blank','Article link target');assert(d.querySelector('.feed-original svg')&&!d.querySelector('.feed-original').textContent,'Original link not icon');
|
await wait(()=>d.querySelector('#feed-reader .feed-body'));const html=d.querySelector('#feed-reader .feed-body').shadowRoot;assert(html?.querySelector('h2')&&html.querySelector('table')&&html.querySelector('strong'),'HTML not rendered');assert(!html.querySelector('script,img,iframe,form'),'Active article HTML');assert(!w.rssAttack,'Script executed');assert(html.querySelector('a').target==='_blank','Article link target');assert(d.querySelector('.feed-original svg')&&!d.querySelector('.feed-original').textContent,'Original link not icon');
|
||||||
const share=d.querySelector('.feed-share-x'),intent=new URL(share.href);assert(share.target==='_blank'&&share.rel.includes('noopener')&&intent.searchParams.get('url')==='https://example.org/article'&&intent.searchParams.get('text').includes('日本語のRSS記事')&&!intent.searchParams.get('text').includes('https://'),'RSS share URL or duplicate URL in text');
|
const share=d.querySelector('.feed-share-x'),intent=new URL(share.href);assert(share.target==='_blank'&&share.rel.includes('noopener')&&intent.searchParams.get('url')==='https://example.org/article'&&intent.searchParams.get('text').includes('日本語のRSS記事')&&!intent.searchParams.get('text').includes('https://'),'RSS share URL or duplicate URL in text');
|
||||||
|
// No X request is made: verify one synchronous popup request and no fallback
|
||||||
|
// navigation even when noopener returns null (also true for blocked popups).
|
||||||
|
const originalOpen=w.open,popupCalls=[],beforeShare=w.location.href;
|
||||||
|
w.open=(...args)=>{popupCalls.push(args);return null;};
|
||||||
|
try{
|
||||||
|
const click=new w.MouseEvent('click',{button:0,bubbles:true,cancelable:true});
|
||||||
|
assert(!share.dispatchEvent(click)&&click.defaultPrevented,'Share default navigation not cancelled');
|
||||||
|
assert(popupCalls.length===1&&popupCalls[0][0]===share.href&&popupCalls[0][2].includes('popup=yes')&&popupCalls[0][2].includes('noopener')&&popupCalls[0][2].includes('noreferrer'),'Share did not request one isolated popup');
|
||||||
|
let modifiedPrevented;
|
||||||
|
share.addEventListener('click',e=>{modifiedPrevented=e.defaultPrevented;e.preventDefault();},{once:true});
|
||||||
|
share.dispatchEvent(new w.MouseEvent('click',{button:0,ctrlKey:true,bubbles:true,cancelable:true}));
|
||||||
|
assert(modifiedPrevented===false&&popupCalls.length===1,'Modified click intercepted');
|
||||||
|
await delay(50);assert(w.location.href===beforeShare&&popupCalls.length===1,'Share navigated or opened twice');
|
||||||
|
}finally{w.open=originalOpen;}
|
||||||
assert(d.getElementById('feeds-app').dataset.linkMode==='embedded','Link preference missing');assert(!d.querySelector('.feed-external iframe'),'External page fetched before click');const externalURL=new URL('/fixture/embedded',w.location.href);externalURL.hostname='localhost';let externalLoaded=0;w.addEventListener('message',e=>{if(e.data==='rss-external-fixture-loaded'&&e.origin==='null')externalLoaded++;});const original=d.querySelector('.feed-original');original.href=externalURL.href;original.click();await wait(()=>d.querySelector('.feed-external[open] iframe'));await wait(()=>externalLoaded===1);let previewFrame=d.querySelector('.feed-external iframe');assert(previewFrame.src===externalURL.href&&previewFrame.getAttribute('sandbox')==='allow-scripts'&&previewFrame.referrerPolicy==='no-referrer','Unsafe external frame');assert(d.querySelector('.feed-external a').target==='_blank','Missing fallback');d.querySelector('.feed-external button').click();await wait(()=>!d.querySelector('.feed-external'));assert(d.querySelector('#feed-reader .feed-body'),'External preview lost article');const articleLink=html.querySelector('a');articleLink.href=externalURL.href;articleLink.click();await wait(()=>externalLoaded===2);d.querySelector('.feed-external').close();await wait(()=>!d.querySelector('.feed-external'));
|
assert(d.getElementById('feeds-app').dataset.linkMode==='embedded','Link preference missing');assert(!d.querySelector('.feed-external iframe'),'External page fetched before click');const externalURL=new URL('/fixture/embedded',w.location.href);externalURL.hostname='localhost';let externalLoaded=0;w.addEventListener('message',e=>{if(e.data==='rss-external-fixture-loaded'&&e.origin==='null')externalLoaded++;});const original=d.querySelector('.feed-original');original.href=externalURL.href;original.click();await wait(()=>d.querySelector('.feed-external[open] iframe'));await wait(()=>externalLoaded===1);let previewFrame=d.querySelector('.feed-external iframe');assert(previewFrame.src===externalURL.href&&previewFrame.getAttribute('sandbox')==='allow-scripts'&&previewFrame.referrerPolicy==='no-referrer','Unsafe external frame');assert(d.querySelector('.feed-external a').target==='_blank','Missing fallback');d.querySelector('.feed-external button').click();await wait(()=>!d.querySelector('.feed-external'));assert(d.querySelector('#feed-reader .feed-body'),'External preview lost article');const articleLink=html.querySelector('a');articleLink.href=externalURL.href;articleLink.click();await wait(()=>externalLoaded===2);d.querySelector('.feed-external').close();await wait(()=>!d.querySelector('.feed-external'));
|
||||||
const help=d.getElementById('feed-help'),helpButton=d.querySelector('[aria-controls="feed-help"]'),key=k=>d.dispatchEvent(new w.KeyboardEvent('keydown',{key:k,bubbles:true}));
|
const help=d.getElementById('feed-help'),helpButton=d.querySelector('[aria-controls="feed-help"]'),key=k=>d.dispatchEvent(new w.KeyboardEvent('keydown',{key:k,bubbles:true}));
|
||||||
d.getElementById('feed-status').textContent='Synthetic status';key('?');await wait(()=>!help.hidden);assert(helpButton.getAttribute('aria-expanded')==='true','Help toggle state');key('Escape');assert(help.hidden&&d.querySelector('.feed-layout').classList.contains('reading'),'Closing help changed reader');assert(d.getElementById('feed-status').textContent==='Synthetic status','Help erased status');key('?');await wait(()=>!help.hidden);key('?');await wait(()=>help.hidden);helpButton.click();await wait(()=>!help.hidden);help.querySelector('button').click();await wait(()=>help.hidden);assert(helpButton.getAttribute('aria-expanded')==='false','Help state not reset');d.getElementById('feed-status').textContent='';
|
d.getElementById('feed-status').textContent='Synthetic status';key('?');await wait(()=>!help.hidden);assert(helpButton.getAttribute('aria-expanded')==='true','Help toggle state');key('Escape');assert(help.hidden&&d.querySelector('.feed-layout').classList.contains('reading'),'Closing help changed reader');assert(d.getElementById('feed-status').textContent==='Synthetic status','Help erased status');key('?');await wait(()=>!help.hidden);key('?');await wait(()=>help.hidden);helpButton.click();await wait(()=>!help.hidden);help.querySelector('button').click();await wait(()=>help.hidden);assert(helpButton.getAttribute('aria-expanded')==='false','Help state not reset');d.getElementById('feed-status').textContent='';
|
||||||
|
|||||||
@@ -12,8 +12,22 @@
|
|||||||
let isolated=false;try{isolated=!frame.contentDocument}catch{isolated=true}assert(isolated,'Frame can access parent origin');
|
let isolated=false;try{isolated=!frame.contentDocument}catch{isolated=true}assert(isolated,'Frame can access parent origin');
|
||||||
assert(frame.getBoundingClientRect().height>=240,'Slide frame collapsed');
|
assert(frame.getBoundingClientRect().height>=240,'Slide frame collapsed');
|
||||||
assert(frame.getBoundingClientRect().width<=innerWidth,'Mobile slide overflow');
|
assert(frame.getBoundingClientRect().width<=innerWidth,'Mobile slide overflow');
|
||||||
|
const playback=frame.parentElement.querySelector('.slides-playback'),play=playback.querySelector('button'),seconds=playback.querySelector('input[type=number]'),loop=playback.querySelector('input[type=checkbox]');
|
||||||
|
assert(play.disabled===false&&play.getAttribute('aria-pressed')==='false','Slideshow should start paused');
|
||||||
|
seconds.value='0';seconds.dispatchEvent(new Event('change'));assert(frame.parentElement.dataset.slidePlaying!=='true','Invalid interval started slideshow');
|
||||||
|
seconds.value='1';seconds.dispatchEvent(new Event('change'));play.click();
|
||||||
|
await wait(()=>frame.parentElement.dataset.slideIndex==='1');
|
||||||
|
await wait(()=>play.getAttribute('aria-pressed')==='false');
|
||||||
|
assert(frame.parentElement.dataset.slideIndex==='1','Non-loop slideshow did not stop at final slide');
|
||||||
|
loop.checked=true;loop.dispatchEvent(new Event('change'));play.click();
|
||||||
|
await wait(()=>frame.parentElement.dataset.slideIndex==='0');
|
||||||
|
await wait(()=>frame.parentElement.dataset.slideIndex==='1');
|
||||||
|
play.click();await wait(()=>play.getAttribute('aria-pressed')==='false');
|
||||||
|
const stoppedIndex=frame.parentElement.dataset.slideIndex;await delay(1150);assert(frame.parentElement.dataset.slideIndex===stoppedIndex,'Paused slideshow advanced');
|
||||||
|
window.postMessage({type:'slides-playback',playing:true,token:'invalid'},'*');await delay(30);assert(play.getAttribute('aria-pressed')==='false','Untrusted playback message accepted');
|
||||||
if(e&&innerWidth<=700){assert(getComputedStyle(document.querySelector('.editor-pane')).display==='none','Mobile preview not full width');setEditorPreviewVisible(false);assert(getComputedStyle(document.querySelector('.editor-pane')).display!=='none','Mobile source inaccessible');setEditorPreviewVisible(true);}
|
if(e&&innerWidth<=700){assert(getComputedStyle(document.querySelector('.editor-pane')).display==='none','Mobile preview not full width');setEditorPreviewVisible(false);assert(getComputedStyle(document.querySelector('.editor-pane')).display!=='none','Mobile source inaccessible');setEditorPreviewVisible(true);}
|
||||||
const host=frame.parentElement;
|
const host=frame.parentElement;
|
||||||
|
host.dataset.slideIndex='0';
|
||||||
// Verify the defensive DOM boundary independently of server sanitization.
|
// Verify the defensive DOM boundary independently of server sanitization.
|
||||||
PagesSlides.render(host,'<h1 onclick="alert(1)" data-background-iframe="https://evil.invalid">Safe</h1><script>alert(1)</scr'+'ipt><iframe src="https://evil.invalid"></iframe><img src="https://evil.invalid/x"><hr><p>Next</p>','/deck');
|
PagesSlides.render(host,'<h1 onclick="alert(1)" data-background-iframe="https://evil.invalid">Safe</h1><script>alert(1)</scr'+'ipt><iframe src="https://evil.invalid"></iframe><img src="https://evil.invalid/x"><hr><p>Next</p>','/deck');
|
||||||
await wait(ready);
|
await wait(ready);
|
||||||
|
|||||||
@@ -188,43 +188,58 @@ func (s *Store) RevokeAuthSession(token string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) ListDomainPrincipals(domainUUID string) ([]Principal, error) {
|
func (s *Store) ListDomainPrincipals(domainUUID string) ([]Principal, error) {
|
||||||
rows, err := s.DB.Query(`SELECT p.uuid,p.display_name,p.email,p.state FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid WHERE m.domain_uuid=`+s.sqlParam(1)+` ORDER BY lower(p.display_name),p.uuid`, domainUUID)
|
return s.ListDomainPrincipalsContext(context.Background(), domainUUID)
|
||||||
|
}
|
||||||
|
func (s *Store) ListDomainPrincipalsContext(ctx context.Context, domainUUID string) ([]Principal, error) {
|
||||||
|
rows, err := s.DB.QueryContext(ctx, `SELECT p.uuid,p.display_name,p.email,p.state FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid WHERE m.domain_uuid=`+s.sqlParam(1)+` ORDER BY lower(p.display_name),p.uuid`, domainUUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, s.sqlError("list principals", err)
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
var out []Principal
|
var out []Principal
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var p Principal
|
var p Principal
|
||||||
if err := rows.Scan(&p.UUID, &p.DisplayName, &p.Email, &p.State); err != nil {
|
if err := rows.Scan(&p.UUID, &p.DisplayName, &p.Email, &p.State); err != nil {
|
||||||
return nil, err
|
return nil, s.sqlError("decode principal", err)
|
||||||
}
|
}
|
||||||
out = append(out, p)
|
out = append(out, p)
|
||||||
}
|
}
|
||||||
return out, rows.Err()
|
return out, s.sqlError("list principals", rows.Err())
|
||||||
}
|
}
|
||||||
func (s *Store) ListAuthSessions(domainUUID string) ([]AuthSessionInfo, error) {
|
func (s *Store) ListAuthSessions(domainUUID string) ([]AuthSessionInfo, error) {
|
||||||
rows, err := s.DB.Query(fmt.Sprintf(`SELECT s.uuid,s.principal_uuid,p.display_name,s.auth_time_ms,s.expires_at_ms,s.last_seen_at_ms,s.mfa_level FROM auth_sessions s JOIN principals p ON p.uuid=s.principal_uuid WHERE s.domain_uuid=%s AND s.revoked_at_ms=0 AND s.expires_at_ms>%s ORDER BY s.last_seen_at_ms DESC,s.uuid`, s.sqlParam(1), s.sqlParam(2)), domainUUID, time.Now().UnixMilli())
|
return s.ListAuthSessionsContext(context.Background(), domainUUID)
|
||||||
|
}
|
||||||
|
func (s *Store) ListAuthSessionsContext(ctx context.Context, domainUUID string) ([]AuthSessionInfo, error) {
|
||||||
|
rows, err := s.DB.QueryContext(ctx, fmt.Sprintf(`SELECT s.uuid,s.principal_uuid,p.display_name,s.auth_time_ms,s.expires_at_ms,s.last_seen_at_ms,s.mfa_level FROM auth_sessions s JOIN principals p ON p.uuid=s.principal_uuid WHERE s.domain_uuid=%s AND s.revoked_at_ms=0 AND s.expires_at_ms>%s ORDER BY s.last_seen_at_ms DESC,s.uuid`, s.sqlParam(1), s.sqlParam(2)), domainUUID, time.Now().UnixMilli())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, s.sqlError("list sessions", err)
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
var out []AuthSessionInfo
|
var out []AuthSessionInfo
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var item AuthSessionInfo
|
var item AuthSessionInfo
|
||||||
if err := rows.Scan(&item.UUID, &item.PrincipalUUID, &item.DisplayName, &item.AuthTimeMS, &item.ExpiresAtMS, &item.LastSeenAtMS, &item.MFALevel); err != nil {
|
if err := rows.Scan(&item.UUID, &item.PrincipalUUID, &item.DisplayName, &item.AuthTimeMS, &item.ExpiresAtMS, &item.LastSeenAtMS, &item.MFALevel); err != nil {
|
||||||
return nil, err
|
return nil, s.sqlError("decode session", err)
|
||||||
}
|
}
|
||||||
out = append(out, item)
|
out = append(out, item)
|
||||||
}
|
}
|
||||||
return out, rows.Err()
|
return out, s.sqlError("list sessions", rows.Err())
|
||||||
}
|
}
|
||||||
func (s *Store) RevokeAuthSessionByID(domainUUID, sessionUUID string) error {
|
func (s *Store) RevokeAuthSessionByID(domainUUID, sessionUUID string) error {
|
||||||
result, err := s.DB.Exec(fmt.Sprintf(`UPDATE auth_sessions SET revoked_at_ms=%s WHERE domain_uuid=%s AND uuid=%s AND revoked_at_ms=0`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), time.Now().UnixMilli(), domainUUID, sessionUUID)
|
return s.RevokeAuthSessionByIDContext(context.Background(), domainUUID, sessionUUID)
|
||||||
|
}
|
||||||
|
func (s *Store) RevokeAuthSessionByIDContext(ctx context.Context, domainUUID, sessionUUID string) error {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
|
result, err := s.DB.ExecContext(ctx, fmt.Sprintf(`UPDATE auth_sessions SET revoked_at_ms=%s WHERE domain_uuid=%s AND uuid=%s AND revoked_at_ms=0`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), time.Now().UnixMilli(), domainUUID, sessionUUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return s.sqlError("revoke session by ID", err)
|
return s.sqlError("revoke session by ID", err)
|
||||||
}
|
}
|
||||||
count, _ := result.RowsAffected()
|
count, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return s.sqlError("revoke session result", err)
|
||||||
|
}
|
||||||
if count == 0 {
|
if count == 0 {
|
||||||
return sql.ErrNoRows
|
return sql.ErrNoRows
|
||||||
}
|
}
|
||||||
@@ -239,6 +254,12 @@ func (s *Store) SetPrincipalStateContext(ctx context.Context, domainUUID, princi
|
|||||||
return errors.New("invalid principal state")
|
return errors.New("invalid principal state")
|
||||||
}
|
}
|
||||||
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
var found string
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT p.uuid FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid WHERE p.uuid=? AND m.domain_uuid=?`, principalUUID, domainUUID).Scan(&found); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE principals SET state=%s,updated_at_ms=%s WHERE uuid=%s AND EXISTS(SELECT 1 FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid=%s)`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), state, time.Now().UnixMilli(), principalUUID, domainUUID, principalUUID)
|
result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE principals SET state=%s,updated_at_ms=%s WHERE uuid=%s AND EXISTS(SELECT 1 FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid=%s)`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), state, time.Now().UnixMilli(), principalUUID, domainUUID, principalUUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -247,7 +268,7 @@ func (s *Store) SetPrincipalStateContext(ctx context.Context, domainUUID, princi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if count == 0 {
|
if count == 0 && s.sqlBackend != storeMySQL {
|
||||||
return sql.ErrNoRows
|
return sql.ErrNoRows
|
||||||
}
|
}
|
||||||
if state != "active" {
|
if state != "active" {
|
||||||
@@ -274,6 +295,9 @@ func (s *Store) CreatePasswordAccount(domainUUID, username, password, displayNam
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) EnsureAuthSchema() error {
|
func (s *Store) EnsureAuthSchema() error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend == storePostgreSQL {
|
||||||
if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil {
|
if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -40,9 +40,9 @@ func (s *Store) createPasswordAccountContext(ctx context.Context, domain, userna
|
|||||||
}
|
}
|
||||||
// PostgreSQL cannot bootstrap into a nonexistent or disabled namespace.
|
// PostgreSQL cannot bootstrap into a nonexistent or disabled namespace.
|
||||||
// SQLite retains its historical authentication-only fixture support.
|
// SQLite retains its historical authentication-only fixture support.
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend != storeSQLite {
|
||||||
var present bool
|
var present bool
|
||||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=$1 AND enabled=1 AND placement='local')`, domain).Scan(&present); err != nil {
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=`+s.sqlParam(1)+` AND enabled=1 AND placement='local')`, domain).Scan(&present); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !present {
|
if !present {
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ func TestAccountBackendCLIHandoff(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAccountBackendExternalIdentity(t *testing.T) {
|
func TestAccountBackendExternalIdentity(t *testing.T) {
|
||||||
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} {
|
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
||||||
s, d := accountBackendStore(t, b)
|
s, d := accountBackendStore(t, b)
|
||||||
s.authKey = make([]byte, 32)
|
s.authKey = make([]byte, 32)
|
||||||
@@ -135,6 +135,13 @@ func TestAccountBackendExternalIdentity(t *testing.T) {
|
|||||||
if err != nil || !provider.Enabled || provider.LDAPBindPassword != config.LDAPBindPassword {
|
if err != nil || !provider.Enabled || provider.LDAPBindPassword != config.LDAPBindPassword {
|
||||||
t.Fatal("provider configuration mismatch", err)
|
t.Fatal("provider configuration mismatch", err)
|
||||||
}
|
}
|
||||||
|
var encoded, sealed string
|
||||||
|
if err := s.DB.QueryRow(`SELECT config_json,secret_encrypted FROM auth_providers WHERE domain_uuid=`+s.sqlParam(1)+` AND kind='ldap'`, d).Scan(&encoded, &sealed); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if sealed == "" || strings.Contains(encoded, config.LDAPBindPassword) || strings.Contains(sealed, config.LDAPBindPassword) {
|
||||||
|
t.Fatal("provider secret stored in plaintext")
|
||||||
|
}
|
||||||
config.LDAPBindPassword = ""
|
config.LDAPBindPassword = ""
|
||||||
config.LDAPSearchFilter = "(mail={{username}})"
|
config.LDAPSearchFilter = "(mail={{username}})"
|
||||||
if err = s.SetAuthProviderConfig(d, config); err != nil {
|
if err = s.SetAuthProviderConfig(d, config); err != nil {
|
||||||
@@ -180,6 +187,11 @@ func TestAccountBackendExternalIdentity(t *testing.T) {
|
|||||||
if err = s.BindExternalIdentity(second.UUID, "ldap", provider.UUID, "", "immutable-id", nil); !errors.Is(err, ErrAccessDenied) {
|
if err = s.BindExternalIdentity(second.UUID, "ldap", provider.UUID, "", "immutable-id", nil); !errors.Is(err, ErrAccessDenied) {
|
||||||
t.Fatal("identity owner replaced", err)
|
t.Fatal("identity owner replaced", err)
|
||||||
}
|
}
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if err = s.BindExternalIdentity(p.UUID, "ldap", provider.UUID, "", "immutable-id", nil); err != nil {
|
||||||
|
t.Fatal("identical owner binding must be idempotent", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if _, err = s.ProvisionExternalAccount(d, "rollback-ext", "", "", "ldap", provider.UUID, "", "immutable-id", nil); !errors.Is(err, ErrAccessDenied) {
|
if _, err = s.ProvisionExternalAccount(d, "rollback-ext", "", "", "ldap", provider.UUID, "", "immutable-id", nil); !errors.Is(err, ErrAccessDenied) {
|
||||||
t.Fatal("duplicate identity provisioned", err)
|
t.Fatal("duplicate identity provisioned", err)
|
||||||
}
|
}
|
||||||
@@ -222,8 +234,51 @@ func TestAccountBackendExternalIdentity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAccountBackendProviderSecrets(t *testing.T) {
|
||||||
|
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
|
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
||||||
|
s, d := accountBackendStore(t, b)
|
||||||
|
s.authKey = make([]byte, 32)
|
||||||
|
for _, config := range []AuthProviderConfig{
|
||||||
|
{Kind: "oidc", Enabled: true, Issuer: "https://issuer.example.test", ClientID: "synthetic", ClientSecret: "private-oidc-secret", OIDCMatchBy: "preferred_username"},
|
||||||
|
{Kind: "smtp", Enabled: true, SMTPAddress: "smtp.example.test:587", SMTPPassword: "private-smtp-secret"},
|
||||||
|
validLDAPProviderConfig(),
|
||||||
|
} {
|
||||||
|
t.Run(config.Kind, func(t *testing.T) {
|
||||||
|
if err := s.SetAuthProviderConfig(d, config); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
before, err := s.AuthProviderConfig(d, config.Kind)
|
||||||
|
if err != nil || before.UUID == "" || before.ClientSecret != config.ClientSecret || before.SMTPPassword != config.SMTPPassword || before.LDAPBindPassword != config.LDAPBindPassword {
|
||||||
|
t.Fatal("provider secret round trip", err)
|
||||||
|
}
|
||||||
|
config.ClientSecret, config.SMTPPassword, config.LDAPBindPassword = "", "", ""
|
||||||
|
config.Enabled = false
|
||||||
|
if err := s.SetAuthProviderConfig(d, config); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
after, err := s.AuthProviderConfig(d, config.Kind)
|
||||||
|
if err != nil || after.Enabled || after.UUID != before.UUID || after.ClientSecret != before.ClientSecret || after.SMTPPassword != before.SMTPPassword || after.LDAPBindPassword != before.LDAPBindPassword {
|
||||||
|
t.Fatal("provider secret preservation", err)
|
||||||
|
}
|
||||||
|
if config.Kind == "oidc" && after.OIDCMatchBy != "preferred_username" {
|
||||||
|
t.Fatal("account match mode lost")
|
||||||
|
}
|
||||||
|
s.ReadOnly = true
|
||||||
|
config.Enabled = true
|
||||||
|
err = s.SetAuthProviderConfig(d, config)
|
||||||
|
s.ReadOnly = false
|
||||||
|
if !errors.Is(err, ErrReadOnly) {
|
||||||
|
t.Fatal("read-only provider write", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAccountBackendTOTP(t *testing.T) {
|
func TestAccountBackendTOTP(t *testing.T) {
|
||||||
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} {
|
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
||||||
s, d := accountBackendStore(t, b)
|
s, d := accountBackendStore(t, b)
|
||||||
s.authKey = make([]byte, 32) // Synthetic credential encryption key.
|
s.authKey = make([]byte, 32) // Synthetic credential encryption key.
|
||||||
@@ -238,6 +293,12 @@ func TestAccountBackendTOTP(t *testing.T) {
|
|||||||
if s.HasTOTP(p.UUID) || s.PendingTOTPSecret(p.UUID) != secret {
|
if s.HasTOTP(p.UUID) || s.PendingTOTPSecret(p.UUID) != secret {
|
||||||
t.Fatal("pending enrollment mismatch")
|
t.Fatal("pending enrollment mismatch")
|
||||||
}
|
}
|
||||||
|
// Reopening enrollment replaces only the pending secret.
|
||||||
|
previous := secret
|
||||||
|
secret, err = s.BeginTOTPEnrollment(p.UUID)
|
||||||
|
if err != nil || secret == previous || s.PendingTOTPSecret(p.UUID) != secret {
|
||||||
|
t.Fatal("pending enrollment replacement", err)
|
||||||
|
}
|
||||||
code, err := totpCode(secret, time.Now().Unix()/30)
|
code, err := totpCode(secret, time.Now().Unix()/30)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -293,6 +354,15 @@ func TestAccountBackendTOTP(t *testing.T) {
|
|||||||
if _, e := s.CompleteTOTPLoginChallenge(d, challenge, "invalid"); !errors.Is(e, ErrAccessDenied) {
|
if _, e := s.CompleteTOTPLoginChallenge(d, challenge, "invalid"); !errors.Is(e, ErrAccessDenied) {
|
||||||
t.Fatal(e)
|
t.Fatal(e)
|
||||||
}
|
}
|
||||||
|
var attempts int
|
||||||
|
var consumed int64
|
||||||
|
if err := s.DB.QueryRow(`SELECT attempt_count,consumed_at_ms FROM auth_challenges WHERE token_hash=`+s.sqlParam(1), hashAuthToken(challenge)).Scan(&attempts, &consumed); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := min(i+1, 5)
|
||||||
|
if attempts != want || (consumed > 0) != (want == 5) {
|
||||||
|
t.Fatal("TOTP attempt limit", attempts, consumed, "want", want)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err = s.PurgeExpiredAuthArtifacts(); err != nil {
|
if err = s.PurgeExpiredAuthArtifacts(); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -312,7 +382,7 @@ func TestAccountBackendTOTP(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAccountBackendProfileAndSessionManagement(t *testing.T) {
|
func TestAccountBackendProfileAndSessionManagement(t *testing.T) {
|
||||||
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} {
|
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
||||||
s, d := accountBackendStore(t, b)
|
s, d := accountBackendStore(t, b)
|
||||||
p, err := s.BootstrapOwner(d, "owner", "synthetic password for backend tests", "Owner", "")
|
p, err := s.BootstrapOwner(d, "owner", "synthetic password for backend tests", "Owner", "")
|
||||||
@@ -382,7 +452,7 @@ func TestAccountBackendProfileAndSessionManagement(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAccountBackendBootstrapProjectionFailureIsAtomic(t *testing.T) {
|
func TestAccountBackendBootstrapProjectionFailureIsAtomic(t *testing.T) {
|
||||||
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} {
|
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
||||||
s, d := accountBackendStore(t, b)
|
s, d := accountBackendStore(t, b)
|
||||||
if _, err := s.DB.Exec(`ALTER TABLE campus_admin_grants RENAME COLUMN source TO missing_source`); err != nil {
|
if _, err := s.DB.Exec(`ALTER TABLE campus_admin_grants RENAME COLUMN source TO missing_source`); err != nil {
|
||||||
@@ -403,7 +473,12 @@ func TestAccountBackendBootstrapProjectionFailureIsAtomic(t *testing.T) {
|
|||||||
|
|
||||||
func accountBackendStore(t *testing.T, b storeSQLBackend) (*Store, string) {
|
func accountBackendStore(t *testing.T, b storeSQLBackend) (*Store, string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
s := testNamespaceStore(t, b)
|
s := testNamespaceCoreStore(t, b)
|
||||||
|
if b == storeMySQL {
|
||||||
|
if err := s.ensureMySQLAuthFoundation(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if b == storePostgreSQL {
|
if b == storePostgreSQL {
|
||||||
if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil {
|
if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -417,7 +492,7 @@ func accountBackendStore(t *testing.T, b storeSQLBackend) (*Store, string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAccountBackendLoginAndSession(t *testing.T) {
|
func TestAccountBackendLoginAndSession(t *testing.T) {
|
||||||
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} {
|
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
||||||
s, d := accountBackendStore(t, b)
|
s, d := accountBackendStore(t, b)
|
||||||
const password = "synthetic password for backend tests"
|
const password = "synthetic password for backend tests"
|
||||||
@@ -500,7 +575,7 @@ func TestAccountBackendLoginAndSession(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAccountBackendConcurrentBootstrap(t *testing.T) {
|
func TestAccountBackendConcurrentBootstrap(t *testing.T) {
|
||||||
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} {
|
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
t.Run(fmt.Sprint(b), func(t *testing.T) {
|
||||||
s, d := accountBackendStore(t, b)
|
s, d := accountBackendStore(t, b)
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
|
|||||||
@@ -168,9 +168,9 @@ func (s *Store) ProvisionExternalAccount(domainUUID, username, displayName, emai
|
|||||||
p.DisplayName = username
|
p.DisplayName = username
|
||||||
}
|
}
|
||||||
err = s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
err = s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend != storeSQLite {
|
||||||
var present bool
|
var present bool
|
||||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=$1 AND enabled=1 AND placement='local')`, domainUUID).Scan(&present); err != nil {
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=`+s.sqlParam(1)+` AND enabled=1 AND placement='local')`, domainUUID).Scan(&present); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !present {
|
if !present {
|
||||||
@@ -214,6 +214,9 @@ func (s *Store) ProvisionExternalAccount(domainUUID, username, displayName, emai
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) SetAuthProviderConfig(domainUUID string, config AuthProviderConfig) error {
|
func (s *Store) SetAuthProviderConfig(domainUUID string, config AuthProviderConfig) error {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
config.Kind = strings.ToLower(strings.TrimSpace(config.Kind))
|
config.Kind = strings.ToLower(strings.TrimSpace(config.Kind))
|
||||||
if config.Kind != "oidc" && config.Kind != "smtp" && config.Kind != "ldap" {
|
if config.Kind != "oidc" && config.Kind != "smtp" && config.Kind != "ldap" {
|
||||||
return errors.New("unsupported authentication provider")
|
return errors.New("unsupported authentication provider")
|
||||||
@@ -256,7 +259,11 @@ func (s *Store) SetAuthProviderConfig(domainUUID string, config AuthProviderConf
|
|||||||
enabled = 1
|
enabled = 1
|
||||||
}
|
}
|
||||||
// Preserve the current secret inside the UPSERT, not via a stale pre-read.
|
// Preserve the current secret inside the UPSERT, not via a stale pre-read.
|
||||||
_, err = s.DB.Exec(`INSERT INTO auth_providers(uuid,domain_uuid,kind,config_json,secret_encrypted,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(8)+`) ON CONFLICT(domain_uuid,kind) DO UPDATE SET config_json=excluded.config_json,secret_encrypted=CASE WHEN excluded.secret_encrypted='' THEN auth_providers.secret_encrypted ELSE excluded.secret_encrypted END,enabled=excluded.enabled,updated_at_ms=excluded.updated_at_ms`, uuid.NewString(), domainUUID, config.Kind, string(payload), encrypted, enabled, time.Now().UnixMilli(), time.Now().UnixMilli())
|
suffix := ` ON CONFLICT(domain_uuid,kind) DO UPDATE SET config_json=excluded.config_json,secret_encrypted=CASE WHEN excluded.secret_encrypted='' THEN auth_providers.secret_encrypted ELSE excluded.secret_encrypted END,enabled=excluded.enabled,updated_at_ms=excluded.updated_at_ms`
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
suffix = ` AS incoming ON DUPLICATE KEY UPDATE config_json=incoming.config_json,secret_encrypted=CASE WHEN incoming.secret_encrypted='' THEN auth_providers.secret_encrypted ELSE incoming.secret_encrypted END,enabled=incoming.enabled,updated_at_ms=incoming.updated_at_ms`
|
||||||
|
}
|
||||||
|
_, err = s.DB.Exec(`INSERT INTO auth_providers(uuid,domain_uuid,kind,config_json,secret_encrypted,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(8)+`)`+suffix, uuid.NewString(), domainUUID, config.Kind, string(payload), encrypted, enabled, time.Now().UnixMilli(), time.Now().UnixMilli())
|
||||||
return s.sqlError("auth provider update", err)
|
return s.sqlError("auth provider update", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -405,14 +412,38 @@ func (s *Store) PrincipalByDisplayName(domainUUID, displayName string) (*Princip
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) BindExternalIdentity(principalUUID, providerType, providerUUID, issuer, subject string, attributes any) error {
|
func (s *Store) BindExternalIdentity(principalUUID, providerType, providerUUID, issuer, subject string, attributes any) error {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
if strings.TrimSpace(subject) == "" || strings.TrimSpace(principalUUID) == "" {
|
if strings.TrimSpace(subject) == "" || strings.TrimSpace(principalUUID) == "" {
|
||||||
return ErrAccessDenied
|
return ErrAccessDenied
|
||||||
}
|
}
|
||||||
payload, err := json.Marshal(attributes)
|
payload, err := externalIdentityPayload(attributes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
// Serialize with provisioning and first-login binding. MySQL reports
|
||||||
|
// changed rows, so a repeated identical binding must not be mistaken
|
||||||
|
// for a denied rebind; test ownership explicitly under the same lock.
|
||||||
|
return s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
var owner, id string
|
||||||
|
err := tx.QueryRowContext(ctx, `SELECT uuid,principal_uuid FROM principal_identities WHERE provider_type=? AND provider_uuid=? AND issuer=? AND subject=?`, providerType, providerUUID, issuer, subject).Scan(&id, &owner)
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO principal_identities(uuid,principal_uuid,provider_type,provider_uuid,issuer,subject,attributes_json,created_at_ms) VALUES(?,?,?,?,?,?,?,?)`, uuid.NewString(), principalUUID, providerType, providerUUID, issuer, subject, payload, now)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if owner != principalUUID {
|
||||||
|
return ErrAccessDenied
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `UPDATE principal_identities SET attributes_json=? WHERE uuid=?`, payload, id)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
}
|
||||||
result, err := s.DB.Exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,provider_uuid,issuer,subject,attributes_json,created_at_ms) VALUES(`+s.sqlValues(8)+`) ON CONFLICT(provider_type,provider_uuid,issuer,subject) DO UPDATE SET attributes_json=excluded.attributes_json WHERE principal_identities.principal_uuid=excluded.principal_uuid`, uuid.NewString(), principalUUID, providerType, providerUUID, issuer, subject, string(payload), now)
|
result, err := s.DB.Exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,provider_uuid,issuer,subject,attributes_json,created_at_ms) VALUES(`+s.sqlValues(8)+`) ON CONFLICT(provider_type,provider_uuid,issuer,subject) DO UPDATE SET attributes_json=excluded.attributes_json WHERE principal_identities.principal_uuid=excluded.principal_uuid`, uuid.NewString(), principalUUID, providerType, providerUUID, issuer, subject, string(payload), now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -430,7 +461,7 @@ func (s *Store) BindExternalIdentity(principalUUID, providerType, providerUUID,
|
|||||||
func (s *Store) PrincipalByExternalIdentity(domainUUID, providerType, providerUUID, issuer, subject string) (*Principal, error) {
|
func (s *Store) PrincipalByExternalIdentity(domainUUID, providerType, providerUUID, issuer, subject string) (*Principal, error) {
|
||||||
var p Principal
|
var p Principal
|
||||||
err := s.DB.QueryRow(`SELECT p.uuid,COALESCE((SELECT subject FROM principal_identities x WHERE x.principal_uuid=p.uuid AND x.provider_type='password' ORDER BY subject,uuid LIMIT 1),p.uuid),p.display_name,p.email,p.state,length(p.avatar)>0 FROM principal_identities i JOIN principals p ON p.uuid=i.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active' WHERE i.provider_type=`+s.sqlParam(2)+` AND i.provider_uuid=`+s.sqlParam(3)+` AND i.issuer=`+s.sqlParam(4)+` AND i.subject=`+s.sqlParam(5)+` AND p.state IN ('active','readonly')`, domainUUID, providerType, providerUUID, issuer, subject).Scan(&p.UUID, &p.Username, &p.DisplayName, &p.Email, &p.State, &p.HasAvatar)
|
err := s.DB.QueryRow(`SELECT p.uuid,COALESCE((SELECT subject FROM principal_identities x WHERE x.principal_uuid=p.uuid AND x.provider_type='password' ORDER BY subject,uuid LIMIT 1),p.uuid),p.display_name,p.email,p.state,length(p.avatar)>0 FROM principal_identities i JOIN principals p ON p.uuid=i.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active' WHERE i.provider_type=`+s.sqlParam(2)+` AND i.provider_uuid=`+s.sqlParam(3)+` AND i.issuer=`+s.sqlParam(4)+` AND i.subject=`+s.sqlParam(5)+` AND p.state IN ('active','readonly')`, domainUUID, providerType, providerUUID, issuer, subject).Scan(&p.UUID, &p.Username, &p.DisplayName, &p.Email, &p.State, &p.HasAvatar)
|
||||||
return &p, err
|
return &p, s.sqlError("external identity lookup", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) CreateAuthChallenge(domainUUID, principalUUID, kind string, payload any, lifetime time.Duration) (string, error) {
|
func (s *Store) CreateAuthChallenge(domainUUID, principalUUID, kind string, payload any, lifetime time.Duration) (string, error) {
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// This is a persistence pilot, not a server/authentication endpoint. The caller
|
||||||
|
// MUST authenticate and authorize every administrator mutation. It intentionally
|
||||||
|
// exposes neither *Store nor grant-only checks as a complete authorization API.
|
||||||
|
// MFA/provider persistence is internally tested but not exposed as a login API.
|
||||||
|
// Audit/locality policy, CLI handoff and Domain deletion remain unported.
|
||||||
|
type MySQLIdentityRepository struct{ store *Store }
|
||||||
|
|
||||||
|
func NewMySQLIdentityRepository(database *sql.DB) *MySQLIdentityRepository {
|
||||||
|
return &MySQLIdentityRepository{store: &Store{DB: database, sqlBackend: storeMySQL}}
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) PrepareSchema(ctx context.Context) error {
|
||||||
|
return r.store.ensureMySQLAuthFoundation(ctx)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) InspectSchema(ctx context.Context) (db.MySQLMigrationStatus, error) {
|
||||||
|
base, err := NewMySQLNamespaceRepository(r.store.DB).InspectSchema(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return base, err
|
||||||
|
}
|
||||||
|
auth, err := db.InspectMySQLMigrations(ctx, r.store.DB, "store-auth-core", mysqlAuthMigrations())
|
||||||
|
if err != nil {
|
||||||
|
return auth, err
|
||||||
|
}
|
||||||
|
result := db.MySQLMigrationStatus{Applied: base.Applied + auth.Applied, Pending: base.Pending + auth.Pending, Dirty: base.Dirty || auth.Dirty}
|
||||||
|
if base.Dirty {
|
||||||
|
result.DirtyComponent, result.NextOperation = base.DirtyComponent, base.NextOperation
|
||||||
|
} else if auth.Dirty {
|
||||||
|
result.DirtyComponent, result.NextOperation = auth.DirtyComponent, auth.NextOperation
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) ResumeSchema(ctx context.Context) error {
|
||||||
|
base, err := NewMySQLNamespaceRepository(r.store.DB).InspectSchema(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if base.Dirty || base.Pending != 0 {
|
||||||
|
return db.ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
return db.ResumeMySQLMigrations(ctx, r.store.DB, "store-auth-core", mysqlAuthMigrations())
|
||||||
|
}
|
||||||
|
func mysqlIdentityIDs(ids ...string) error {
|
||||||
|
for _, id := range ids {
|
||||||
|
if err := mysqlNamespaceUUID(id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) BootstrapOwner(ctx context.Context, domain, username, password, displayName, email string) (*Principal, error) {
|
||||||
|
if err := mysqlIdentityIDs(domain); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r.store.BootstrapOwnerContext(ctx, domain, username, password, displayName, email)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) CreateAccount(ctx context.Context, domain, username, password, displayName, email string) (*Principal, error) {
|
||||||
|
if err := mysqlIdentityIDs(domain); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r.store.CreatePasswordAccountContext(ctx, domain, username, password, displayName, email)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) Principals(ctx context.Context, domain string) ([]Principal, error) {
|
||||||
|
if err := mysqlIdentityIDs(domain); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r.store.ListDomainPrincipalsContext(ctx, domain)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) Sessions(ctx context.Context, domain string) ([]AuthSessionInfo, error) {
|
||||||
|
if err := mysqlIdentityIDs(domain); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r.store.ListAuthSessionsContext(ctx, domain)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) RevokeSession(ctx context.Context, domain, session string) error {
|
||||||
|
if err := mysqlIdentityIDs(domain, session); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.RevokeAuthSessionByIDContext(ctx, domain, session)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) SetPrincipalState(ctx context.Context, domain, principal, state string) error {
|
||||||
|
if err := mysqlIdentityIDs(domain, principal); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.SetPrincipalStateContext(ctx, domain, principal, state)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) CreateGroup(ctx context.Context, domain, owner, name, title, description, visibility string) (*Group, error) {
|
||||||
|
if err := mysqlIdentityIDs(domain, owner); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r.store.CreateGroupContext(ctx, domain, owner, name, title, description, visibility)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) Groups(ctx context.Context, domain, principal string) ([]Group, error) {
|
||||||
|
if err := mysqlIdentityIDs(domain); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if principal != "" {
|
||||||
|
if err := mysqlIdentityIDs(principal); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r.store.ListGroupsContext(ctx, domain, principal)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) Group(ctx context.Context, domain, name string) (*Group, error) {
|
||||||
|
if err := mysqlIdentityIDs(domain); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r.store.GroupByNameContext(ctx, domain, name)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) Members(ctx context.Context, domain, group string) ([]GroupMember, error) {
|
||||||
|
if err := r.groupScope(ctx, domain, group); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r.store.ListGroupMembersContext(ctx, group)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) groupScope(ctx context.Context, domain, group string) error {
|
||||||
|
if err := mysqlIdentityIDs(domain, group); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := r.store.GroupByUUIDContext(ctx, domain, group)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) AddMember(ctx context.Context, domain, group, username, role string) error {
|
||||||
|
if err := mysqlIdentityIDs(domain, group); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.AddGroupMemberByUsernameContext(ctx, domain, group, username, role)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) RemoveMember(ctx context.Context, domain, group, membership string, ownerAuthority bool) error {
|
||||||
|
if err := mysqlIdentityIDs(membership); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := r.groupScope(ctx, domain, group); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.RemoveGroupMemberWithAuthorityContext(ctx, group, membership, ownerAuthority)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) SetPermission(ctx context.Context, domain, group, path, permission string) error {
|
||||||
|
if err := r.groupScope(ctx, domain, group); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.SetGroupPermissionContext(ctx, group, path, permission)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) SetInheritance(ctx context.Context, domain, group string, enabled bool) error {
|
||||||
|
if err := r.groupScope(ctx, domain, group); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.SetCampusAdminInheritanceContext(ctx, group, enabled)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) IsBuiltinAdmin(ctx context.Context, domain, principal, key string) (bool, error) {
|
||||||
|
if err := mysqlIdentityIDs(domain, principal); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return r.store.IsBuiltinGroupAdminContext(ctx, domain, principal, key)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) CreateLocalDomain(ctx context.Context, campus, name, title, host string, enabled bool) error {
|
||||||
|
if err := mysqlIdentityIDs(campus); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.writeDomain(ctx, 0, false, campus, name, title, host, "local", "", "", enabled)
|
||||||
|
}
|
||||||
|
func (r *MySQLIdentityRepository) UpdateLocalDomain(ctx context.Context, id int64, campus, name, title, host string, enabled bool) error {
|
||||||
|
if err := mysqlIdentityIDs(campus); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.writeDomain(ctx, id, true, campus, name, title, host, "local", "", "", enabled)
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// These definitions are owned native MySQL DDL, not translations of SQLite
|
||||||
|
// migrations. NO PAD binary collation keeps identifiers and Path scopes exact.
|
||||||
|
type mysqlAuthColumn struct{ name, kind, defaultSQL string }
|
||||||
|
type mysqlAuthTable struct {
|
||||||
|
name string
|
||||||
|
columns []mysqlAuthColumn
|
||||||
|
keys []string // first is primary; remaining keys are unique
|
||||||
|
indexes []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func mysqlAuthMigrations() []db.MySQLMigration {
|
||||||
|
const id = "varchar(36)"
|
||||||
|
const text = "longtext"
|
||||||
|
const state = "varchar(32)"
|
||||||
|
const number = "bigint"
|
||||||
|
tables := []mysqlAuthTable{
|
||||||
|
{"principals", []mysqlAuthColumn{{"uuid", id, ""}, {"display_name", text, "('')"}, {"email", text, "('')"}, {"state", state, "'active'"}, {"avatar", "longblob", "(X'')"}, {"avatar_content_type", "varchar(128)", "''"}, {"created_at_ms", number, ""}, {"updated_at_ms", number, ""}}, []string{"uuid"}, nil},
|
||||||
|
{"principal_identities", []mysqlAuthColumn{{"uuid", id, ""}, {"principal_uuid", id, ""}, {"provider_type", "varchar(32)", ""}, {"provider_uuid", id, "''"}, {"issuer", "varchar(255)", "''"}, {"subject", "varchar(255)", ""}, {"attributes_json", text, "('{}')"}, {"created_at_ms", number, ""}}, []string{"uuid", "provider_type,provider_uuid,issuer,subject"}, []string{"principal_uuid,provider_type,subject"}},
|
||||||
|
{"domain_memberships", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"principal_uuid", id, ""}, {"state", state, "'active'"}, {"created_at_ms", number, ""}}, []string{"uuid", "domain_uuid,principal_uuid"}, []string{"principal_uuid,domain_uuid"}},
|
||||||
|
{"auth_roles", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"name", "varchar(128)", ""}, {"description", text, "('')"}, {"created_at_ms", number, ""}}, []string{"uuid", "domain_uuid,name"}, nil},
|
||||||
|
{"auth_role_bindings", []mysqlAuthColumn{{"membership_uuid", id, ""}, {"role_uuid", id, ""}, {"created_at_ms", number, ""}}, []string{"membership_uuid,role_uuid"}, nil},
|
||||||
|
{"auth_capability_grants", []mysqlAuthColumn{{"uuid", id, ""}, {"role_uuid", id, ""}, {"capability", "varchar(32)", ""}, {"target_type", "varchar(32)", ""}, {"target_id", "varchar(512)", "'*'"}, {"created_at_ms", number, ""}}, []string{"uuid", "role_uuid,capability,target_type,target_id"}, nil},
|
||||||
|
{"groups", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"name", "varchar(64)", ""}, {"display_name", text, "('')"}, {"description", text, "('')"}, {"visibility", "varchar(32)", "'members'"}, {"state", state, "'active'"}, {"builtin_key", "varchar(32)", "''"}, {"inherit_members", "int", "0"}, {"created_at_ms", number, ""}, {"updated_at_ms", number, ""}}, []string{"uuid", "domain_uuid,name"}, nil},
|
||||||
|
{"group_members", []mysqlAuthColumn{{"group_uuid", id, ""}, {"membership_uuid", id, ""}, {"member_role", "varchar(32)", "'member'"}, {"source", "varchar(128)", "'local'"}, {"created_at_ms", number, ""}}, []string{"group_uuid,membership_uuid"}, []string{"membership_uuid,group_uuid"}},
|
||||||
|
{"campus_admin_grants", []mysqlAuthColumn{{"group_uuid", id, ""}, {"membership_uuid", id, ""}, {"source", "varchar(128)", ""}, {"member_role", "varchar(32)", ""}, {"created_at_ms", number, ""}}, []string{"group_uuid,membership_uuid,source"}, []string{"membership_uuid"}},
|
||||||
|
{"campus_admin_membership_origins", []mysqlAuthColumn{{"membership_uuid", id, ""}, {"domain_uuid", id, ""}, {"principal_uuid", id, ""}}, []string{"membership_uuid", "domain_uuid,principal_uuid"}, nil},
|
||||||
|
{"campus_admin_migrations", []mysqlAuthColumn{{"key", "varchar(128)", ""}}, []string{"key"}, nil},
|
||||||
|
{"auth_sessions", []mysqlAuthColumn{{"uuid", id, ""}, {"token_hash", "varchar(128)", ""}, {"principal_uuid", id, ""}, {"domain_uuid", id, ""}, {"auth_time_ms", number, ""}, {"expires_at_ms", number, ""}, {"last_seen_at_ms", number, ""}, {"mfa_level", "int", "0"}, {"revoked_at_ms", number, "0"}}, []string{"uuid", "token_hash"}, []string{"domain_uuid,principal_uuid,revoked_at_ms"}},
|
||||||
|
{"group_permissions", []mysqlAuthColumn{{"uuid", id, ""}, {"group_uuid", id, ""}, {"scope_path", "varchar(512)", ""}, {"permission", "varchar(32)", ""}, {"created_at_ms", number, ""}}, []string{"uuid", "group_uuid,scope_path"}, nil},
|
||||||
|
{"auth_credentials", []mysqlAuthColumn{{"uuid", id, ""}, {"principal_uuid", id, ""}, {"kind", "varchar(32)", ""}, {"identifier", "varchar(255)", "''"}, {"secret_hash", text, ""}, {"parameters_json", text, "('{}')"}, {"enabled", "int", "1"}, {"created_at_ms", number, ""}, {"updated_at_ms", number, ""}}, []string{"uuid", "kind,identifier"}, nil},
|
||||||
|
}
|
||||||
|
steps := []db.MySQLMigration{
|
||||||
|
mysqlAuthTableMigration(1, "identity membership and group foundation", tables),
|
||||||
|
mysqlAuthTableMigration(2, "authentication challenges and provider configuration", []mysqlAuthTable{
|
||||||
|
{"auth_challenges", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"principal_uuid", id, "''"}, {"kind", state, ""}, {"token_hash", "varchar(128)", ""}, {"payload_json", text, "('{}')"}, {"expires_at_ms", number, ""}, {"consumed_at_ms", number, "0"}, {"attempt_count", "int", "0"}, {"created_at_ms", number, ""}}, []string{"uuid", "token_hash"}, []string{"expires_at_ms"}},
|
||||||
|
{"auth_providers", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"kind", state, ""}, {"config_json", text, "('{}')"}, {"secret_encrypted", text, "('')"}, {"enabled", "int", "0"}, {"created_at_ms", number, ""}, {"updated_at_ms", number, ""}}, []string{"uuid", "domain_uuid,kind"}, nil},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
// Inspect validates the latest contract only, since later versions may
|
||||||
|
// replace older columns. This additive version must retain all v1 checks.
|
||||||
|
steps[1].Assertions = append(append([]string{}, steps[0].Assertions...), steps[1].Assertions...)
|
||||||
|
return steps
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep generated version 1 operations/assertions byte-identical: deployed
|
||||||
|
// journals checksum the plan. Extend with new versions, never rewrite history.
|
||||||
|
func mysqlAuthTableMigration(version int, name string, tables []mysqlAuthTable) db.MySQLMigration {
|
||||||
|
var ops []db.MySQLOperation
|
||||||
|
var checks []string
|
||||||
|
for _, table := range tables {
|
||||||
|
var definitions, signature []string
|
||||||
|
for _, col := range table.columns {
|
||||||
|
definition := "`" + col.name + "` " + col.kind + " NOT NULL"
|
||||||
|
if col.defaultSQL != "" {
|
||||||
|
definition += " DEFAULT " + col.defaultSQL
|
||||||
|
}
|
||||||
|
definitions = append(definitions, definition)
|
||||||
|
collation := ""
|
||||||
|
if strings.Contains(col.kind, "char") || strings.Contains(col.kind, "text") {
|
||||||
|
collation = "utf8mb4_0900_bin"
|
||||||
|
}
|
||||||
|
signature = append(signature, col.name+":"+col.kind+":NO:"+collation)
|
||||||
|
}
|
||||||
|
definitions = append(definitions, "PRIMARY KEY("+mysqlAuthIdentifiers(table.keys[0])+")")
|
||||||
|
check := mysqlMLTableCheck(table.name, strings.Join(signature, "|"), table.keys[0], 0)
|
||||||
|
for i, key := range table.keys[1:] {
|
||||||
|
name := fmt.Sprintf("uq_%d", i)
|
||||||
|
definitions = append(definitions, "UNIQUE KEY "+name+"("+mysqlAuthIdentifiers(key)+")")
|
||||||
|
check += fmt.Sprintf(` AND (SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index SEPARATOR ',') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='%s' AND index_name='%s' AND non_unique=0)='%s'`, table.name, name, key)
|
||||||
|
}
|
||||||
|
for i, key := range table.indexes {
|
||||||
|
definitions = append(definitions, fmt.Sprintf("INDEX ix_%d(%s)", i, mysqlAuthIdentifiers(key)))
|
||||||
|
}
|
||||||
|
statement := "CREATE TABLE `" + table.name + "`(" + strings.Join(definitions, ",") + ") ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin"
|
||||||
|
ops = append(ops, db.MySQLOperation{SQL: statement, Check: check, ReplaySafe: true})
|
||||||
|
checks = append(checks, check)
|
||||||
|
}
|
||||||
|
return db.MySQLMigration{Version: version, Name: name, Operations: ops, Assertions: checks}
|
||||||
|
}
|
||||||
|
func mysqlAuthIdentifiers(names string) string {
|
||||||
|
return "`" + strings.ReplaceAll(names, ",", "`,`") + "`"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ensureMySQLAuthFoundation(ctx context.Context) error {
|
||||||
|
if err := NewMySQLNamespaceRepository(s.DB).PrepareSchema(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return db.ApplyMySQLMigrations(ctx, s.DB, "store-auth-core", mysqlAuthMigrations())
|
||||||
|
}
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMySQLIdentityDomainLifecycle(t *testing.T) {
|
||||||
|
database := mysqlTestDatabase(t)
|
||||||
|
r := NewMySQLIdentityRepository(database)
|
||||||
|
ns := NewMySQLNamespaceRepository(database)
|
||||||
|
ctx := context.Background()
|
||||||
|
if e := r.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := ns.CreateCampus(ctx, "home", "キャンパス", "ja", "standalone", "home.example.test", true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
campuses, e := ns.Campuses(ctx)
|
||||||
|
if e != nil || len(campuses) != 1 {
|
||||||
|
t.Fatal(campuses, e)
|
||||||
|
}
|
||||||
|
campus := campuses[0]
|
||||||
|
if e := r.CreateLocalDomain(ctx, campus.UUID, "default", "ドメイン", "", true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
domain, e := ns.ResolveHost(ctx, "home.example.test")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
const password = "synthetic password for identity pilot"
|
||||||
|
owner, e := r.BootstrapOwner(ctx, domain.UUID, "owner", password, "所有者", "owner@example.test")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
member, e := r.CreateAccount(ctx, domain.UUID, "member", password, "利用者", "member@example.test")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := r.CreateAccount(ctx, domain.UUID, "member", password, "private duplicate title", ""); e == nil || strings.Contains(e.Error(), "private duplicate title") {
|
||||||
|
t.Fatal("duplicate account handling", e)
|
||||||
|
}
|
||||||
|
people, e := r.Principals(ctx, domain.UUID)
|
||||||
|
if e != nil || len(people) != 2 {
|
||||||
|
t.Fatal(people, e)
|
||||||
|
}
|
||||||
|
g, e := r.CreateGroup(ctx, domain.UUID, owner.UUID, "team", "チーム", "説明", "members")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if e := r.AddMember(ctx, domain.UUID, g.UUID, "member", "member"); e != nil {
|
||||||
|
t.Fatal("repeat add", e)
|
||||||
|
}
|
||||||
|
if e := r.SetPermission(ctx, domain.UUID, g.UUID, "/literal%_", "read_write"); e != nil {
|
||||||
|
t.Fatal("repeat permission", e)
|
||||||
|
}
|
||||||
|
if e := r.SetPrincipalState(ctx, domain.UUID, member.UUID, "active"); e != nil {
|
||||||
|
t.Fatal("repeat state", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
members, e := r.Members(ctx, domain.UUID, g.UUID)
|
||||||
|
if e != nil || len(members) != 2 {
|
||||||
|
t.Fatal(members, e)
|
||||||
|
}
|
||||||
|
if e := r.AddMember(ctx, domain.UUID, g.UUID, "owner", "member"); e == nil {
|
||||||
|
t.Fatal("owner downgraded")
|
||||||
|
}
|
||||||
|
for _, m := range members {
|
||||||
|
if m.PrincipalUUID == member.UUID {
|
||||||
|
if e := r.RemoveMember(ctx, domain.UUID, g.UUID, m.MembershipUUID, false); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e := r.CreateLocalDomain(ctx, campus.UUID, "child", "Child", "child", true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
results := make(chan error, 2)
|
||||||
|
for _, name := range []string{"race-one", "race-two"} {
|
||||||
|
go func(name string) { results <- r.CreateLocalDomain(ctx, campus.UUID, name, "Race", "same-host", true) }(name)
|
||||||
|
}
|
||||||
|
success := 0
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if <-results == nil {
|
||||||
|
success++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if success != 1 {
|
||||||
|
t.Fatal("Domain host concurrency", success)
|
||||||
|
}
|
||||||
|
child, e := ns.ResolveHost(ctx, "child.home.example.test")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if got, e := ns.Config(ctx, child.UUID, "locale"); e != nil || got != "ja" {
|
||||||
|
t.Fatal("locale inheritance", got, e)
|
||||||
|
}
|
||||||
|
if allowed, e := r.IsBuiltinAdmin(ctx, child.UUID, owner.UUID, "campus_admin"); e != nil || !allowed {
|
||||||
|
t.Fatal("admin inheritance", e)
|
||||||
|
}
|
||||||
|
if _, e := r.Members(ctx, child.UUID, g.UUID); !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
t.Fatal("cross-domain group", e)
|
||||||
|
}
|
||||||
|
root, e := r.Group(ctx, domain.UUID, "campus_admin")
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if e := r.SetInheritance(ctx, domain.UUID, root.UUID, true); e != nil {
|
||||||
|
t.Fatal("repeat inheritance", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
token, e := r.store.CreateBrowserAuthSession(child.UUID, owner.UUID, 1)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
sessions, e := r.Sessions(ctx, child.UUID)
|
||||||
|
if e != nil || len(sessions) != 1 {
|
||||||
|
t.Fatal("session administration", sessions, e)
|
||||||
|
}
|
||||||
|
if e := r.RevokeSession(ctx, domain.UUID, sessions[0].UUID); !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
t.Fatal("cross-domain session revocation", e)
|
||||||
|
}
|
||||||
|
if e := r.RevokeSession(ctx, child.UUID, sessions[0].UUID); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := r.store.PrincipalForSession(child.UUID, token); !errors.Is(e, ErrAccessDenied) {
|
||||||
|
t.Fatal("administratively revoked session accepted", e)
|
||||||
|
}
|
||||||
|
token, e = r.store.CreateBrowserAuthSession(child.UUID, owner.UUID, 1)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := ns.CreateCampus(ctx, "other", "Other", "en", "standalone", "other.example.test", true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
campuses, e = ns.Campuses(ctx)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
var other string
|
||||||
|
for _, c := range campuses {
|
||||||
|
if c.UUID != campus.UUID {
|
||||||
|
other = c.UUID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e := r.UpdateLocalDomain(ctx, child.ID, other, child.Name, "Moved", child.Domain, true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if allowed, e := r.IsBuiltinAdmin(ctx, child.UUID, owner.UUID, "campus_admin"); e != nil || allowed {
|
||||||
|
t.Fatal("stale inherited admin", e)
|
||||||
|
}
|
||||||
|
if _, e := r.store.PrincipalForSession(child.UUID, token); !errors.Is(e, ErrAccessDenied) {
|
||||||
|
t.Fatal("stale session", e)
|
||||||
|
}
|
||||||
|
if _, e := database.Exec(`UPDATE domains SET placement='remote' WHERE uuid=?`, child.UUID); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.UpdateLocalDomain(ctx, child.ID, other, child.Name, "Must not change", child.Domain, true); !errors.Is(e, ErrBackendFeatureUnavailable) {
|
||||||
|
t.Fatal("remote Domain adopted locally", e)
|
||||||
|
}
|
||||||
|
if _, e := database.Exec(`UPDATE domains SET placement='local' WHERE uuid=?`, child.UUID); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.CreateLocalDomain(ctx, campus.UUID, "collision", "Collision", "", true); e == nil {
|
||||||
|
t.Fatal("host collision")
|
||||||
|
}
|
||||||
|
if e := ns.CreateCampus(ctx, "controller", "Controller", "en", "controller", "controller.example.test", true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
campuses, e = ns.Campuses(ctx)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for _, c := range campuses {
|
||||||
|
if c.Name == "controller" {
|
||||||
|
if e := r.CreateLocalDomain(ctx, c.UUID, "remote", "Remote", "remote", true); !errors.Is(e, ErrBackendFeatureUnavailable) {
|
||||||
|
t.Fatal("federation bypass", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A failing inheritance write must roll back Domain, locale and built-ins.
|
||||||
|
before, e := ns.Domains(ctx)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := database.Exec(`ALTER TABLE campus_admin_grants RENAME COLUMN source TO missing_source`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.CreateLocalDomain(ctx, campus.UUID, "rollback", "Rollback", "rollback", true); e == nil {
|
||||||
|
t.Fatal("partial Domain accepted")
|
||||||
|
}
|
||||||
|
after, e := ns.Domains(ctx)
|
||||||
|
if e != nil || len(before) != len(after) {
|
||||||
|
t.Fatal("partial Domain remains", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLIdentitySchemaAndCancellation(t *testing.T) {
|
||||||
|
database := mysqlTestDatabase(t)
|
||||||
|
r := NewMySQLIdentityRepository(database)
|
||||||
|
ctx := context.Background()
|
||||||
|
if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 5 {
|
||||||
|
t.Fatal(status, e)
|
||||||
|
}
|
||||||
|
if e := r.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal("repeat prepare", e)
|
||||||
|
}
|
||||||
|
if _, e := database.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=1 WHERE component='store-auth-core' AND version=2`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.PrepareSchema(ctx); !errors.Is(e, db.ErrMySQLMigrationDirty) {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.ResumeSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 0 || status.Dirty {
|
||||||
|
t.Fatal(status, e)
|
||||||
|
}
|
||||||
|
cancelled, cancel := context.WithCancel(ctx)
|
||||||
|
cancel()
|
||||||
|
if _, e := r.store.ListDomainPrincipalsContext(cancelled, "unused"); !errors.Is(e, context.Canceled) {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
const validID = "00000000-0000-4000-a000-000000000001"
|
||||||
|
if _, e := r.Sessions(cancelled, validID); !errors.Is(e, context.Canceled) {
|
||||||
|
t.Fatal("cancel session list", e)
|
||||||
|
}
|
||||||
|
if e := r.RevokeSession(cancelled, validID, validID); !errors.Is(e, context.Canceled) {
|
||||||
|
t.Fatal("cancel session revocation", e)
|
||||||
|
}
|
||||||
|
r.store.ReadOnly = true
|
||||||
|
if e := r.RevokeSession(ctx, validID, validID); !errors.Is(e, ErrReadOnly) {
|
||||||
|
t.Fatal("read-only session revocation", e)
|
||||||
|
}
|
||||||
|
r.store.ReadOnly = false
|
||||||
|
if e := r.CreateLocalDomain(cancelled, "00000000-0000-4000-a000-000000000001", "cancelled", "Cancelled", "cancelled", true); !errors.Is(e, context.Canceled) {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := database.Exec(`ALTER TABLE group_permissions MODIFY scope_path VARCHAR(256) NOT NULL`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := r.InspectSchema(ctx); e == nil {
|
||||||
|
t.Fatal("schema drift accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLIdentitySchemaUpgradePreservesAccounts(t *testing.T) {
|
||||||
|
database := mysqlTestDatabase(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := NewMySQLNamespaceRepository(database).PrepareSchema(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
plan := mysqlAuthMigrations()
|
||||||
|
if err := db.ApplyMySQLMigrations(ctx, database, "store-auth-core", plan[:1]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var before string
|
||||||
|
if err := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='store-auth-core' AND version=1`).Scan(&before); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := database.Exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES('upgrade-user','既存の利用者',1,1)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := NewMySQLIdentityRepository(database)
|
||||||
|
if status, err := r.InspectSchema(ctx); err != nil || status.Pending != 1 || status.Applied != 4 {
|
||||||
|
t.Fatal(status, err)
|
||||||
|
}
|
||||||
|
if err := r.PrepareSchema(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var after, title string
|
||||||
|
if err := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='store-auth-core' AND version=1`).Scan(&after); err != nil || after != before {
|
||||||
|
t.Fatal("historical checksum changed", err)
|
||||||
|
}
|
||||||
|
if err := database.QueryRow(`SELECT display_name FROM principals WHERE uuid='upgrade-user'`).Scan(&title); err != nil || title != "既存の利用者" {
|
||||||
|
t.Fatal("existing principal changed", err)
|
||||||
|
}
|
||||||
|
if status, err := r.InspectSchema(ctx); err != nil || status.Pending != 0 || status.Applied != 5 {
|
||||||
|
t.Fatal(status, err)
|
||||||
|
}
|
||||||
|
if _, err := database.Exec(`ALTER TABLE auth_providers DROP INDEX uq_0`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := r.InspectSchema(ctx); err == nil {
|
||||||
|
t.Fatal("provider uniqueness drift accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -66,7 +66,11 @@ func (s *Store) BeginTOTPEnrollment(principalUUID string) (string, error) {
|
|||||||
}
|
}
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
err = s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
err = s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
||||||
_, err := tx.ExecContext(ctx, `INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,parameters_json,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`) ON CONFLICT(kind,identifier) DO UPDATE SET secret_hash=excluded.secret_hash,parameters_json='{}',enabled=0,updated_at_ms=excluded.updated_at_ms`, uuid.NewString(), principalUUID, "totp-pending", principalUUID, encrypted, "{}", 0, now, now)
|
suffix := ` ON CONFLICT(kind,identifier) DO UPDATE SET secret_hash=excluded.secret_hash,parameters_json='{}',enabled=0,updated_at_ms=excluded.updated_at_ms`
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
suffix = ` AS incoming ON DUPLICATE KEY UPDATE secret_hash=incoming.secret_hash,parameters_json='{}',enabled=0,updated_at_ms=incoming.updated_at_ms`
|
||||||
|
}
|
||||||
|
_, err := tx.ExecContext(ctx, `INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,parameters_json,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`)`+suffix, uuid.NewString(), principalUUID, "totp-pending", principalUUID, encrypted, "{}", 0, now, now)
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -229,7 +233,10 @@ func (s *Store) CompleteTOTPLoginChallengeForLogin(domainUUID, token, code strin
|
|||||||
return "", false, ErrAccessDenied
|
return "", false, ErrAccessDenied
|
||||||
}
|
}
|
||||||
if err = s.VerifyTOTP(principalUUID, code); err != nil {
|
if err = s.VerifyTOTP(principalUUID, code); err != nil {
|
||||||
_, _ = s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET attempt_count=attempt_count+1,consumed_at_ms=CASE WHEN attempt_count+1>=5 THEN %s ELSE consumed_at_ms END WHERE uuid=%s AND consumed_at_ms=0`, s.sqlParam(1), s.sqlParam(2)), time.Now().UnixMilli(), challengeUUID)
|
// MySQL evaluates single-table UPDATE assignments left-to-right. Test
|
||||||
|
// the old counter before incrementing, or the fifth-attempt limit
|
||||||
|
// becomes four attempts on that backend.
|
||||||
|
_, _ = s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET consumed_at_ms=CASE WHEN attempt_count+1>=5 THEN %s ELSE consumed_at_ms END,attempt_count=attempt_count+1 WHERE uuid=%s AND consumed_at_ms=0`, s.sqlParam(1), s.sqlParam(2)), time.Now().UnixMilli(), challengeUUID)
|
||||||
return "", false, err
|
return "", false, err
|
||||||
}
|
}
|
||||||
result, err := s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET consumed_at_ms=%s WHERE uuid=%s AND consumed_at_ms=0 AND attempt_count<5 AND expires_at_ms>%s`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), time.Now().UnixMilli(), challengeUUID, time.Now().UnixMilli())
|
result, err := s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET consumed_at_ms=%s WHERE uuid=%s AND consumed_at_ms=0 AND attempt_count<5 AND expires_at_ms>%s`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), time.Now().UnixMilli(), challengeUUID, time.Now().UnixMilli())
|
||||||
|
|||||||
@@ -26,6 +26,9 @@ type Campus struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) EnsureCampusesSchema() error {
|
func (s *Store) EnsureCampusesSchema() error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend == storePostgreSQL {
|
||||||
return s.ensurePostgreSQLCampusDefaults(context.Background())
|
return s.ensurePostgreSQLCampusDefaults(context.Background())
|
||||||
}
|
}
|
||||||
@@ -249,6 +252,13 @@ func (s *Store) CreateCampus(
|
|||||||
fqdn string,
|
fqdn string,
|
||||||
enabled bool,
|
enabled bool,
|
||||||
) error {
|
) error {
|
||||||
|
return s.CreateCampusContext(context.Background(), name, title, defaultLang, authorityMode, fqdn, enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CreateCampusContext(ctx context.Context, name, title, defaultLang, authorityMode, fqdn string, enabled bool) error {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
name = normalizeCampusName(name)
|
name = normalizeCampusName(name)
|
||||||
title = strings.TrimSpace(title)
|
title = strings.TrimSpace(title)
|
||||||
if name == "" {
|
if name == "" {
|
||||||
@@ -282,7 +292,7 @@ func (s *Store) CreateCampus(
|
|||||||
enabledValue = 1
|
enabledValue = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.namespaceWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error {
|
return s.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
if err := s.ensureCampusFQDNAvailableFrom(ctx, tx, 0, fqdn); err != nil {
|
if err := s.ensureCampusFQDNAvailableFrom(ctx, tx, 0, fqdn); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -300,10 +310,17 @@ func (s *Store) UpdateCampus(
|
|||||||
fqdn string,
|
fqdn string,
|
||||||
enabled bool,
|
enabled bool,
|
||||||
) error {
|
) error {
|
||||||
|
return s.UpdateCampusContext(context.Background(), id, name, title, defaultLang, authorityMode, fqdn, enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) UpdateCampusContext(ctx context.Context, id int64, name, title, defaultLang, authorityMode, fqdn string, enabled bool) error {
|
||||||
|
if s.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
if id <= 0 {
|
if id <= 0 {
|
||||||
return namespaceValidationError("campus id is required")
|
return namespaceValidationError("campus id is required")
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
var existingMode string
|
var existingMode string
|
||||||
if err := s.DB.QueryRowContext(ctx, `
|
if err := s.DB.QueryRowContext(ctx, `
|
||||||
@@ -412,6 +429,9 @@ func (s *Store) UpdateCampus(
|
|||||||
func (s *Store) DeleteCampus(
|
func (s *Store) DeleteCampus(
|
||||||
id int64,
|
id int64,
|
||||||
) error {
|
) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
if s.ReadOnly {
|
if s.ReadOnly {
|
||||||
return ErrReadOnly
|
return ErrReadOnly
|
||||||
}
|
}
|
||||||
@@ -558,8 +578,7 @@ func (s *Store) ensureCampusFQDNAvailableFrom(ctx context.Context, q interface {
|
|||||||
WHEN d.domain = '' THEN
|
WHEN d.domain = '' THEN
|
||||||
CASE WHEN c.id = `+s.sqlParam(1)+` THEN `+s.sqlParam(2)+` ELSE c.fqdn END
|
CASE WHEN c.id = `+s.sqlParam(1)+` THEN `+s.sqlParam(2)+` ELSE c.fqdn END
|
||||||
WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain
|
WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain
|
||||||
ELSE d.domain || '.' ||
|
ELSE `+s.sqlConcat("d.domain", "'.'", "CASE WHEN c.id = "+s.sqlParam(3)+" THEN "+s.sqlParam(4)+" ELSE c.fqdn END")+`
|
||||||
CASE WHEN c.id = `+s.sqlParam(3)+` THEN `+s.sqlParam(4)+` ELSE c.fqdn END
|
|
||||||
END
|
END
|
||||||
) AS host
|
) AS host
|
||||||
FROM domains d
|
FROM domains d
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func (s *Store) EnsureConfigTable() error {
|
func (s *Store) EnsureConfigTable() error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend == storePostgreSQL {
|
||||||
return s.ensurePostgreSQLNamespaces(context.Background())
|
return s.ensurePostgreSQLNamespaces(context.Background())
|
||||||
}
|
}
|
||||||
@@ -112,7 +115,7 @@ func (s *Store) GetConfigInDomainContext(ctx context.Context, domainUUID, key st
|
|||||||
var value string
|
var value string
|
||||||
err := s.DB.QueryRowContext(ctx, `
|
err := s.DB.QueryRowContext(ctx, `
|
||||||
SELECT value FROM config
|
SELECT value FROM config
|
||||||
WHERE domain_uuid = `+s.sqlParam(1)+` AND key = `+s.sqlParam(2)+`
|
WHERE domain_uuid = `+s.sqlParam(1)+` AND `+s.sqlConfigKey()+` = `+s.sqlParam(2)+`
|
||||||
`, domainUUID, key).Scan(&value)
|
`, domainUUID, key).Scan(&value)
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
return "", nil
|
return "", nil
|
||||||
@@ -133,7 +136,18 @@ func (s *Store) SetConfigInDomain(domainUUID, key, value string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) SetConfigInDomainContext(ctx context.Context, domainUUID, key, value string) error {
|
func (s *Store) SetConfigInDomainContext(ctx context.Context, domainUUID, key, value string) error {
|
||||||
_, err := s.DB.ExecContext(ctx, `
|
return s.setConfigWith(ctx, s.DB, domainUUID, key, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) setConfigWith(ctx context.Context, q interface {
|
||||||
|
ExecContext(context.Context, string, ...any) (sql.Result, error)
|
||||||
|
}, domainUUID, key, value string) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
now := time.Now().Unix()
|
||||||
|
_, err := q.ExecContext(ctx, "INSERT INTO config(domain_uuid,`key`,value,updated_at) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE value=?,updated_at=?", domainUUID, key, value, now, value, now)
|
||||||
|
return s.sqlError("write configuration", err)
|
||||||
|
}
|
||||||
|
_, err := q.ExecContext(ctx, `
|
||||||
INSERT INTO config (domain_uuid, key, value, updated_at)
|
INSERT INTO config (domain_uuid, key, value, updated_at)
|
||||||
VALUES (`+s.sqlValues(4)+`)
|
VALUES (`+s.sqlValues(4)+`)
|
||||||
ON CONFLICT(domain_uuid, key)
|
ON CONFLICT(domain_uuid, key)
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ import (
|
|||||||
// transaction. A second connection must never observe a Domain without its
|
// transaction. A second connection must never observe a Domain without its
|
||||||
// built-in groups, or retain Campus privileges after a Domain moves.
|
// built-in groups, or retain Campus privileges after a Domain moves.
|
||||||
func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus, name, title, host, placement, instance, fingerprint string, enabled bool) error {
|
func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus, name, title, host, placement, instance, fingerprint string, enabled bool) error {
|
||||||
|
if s.sqlBackend == storeMySQL && (strings.TrimSpace(placement) != "local" || instance != "" || fingerprint != "") {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
if s.ReadOnly {
|
if s.ReadOnly {
|
||||||
return ErrReadOnly
|
return ErrReadOnly
|
||||||
}
|
}
|
||||||
@@ -33,6 +36,15 @@ func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus,
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return s.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
return s.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
var mode string
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT authority_mode FROM campuses WHERE uuid=?`, campus).Scan(&mode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if mode != "standalone" {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
|
}
|
||||||
if err := s.ensureCampusExists(ctx, tx, campus); err != nil {
|
if err := s.ensureCampusExists(ctx, tx, campus); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -45,6 +57,15 @@ func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus,
|
|||||||
}
|
}
|
||||||
key := uuid.NewString()
|
key := uuid.NewString()
|
||||||
if update {
|
if update {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
var existingPlacement string
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT placement FROM domains WHERE id=?`, id).Scan(&existingPlacement); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if existingPlacement != "local" {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
|
}
|
||||||
var mode string
|
var mode string
|
||||||
if err := tx.QueryRowContext(ctx, `SELECT d.uuid,c.authority_mode FROM domains d JOIN campuses c ON c.uuid=d.campus_uuid WHERE d.id=`+s.sqlParam(1), id).Scan(&key, &mode); err != nil {
|
if err := tx.QueryRowContext(ctx, `SELECT d.uuid,c.authority_mode FROM domains d JOIN campuses c ON c.uuid=d.campus_uuid WHERE d.id=`+s.sqlParam(1), id).Scan(&key, &mode); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -52,6 +73,9 @@ func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus,
|
|||||||
if mode == "managed" {
|
if mode == "managed" {
|
||||||
return namespaceValidationError("managed campus topology is read-only")
|
return namespaceValidationError("managed campus topology is read-only")
|
||||||
}
|
}
|
||||||
|
if s.sqlBackend == storeMySQL && mode != "standalone" {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
if placement == "remote" {
|
if placement == "remote" {
|
||||||
var used bool
|
var used bool
|
||||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM paths WHERE domain_uuid=`+s.sqlParam(1)+`)`, key).Scan(&used); err != nil {
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM paths WHERE domain_uuid=`+s.sqlParam(1)+`)`, key).Scan(&used); err != nil {
|
||||||
@@ -83,7 +107,7 @@ func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !update && hasConfig {
|
if !update && hasConfig {
|
||||||
_, err = tx.ExecContext(ctx, `INSERT INTO config(domain_uuid,key,value,updated_at) SELECT `+s.sqlParam(1)+`,'locale',CASE WHEN lower(default_lang) LIKE 'ja%' THEN 'ja' ELSE 'en' END,`+s.sqlParam(2)+` FROM campuses WHERE uuid=`+s.sqlParam(3)+` ON CONFLICT(domain_uuid,key) DO NOTHING`, key, now, campus)
|
_, err = tx.ExecContext(ctx, `INSERT INTO config(domain_uuid,`+s.sqlConfigKey()+`,value,updated_at) SELECT `+s.sqlParam(1)+`,'locale',CASE WHEN lower(default_lang) LIKE 'ja%' THEN 'ja' ELSE 'en' END,`+s.sqlParam(2)+` FROM campuses WHERE uuid=`+s.sqlParam(3)+s.sqlConflictDoNothing("config", "key", "domain_uuid,key"), key, now, campus)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ type Domain struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) EnsureDomainsSchema() error {
|
func (s *Store) EnsureDomainsSchema() error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend == storePostgreSQL {
|
||||||
if err := s.ensurePostgreSQLNamespaces(context.Background()); err != nil {
|
if err := s.ensurePostgreSQLNamespaces(context.Background()); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -193,7 +196,7 @@ func (s *Store) GetDomainByHostContext(ctx context.Context, host string) (*Domai
|
|||||||
CASE
|
CASE
|
||||||
WHEN d.domain = '' THEN c.fqdn
|
WHEN d.domain = '' THEN c.fqdn
|
||||||
WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain
|
WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain
|
||||||
ELSE d.domain || '.' || c.fqdn
|
ELSE `+s.sqlConcat("d.domain", "'.'", "c.fqdn")+`
|
||||||
END
|
END
|
||||||
) = `+s.sqlParam(1)+`
|
) = `+s.sqlParam(1)+`
|
||||||
ORDER BY d.id
|
ORDER BY d.id
|
||||||
@@ -235,7 +238,7 @@ func (s *Store) GetDomainEffectiveHostContext(ctx context.Context, domainUUID st
|
|||||||
CASE
|
CASE
|
||||||
WHEN d.domain = '' THEN c.fqdn
|
WHEN d.domain = '' THEN c.fqdn
|
||||||
WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain
|
WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain
|
||||||
ELSE d.domain || '.' || c.fqdn
|
ELSE `+s.sqlConcat("d.domain", "'.'", "c.fqdn")+`
|
||||||
END
|
END
|
||||||
)
|
)
|
||||||
FROM domains d
|
FROM domains d
|
||||||
@@ -342,6 +345,9 @@ func (s *Store) CountDomainsContext(ctx context.Context) (int, error) {
|
|||||||
func (s *Store) DeleteDomain(
|
func (s *Store) DeleteDomain(
|
||||||
id int64,
|
id int64,
|
||||||
) error {
|
) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return ErrBackendFeatureUnavailable
|
||||||
|
}
|
||||||
if s.ReadOnly {
|
if s.ReadOnly {
|
||||||
return ErrReadOnly
|
return ErrReadOnly
|
||||||
}
|
}
|
||||||
@@ -623,7 +629,7 @@ func (s *Store) ensureDomainUnique(
|
|||||||
CASE
|
CASE
|
||||||
WHEN d.domain = '' THEN c.fqdn
|
WHEN d.domain = '' THEN c.fqdn
|
||||||
WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain
|
WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain
|
||||||
ELSE d.domain || '.' || c.fqdn
|
ELSE `+s.sqlConcat("d.domain", "'.'", "c.fqdn")+`
|
||||||
END
|
END
|
||||||
) = `+s.sqlParam(3)+`
|
) = `+s.sqlParam(3)+`
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -59,6 +59,9 @@ func (s *Store) EnsureBuiltinAdminGroupsContext(ctx context.Context) error {
|
|||||||
|
|
||||||
// The caller holds the namespace writer lock, including when creating a Domain.
|
// The caller holds the namespace writer lock, including when creating a Domain.
|
||||||
func (s *Store) ensureBuiltinAdminGroupsContext(ctx context.Context, tx *sql.Tx) error {
|
func (s *Store) ensureBuiltinAdminGroupsContext(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return s.ensureMySQLBuiltinGroups(ctx, tx)
|
||||||
|
}
|
||||||
now := time.Now().UnixMilli()
|
now := time.Now().UnixMilli()
|
||||||
rows, err := tx.QueryContext(ctx, `SELECT uuid FROM domains ORDER BY uuid`)
|
rows, err := tx.QueryContext(ctx, `SELECT uuid FROM domains ORDER BY uuid`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -86,14 +89,14 @@ func (s *Store) ensureBuiltinAdminGroupsContext(ctx context.Context, tx *sql.Tx)
|
|||||||
if key == "campus_admin" {
|
if key == "campus_admin" {
|
||||||
inherit = 1
|
inherit = 1
|
||||||
}
|
}
|
||||||
_, err = tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO groups(uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms) VALUES(%s,%s,%s,%s,%s,'members','active',%s,%s,%s,%s) ON CONFLICT(domain_uuid,name) DO UPDATE SET builtin_key=excluded.builtin_key`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5), s.sqlParam(6), s.sqlParam(7), s.sqlParam(8), s.sqlParam(9)), uuid.NewString(), domainUUID, key, strings.ReplaceAll(key, "_", " "), "Built-in administrative group", key, inherit, now, now)
|
_, err = tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO `+s.sqlGroupTable()+`(uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms) VALUES(%s,%s,%s,%s,%s,'members','active',%s,%s,%s,%s) ON CONFLICT(domain_uuid,name) DO UPDATE SET builtin_key=excluded.builtin_key`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5), s.sqlParam(6), s.sqlParam(7), s.sqlParam(8), s.sqlParam(9)), uuid.NewString(), domainUUID, key, strings.ReplaceAll(key, "_", " "), "Built-in administrative group", key, inherit, now, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_, err = tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members
|
_, err = tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members
|
||||||
(group_uuid,membership_uuid,member_role,source,created_at_ms)
|
(group_uuid,membership_uuid,member_role,source,created_at_ms)
|
||||||
SELECT g.uuid,m.uuid,'owner','migration',%s FROM groups g
|
SELECT g.uuid,m.uuid,'owner','migration',%s FROM `+s.sqlGroupTable()+` g
|
||||||
JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid
|
JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid
|
||||||
JOIN auth_role_bindings b ON b.membership_uuid=m.uuid
|
JOIN auth_role_bindings b ON b.membership_uuid=m.uuid
|
||||||
JOIN auth_roles r ON r.uuid=b.role_uuid AND r.domain_uuid=m.domain_uuid
|
JOIN auth_roles r ON r.uuid=b.role_uuid AND r.domain_uuid=m.domain_uuid
|
||||||
@@ -124,7 +127,7 @@ func (s *Store) IsBuiltinGroupAdminContext(ctx context.Context, domainUUID, prin
|
|||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
var allowed bool
|
var allowed bool
|
||||||
err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM groups g JOIN domains d ON d.uuid=g.domain_uuid AND d.enabled=1 JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE g.domain_uuid=%s AND g.builtin_key=%s AND g.state='active' AND m.principal_uuid=%s AND m.state='active' AND p.state='active' AND gm.member_role IN ('owner','manager'))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), domainUUID, key, principalUUID).Scan(&allowed)
|
err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM `+s.sqlGroupTable()+` g JOIN domains d ON d.uuid=g.domain_uuid AND d.enabled=1 JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE g.domain_uuid=%s AND g.builtin_key=%s AND g.state='active' AND m.principal_uuid=%s AND m.state='active' AND p.state='active' AND gm.member_role IN ('owner','manager'))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), domainUUID, key, principalUUID).Scan(&allowed)
|
||||||
return err == nil && allowed, s.sqlError("builtin group authorization", err)
|
return err == nil && allowed, s.sqlError("builtin group authorization", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +141,7 @@ func (s *Store) IsCampusAdminContext(ctx context.Context, campusUUID, principalU
|
|||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
var allowed bool
|
var allowed bool
|
||||||
err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM groups g JOIN domains d ON d.uuid=g.domain_uuid AND d.enabled=1 JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE d.campus_uuid=%s AND g.builtin_key='campus_admin' AND g.state='active' AND m.principal_uuid=%s AND m.state='active' AND p.state='active' AND gm.member_role IN ('owner','manager'))`, s.sqlParam(1), s.sqlParam(2)), campusUUID, principalUUID).Scan(&allowed)
|
err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM `+s.sqlGroupTable()+` g JOIN domains d ON d.uuid=g.domain_uuid AND d.enabled=1 JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE d.campus_uuid=%s AND g.builtin_key='campus_admin' AND g.state='active' AND m.principal_uuid=%s AND m.state='active' AND p.state='active' AND gm.member_role IN ('owner','manager'))`, s.sqlParam(1), s.sqlParam(2)), campusUUID, principalUUID).Scan(&allowed)
|
||||||
return err == nil && allowed, s.sqlError("campus authorization", err)
|
return err == nil && allowed, s.sqlError("campus authorization", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,7 +155,13 @@ func (s *Store) SetCampusAdminInheritanceContext(ctx context.Context, groupUUID
|
|||||||
value = 1
|
value = 1
|
||||||
}
|
}
|
||||||
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE groups SET inherit_members=%s,updated_at_ms=%s WHERE uuid=%s AND builtin_key='campus_admin'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), value, time.Now().UnixMilli(), groupUUID)
|
if s.sqlBackend == storeMySQL {
|
||||||
|
var found string
|
||||||
|
if err := tx.QueryRowContext(ctx, "SELECT uuid FROM `groups` WHERE uuid=? AND builtin_key='campus_admin'", groupUUID).Scan(&found); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE `+s.sqlGroupTable()+` SET inherit_members=%s,updated_at_ms=%s WHERE uuid=%s AND builtin_key='campus_admin'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), value, time.Now().UnixMilli(), groupUUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -160,7 +169,7 @@ func (s *Store) SetCampusAdminInheritanceContext(ctx context.Context, groupUUID
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if changed != 1 {
|
if changed != 1 && s.sqlBackend != storeMySQL {
|
||||||
return namespaceValidationError("campus_admin group not found")
|
return namespaceValidationError("campus_admin group not found")
|
||||||
}
|
}
|
||||||
return s.projectCampusAdminMembershipsContext(ctx, tx)
|
return s.projectCampusAdminMembershipsContext(ctx, tx)
|
||||||
@@ -189,7 +198,7 @@ func (s *Store) CreateGroupContext(ctx context.Context, domainUUID, ownerPrincip
|
|||||||
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT m.uuid FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid AND p.state='active' WHERE m.domain_uuid=%s AND m.principal_uuid=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2)), domainUUID, ownerPrincipalUUID).Scan(&membershipUUID); err != nil {
|
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT m.uuid FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid AND p.state='active' WHERE m.domain_uuid=%s AND m.principal_uuid=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2)), domainUUID, ownerPrincipalUUID).Scan(&membershipUUID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := tx.ExecContext(ctx, `INSERT INTO groups(uuid,domain_uuid,name,display_name,description,visibility,state,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`)`, group.UUID, domainUUID, group.Name, group.DisplayName, group.Description, group.Visibility, group.State, now, now); err != nil {
|
if _, err := tx.ExecContext(ctx, `INSERT INTO `+s.sqlGroupTable()+`(uuid,domain_uuid,name,display_name,description,visibility,state,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`)`, group.UUID, domainUUID, group.Name, group.DisplayName, group.Description, group.Visibility, group.State, now, now); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(%s,%s,'owner','local',%s)`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), group.UUID, membershipUUID, now); err != nil {
|
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(%s,%s,'owner','local',%s)`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), group.UUID, membershipUUID, now); err != nil {
|
||||||
@@ -211,7 +220,7 @@ func (s *Store) GroupByName(domainUUID, name string) (*Group, error) {
|
|||||||
|
|
||||||
func (s *Store) GroupByNameContext(ctx context.Context, domainUUID, name string) (*Group, error) {
|
func (s *Store) GroupByNameContext(ctx context.Context, domainUUID, name string) (*Group, error) {
|
||||||
var group Group
|
var group Group
|
||||||
err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms FROM groups WHERE domain_uuid=%s AND name=%s AND state!='archived'`, s.sqlParam(1), s.sqlParam(2)), domainUUID, strings.ToLower(strings.TrimSpace(name))).Scan(&group.UUID, &group.DomainUUID, &group.Name, &group.DisplayName, &group.Description, &group.Visibility, &group.State, &group.BuiltinKey, &group.InheritMembers, &group.CreatedAtMS, &group.UpdatedAtMS)
|
err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms FROM `+s.sqlGroupTable()+` WHERE domain_uuid=%s AND name=%s AND state!='archived'`, s.sqlParam(1), s.sqlParam(2)), domainUUID, strings.ToLower(strings.TrimSpace(name))).Scan(&group.UUID, &group.DomainUUID, &group.Name, &group.DisplayName, &group.Description, &group.Visibility, &group.State, &group.BuiltinKey, &group.InheritMembers, &group.CreatedAtMS, &group.UpdatedAtMS)
|
||||||
return &group, s.sqlError("read group by name", err)
|
return &group, s.sqlError("read group by name", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,7 +230,7 @@ func (s *Store) GroupByUUID(domainUUID, groupUUID string) (*Group, error) {
|
|||||||
|
|
||||||
func (s *Store) GroupByUUIDContext(ctx context.Context, domainUUID, groupUUID string) (*Group, error) {
|
func (s *Store) GroupByUUIDContext(ctx context.Context, domainUUID, groupUUID string) (*Group, error) {
|
||||||
var group Group
|
var group Group
|
||||||
err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms FROM groups WHERE domain_uuid=%s AND uuid=%s`, s.sqlParam(1), s.sqlParam(2)), domainUUID, groupUUID).Scan(&group.UUID, &group.DomainUUID, &group.Name, &group.DisplayName, &group.Description, &group.Visibility, &group.State, &group.BuiltinKey, &group.InheritMembers, &group.CreatedAtMS, &group.UpdatedAtMS)
|
err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms FROM `+s.sqlGroupTable()+` WHERE domain_uuid=%s AND uuid=%s`, s.sqlParam(1), s.sqlParam(2)), domainUUID, groupUUID).Scan(&group.UUID, &group.DomainUUID, &group.Name, &group.DisplayName, &group.Description, &group.Visibility, &group.State, &group.BuiltinKey, &group.InheritMembers, &group.CreatedAtMS, &group.UpdatedAtMS)
|
||||||
return &group, s.sqlError("read group by UUID", err)
|
return &group, s.sqlError("read group by UUID", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,7 +242,7 @@ func (s *Store) ListGroupsContext(ctx context.Context, domainUUID, principalUUID
|
|||||||
// EXISTS avoids duplicate rows and PostgreSQL's DISTINCT/ORDER BY mismatch.
|
// EXISTS avoids duplicate rows and PostgreSQL's DISTINCT/ORDER BY mismatch.
|
||||||
// A nonempty global Principal UUID alone is not Domain membership.
|
// A nonempty global Principal UUID alone is not Domain membership.
|
||||||
rows, err := s.DB.QueryContext(ctx, fmt.Sprintf(`SELECT g.uuid,g.domain_uuid,g.name,g.display_name,g.description,g.visibility,g.state,g.builtin_key,g.inherit_members,g.created_at_ms,g.updated_at_ms
|
rows, err := s.DB.QueryContext(ctx, fmt.Sprintf(`SELECT g.uuid,g.domain_uuid,g.name,g.display_name,g.description,g.visibility,g.state,g.builtin_key,g.inherit_members,g.created_at_ms,g.updated_at_ms
|
||||||
FROM groups g WHERE g.domain_uuid=%s AND g.state!='archived'
|
FROM `+s.sqlGroupTable()+` g WHERE g.domain_uuid=%s AND g.state!='archived'
|
||||||
AND (g.visibility='public' OR EXISTS(
|
AND (g.visibility='public' OR EXISTS(
|
||||||
SELECT 1 FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid
|
SELECT 1 FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid
|
||||||
WHERE m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active'
|
WHERE m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active'
|
||||||
@@ -257,13 +266,13 @@ func (s *Store) ListGroupsContext(ctx context.Context, domainUUID, principalUUID
|
|||||||
|
|
||||||
func (s *Store) GroupMemberRole(groupUUID, principalUUID string) string {
|
func (s *Store) GroupMemberRole(groupUUID, principalUUID string) string {
|
||||||
var role string
|
var role string
|
||||||
_ = s.DB.QueryRow(fmt.Sprintf(`SELECT gm.member_role FROM group_members gm JOIN groups g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=%s AND m.principal_uuid=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2)), groupUUID, principalUUID).Scan(&role)
|
_ = s.DB.QueryRow(fmt.Sprintf(`SELECT gm.member_role FROM group_members gm JOIN `+s.sqlGroupTable()+` g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=%s AND m.principal_uuid=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2)), groupUUID, principalUUID).Scan(&role)
|
||||||
return role
|
return role
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) GroupMemberRoleByMembership(groupUUID, membershipUUID string) string {
|
func (s *Store) GroupMemberRoleByMembership(groupUUID, membershipUUID string) string {
|
||||||
var role string
|
var role string
|
||||||
_ = s.DB.QueryRow(fmt.Sprintf(`SELECT gm.member_role FROM group_members gm JOIN groups g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=%s AND gm.membership_uuid=%s`, s.sqlParam(1), s.sqlParam(2)), groupUUID, membershipUUID).Scan(&role)
|
_ = s.DB.QueryRow(fmt.Sprintf(`SELECT gm.member_role FROM group_members gm JOIN `+s.sqlGroupTable()+` g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=%s AND gm.membership_uuid=%s`, s.sqlParam(1), s.sqlParam(2)), groupUUID, membershipUUID).Scan(&role)
|
||||||
return role
|
return role
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -272,7 +281,7 @@ func (s *Store) ListGroupMembers(groupUUID string) ([]GroupMember, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) ListGroupMembersContext(ctx context.Context, groupUUID string) ([]GroupMember, error) {
|
func (s *Store) ListGroupMembersContext(ctx context.Context, groupUUID string) ([]GroupMember, error) {
|
||||||
rows, err := s.DB.QueryContext(ctx, `SELECT m.uuid,p.uuid,COALESCE((SELECT subject FROM principal_identities i WHERE i.principal_uuid=p.uuid AND i.provider_type='password' ORDER BY i.subject,i.uuid LIMIT 1),p.uuid),p.display_name,gm.member_role,gm.source FROM group_members gm JOIN groups g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE gm.group_uuid=`+s.sqlParam(1)+` ORDER BY CASE gm.member_role WHEN 'owner' THEN 0 WHEN 'manager' THEN 1 ELSE 2 END,lower(p.display_name),m.uuid`, groupUUID)
|
rows, err := s.DB.QueryContext(ctx, `SELECT m.uuid,p.uuid,COALESCE((SELECT subject FROM principal_identities i WHERE i.principal_uuid=p.uuid AND i.provider_type='password' ORDER BY i.subject,i.uuid LIMIT 1),p.uuid),p.display_name,gm.member_role,gm.source FROM group_members gm JOIN `+s.sqlGroupTable()+` g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE gm.group_uuid=`+s.sqlParam(1)+` ORDER BY CASE gm.member_role WHEN 'owner' THEN 0 WHEN 'manager' THEN 1 ELSE 2 END,lower(p.display_name),m.uuid`, groupUUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, s.sqlError("list group members", err)
|
return nil, s.sqlError("list group members", err)
|
||||||
}
|
}
|
||||||
@@ -298,24 +307,30 @@ func (s *Store) AddGroupMemberByUsernameContext(ctx context.Context, domainUUID,
|
|||||||
}
|
}
|
||||||
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
// Serialize before the identity lookup as well as the ownership check.
|
// Serialize before the identity lookup as well as the ownership check.
|
||||||
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE groups SET updated_at_ms=updated_at_ms WHERE uuid=%s AND domain_uuid=%s`, s.sqlParam(1), s.sqlParam(2)), groupUUID, domainUUID); err != nil {
|
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE `+s.sqlGroupTable()+` SET updated_at_ms=updated_at_ms WHERE uuid=%s AND domain_uuid=%s`, s.sqlParam(1), s.sqlParam(2)), groupUUID, domainUUID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var membershipUUID, builtinKey string
|
var membershipUUID, builtinKey string
|
||||||
err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT m.uuid,g.builtin_key FROM domain_memberships m JOIN principal_identities i ON i.principal_uuid=m.principal_uuid AND i.provider_type='password' JOIN groups g ON g.uuid=%s AND g.domain_uuid=m.domain_uuid WHERE m.domain_uuid=%s AND i.subject=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), groupUUID, domainUUID, strings.ToLower(strings.TrimSpace(username))).Scan(&membershipUUID, &builtinKey)
|
err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT m.uuid,g.builtin_key FROM domain_memberships m JOIN principal_identities i ON i.principal_uuid=m.principal_uuid AND i.provider_type='password' JOIN `+s.sqlGroupTable()+` g ON g.uuid=%s AND g.domain_uuid=m.domain_uuid WHERE m.domain_uuid=%s AND i.subject=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), groupUUID, domainUUID, strings.ToLower(strings.TrimSpace(username))).Scan(&membershipUUID, &builtinKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// Ordinary add/update is not an ownership-transfer API. Keep this check in
|
// Ordinary add/update is not an ownership-transfer API. Keep this check in
|
||||||
// the write itself, including when another request just promoted the member.
|
// the write itself, including when another request just promoted the member.
|
||||||
result, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(%s,%s,%s,'local',%s) ON CONFLICT(group_uuid,membership_uuid) DO UPDATE SET member_role=excluded.member_role,source=excluded.source WHERE group_members.member_role!='owner' OR excluded.member_role='owner'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4)), groupUUID, membershipUUID, role, time.Now().UnixMilli())
|
if s.sqlBackend == storeMySQL {
|
||||||
if err != nil {
|
if err := mysqlAddGroupMember(ctx, tx, groupUUID, membershipUUID, role); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if count, err := result.RowsAffected(); err != nil {
|
} else {
|
||||||
return err
|
result, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(%s,%s,%s,'local',%s) ON CONFLICT(group_uuid,membership_uuid) DO UPDATE SET member_role=excluded.member_role,source=excluded.source WHERE group_members.member_role!='owner' OR excluded.member_role='owner'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4)), groupUUID, membershipUUID, role, time.Now().UnixMilli())
|
||||||
} else if count == 0 {
|
if err != nil {
|
||||||
return namespaceValidationError("owner role cannot be downgraded by a member update")
|
return err
|
||||||
|
}
|
||||||
|
if count, err := result.RowsAffected(); err != nil {
|
||||||
|
return err
|
||||||
|
} else if count == 0 {
|
||||||
|
return namespaceValidationError("owner role cannot be downgraded by a member update")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if builtinKey == "campus_admin" {
|
if builtinKey == "campus_admin" {
|
||||||
if _, err = tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM campus_admin_grants WHERE group_uuid=%s AND membership_uuid=%s AND substr(source,1,21)!='campus_admin_inherit:'`, s.sqlParam(1), s.sqlParam(2)), groupUUID, membershipUUID); err != nil {
|
if _, err = tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM campus_admin_grants WHERE group_uuid=%s AND membership_uuid=%s AND substr(source,1,21)!='campus_admin_inherit:'`, s.sqlParam(1), s.sqlParam(2)), groupUUID, membershipUUID); err != nil {
|
||||||
@@ -346,11 +361,11 @@ func (s *Store) RemoveGroupMemberWithAuthority(groupUUID, membershipUUID string,
|
|||||||
|
|
||||||
func (s *Store) RemoveGroupMemberWithAuthorityContext(ctx context.Context, groupUUID, membershipUUID string, ownerAuthority bool) error {
|
func (s *Store) RemoveGroupMemberWithAuthorityContext(ctx context.Context, groupUUID, membershipUUID string, ownerAuthority bool) error {
|
||||||
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
if _, err := tx.ExecContext(ctx, `UPDATE groups SET updated_at_ms=updated_at_ms WHERE uuid=`+s.sqlParam(1), groupUUID); err != nil {
|
if _, err := tx.ExecContext(ctx, `UPDATE `+s.sqlGroupTable()+` SET updated_at_ms=updated_at_ms WHERE uuid=`+s.sqlParam(1), groupUUID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var builtinKey string
|
var builtinKey string
|
||||||
if err := tx.QueryRowContext(ctx, `SELECT builtin_key FROM groups WHERE uuid=`+s.sqlParam(1), groupUUID).Scan(&builtinKey); err != nil {
|
if err := tx.QueryRowContext(ctx, `SELECT builtin_key FROM `+s.sqlGroupTable()+` WHERE uuid=`+s.sqlParam(1), groupUUID).Scan(&builtinKey); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if builtinKey == "campus_admin" {
|
if builtinKey == "campus_admin" {
|
||||||
@@ -366,7 +381,7 @@ func (s *Store) RemoveGroupMemberWithAuthorityContext(ctx context.Context, group
|
|||||||
AND mine.membership_uuid=gr.membership_uuid AND mine.member_role='owner'
|
AND mine.membership_uuid=gr.membership_uuid AND mine.member_role='owner'
|
||||||
AND substr(mine.source,1,21)!='campus_admin_inherit:')
|
AND substr(mine.source,1,21)!='campus_admin_inherit:')
|
||||||
OR EXISTS(SELECT 1 FROM campus_admin_grants other
|
OR EXISTS(SELECT 1 FROM campus_admin_grants other
|
||||||
JOIN groups og ON og.uuid=other.group_uuid
|
JOIN `+s.sqlGroupTable()+` og ON og.uuid=other.group_uuid
|
||||||
JOIN domain_memberships om ON om.uuid=other.membership_uuid AND om.domain_uuid=og.domain_uuid
|
JOIN domain_memberships om ON om.uuid=other.membership_uuid AND om.domain_uuid=og.domain_uuid
|
||||||
WHERE other.group_uuid=gr.group_uuid
|
WHERE other.group_uuid=gr.group_uuid
|
||||||
AND other.membership_uuid!=gr.membership_uuid AND other.member_role='owner'
|
AND other.membership_uuid!=gr.membership_uuid AND other.member_role='owner'
|
||||||
@@ -384,10 +399,13 @@ func (s *Store) RemoveGroupMemberWithAuthorityContext(ctx context.Context, group
|
|||||||
}
|
}
|
||||||
// A single SQLite write serializes the check and deletion. A manager cannot
|
// A single SQLite write serializes the check and deletion. A manager cannot
|
||||||
// delete a member concurrently promoted to owner/manager by another request.
|
// delete a member concurrently promoted to owner/manager by another request.
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return mysqlRemoveGroupMember(ctx, tx, groupUUID, membershipUUID, ownerAuthority)
|
||||||
|
}
|
||||||
result, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM group_members WHERE group_uuid=%s AND membership_uuid=%s
|
result, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM group_members WHERE group_uuid=%s AND membership_uuid=%s
|
||||||
AND (%s OR member_role='member')
|
AND (%s OR member_role='member')
|
||||||
AND (member_role!='owner' OR EXISTS (
|
AND (member_role!='owner' OR EXISTS (
|
||||||
SELECT 1 FROM group_members other JOIN groups og ON og.uuid=other.group_uuid
|
SELECT 1 FROM group_members other JOIN `+s.sqlGroupTable()+` og ON og.uuid=other.group_uuid
|
||||||
JOIN domain_memberships om ON om.uuid=other.membership_uuid AND om.domain_uuid=og.domain_uuid
|
JOIN domain_memberships om ON om.uuid=other.membership_uuid AND om.domain_uuid=og.domain_uuid
|
||||||
WHERE other.group_uuid=%s AND other.membership_uuid!=%s AND other.member_role='owner'
|
WHERE other.group_uuid=%s AND other.membership_uuid!=%s AND other.member_role='owner'
|
||||||
))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), groupUUID, membershipUUID, ownerAuthority, groupUUID, membershipUUID)
|
))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), groupUUID, membershipUUID, ownerAuthority, groupUUID, membershipUUID)
|
||||||
@@ -417,8 +435,16 @@ func (s *Store) SetGroupPermissionContext(ctx context.Context, groupUUID, scopeP
|
|||||||
scopePath = "/"
|
scopePath = "/"
|
||||||
}
|
}
|
||||||
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
var found string
|
||||||
|
if err := tx.QueryRowContext(ctx, "SELECT uuid FROM `groups` WHERE uuid=?", groupUUID).Scan(&found); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := tx.ExecContext(ctx, `INSERT INTO group_permissions(uuid,group_uuid,scope_path,permission,created_at_ms) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE permission=?`, uuid.NewString(), groupUUID, scopePath, permission, time.Now().UnixMilli(), permission)
|
||||||
|
return err
|
||||||
|
}
|
||||||
result, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_permissions(uuid,group_uuid,scope_path,permission,created_at_ms)
|
result, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_permissions(uuid,group_uuid,scope_path,permission,created_at_ms)
|
||||||
SELECT %s,uuid,%s,%s,%s FROM groups WHERE uuid=%s
|
SELECT %s,uuid,%s,%s,%s FROM `+s.sqlGroupTable()+` WHERE uuid=%s
|
||||||
ON CONFLICT(group_uuid,scope_path) DO UPDATE SET permission=excluded.permission`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), uuid.NewString(), scopePath, permission, time.Now().UnixMilli(), groupUUID)
|
ON CONFLICT(group_uuid,scope_path) DO UPDATE SET permission=excluded.permission`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), uuid.NewString(), scopePath, permission, time.Now().UnixMilli(), groupUUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -464,7 +490,7 @@ type groupPermissionQueryer interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) groupPermissionAllowsContext(ctx context.Context, q groupPermissionQueryer, domainUUID, principalUUID, capability, targetPath string) (bool, error) {
|
func (s *Store) groupPermissionAllowsContext(ctx context.Context, q groupPermissionQueryer, domainUUID, principalUUID, capability, targetPath string) (bool, error) {
|
||||||
rows, err := q.QueryContext(ctx, fmt.Sprintf(`SELECT gp.scope_path,gp.permission FROM group_permissions gp JOIN groups g ON g.uuid=gp.group_uuid AND g.domain_uuid=%s AND g.state='active' JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active' JOIN principals p ON p.uuid=m.principal_uuid AND (p.state='active' OR (p.state='readonly' AND %s='read'))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), domainUUID, principalUUID, capability)
|
rows, err := q.QueryContext(ctx, fmt.Sprintf(`SELECT gp.scope_path,gp.permission FROM group_permissions gp JOIN `+s.sqlGroupTable()+` g ON g.uuid=gp.group_uuid AND g.domain_uuid=%s AND g.state='active' JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active' JOIN principals p ON p.uuid=m.principal_uuid AND (p.state='active' OR (p.state='readonly' AND %s='read'))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), domainUUID, principalUUID, capability)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, s.sqlError("group permission evaluation", err)
|
return false, s.sqlError("group permission evaluation", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,12 @@ type adminBackendFixture struct {
|
|||||||
|
|
||||||
func newAdminBackendFixture(t *testing.T, backend storeSQLBackend) *adminBackendFixture {
|
func newAdminBackendFixture(t *testing.T, backend storeSQLBackend) *adminBackendFixture {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
s := testNamespaceStore(t, backend)
|
s := testNamespaceCoreStore(t, backend)
|
||||||
|
if backend == storeMySQL {
|
||||||
|
if err := s.ensureMySQLAuthFoundation(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if backend == storePostgreSQL {
|
if backend == storePostgreSQL {
|
||||||
if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil {
|
if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -64,6 +69,10 @@ func newAdminBackendFixture(t *testing.T, backend storeSQLBackend) *adminBackend
|
|||||||
// Test fixture SQL is owned and uses explicit format slots; production queries
|
// Test fixture SQL is owned and uses explicit format slots; production queries
|
||||||
// do not run through a SQL string rewriting layer.
|
// do not run through a SQL string rewriting layer.
|
||||||
func (f *adminBackendFixture) query(query string, n int) string {
|
func (f *adminBackendFixture) query(query string, n int) string {
|
||||||
|
if f.s.sqlBackend == storeMySQL {
|
||||||
|
// Only owned fixture SQL. Production statements compose identifiers.
|
||||||
|
query = strings.ReplaceAll(query, " groups ", " `groups` ")
|
||||||
|
}
|
||||||
p := make([]any, n)
|
p := make([]any, n)
|
||||||
for i := range p {
|
for i := range p {
|
||||||
p[i] = f.s.sqlParam(i + 1)
|
p[i] = f.s.sqlParam(i + 1)
|
||||||
@@ -81,9 +90,15 @@ func (f *adminBackendFixture) row(query string, args ...any) *sql.Row {
|
|||||||
}
|
}
|
||||||
func (f *adminBackendFixture) local(domain, user string) string {
|
func (f *adminBackendFixture) local(domain, user string) string {
|
||||||
f.t.Helper()
|
f.t.Helper()
|
||||||
f.exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES(%s,%s,1,1) ON CONFLICT DO NOTHING`, user, user)
|
if f.s.sqlBackend == storeMySQL {
|
||||||
f.exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,subject,created_at_ms) VALUES(%s,%s,'password',%s,1) ON CONFLICT DO NOTHING`, user, user, user)
|
f.exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES(%s,%s,1,1) ON DUPLICATE KEY UPDATE uuid=principals.uuid`, user, user)
|
||||||
f.exec(`INSERT INTO domain_memberships(uuid,domain_uuid,principal_uuid,created_at_ms) VALUES(%s,%s,%s,1) ON CONFLICT DO NOTHING`, domain+":"+user, f.domains[domain], user)
|
f.exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,subject,created_at_ms) VALUES(%s,%s,'password',%s,1) ON DUPLICATE KEY UPDATE uuid=principal_identities.uuid`, user, user, user)
|
||||||
|
f.exec(`INSERT INTO domain_memberships(uuid,domain_uuid,principal_uuid,created_at_ms) VALUES(%s,%s,%s,1) ON DUPLICATE KEY UPDATE uuid=domain_memberships.uuid`, domain+":"+user, f.domains[domain], user)
|
||||||
|
} else {
|
||||||
|
f.exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES(%s,%s,1,1) ON CONFLICT DO NOTHING`, user, user)
|
||||||
|
f.exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,subject,created_at_ms) VALUES(%s,%s,'password',%s,1) ON CONFLICT DO NOTHING`, user, user, user)
|
||||||
|
f.exec(`INSERT INTO domain_memberships(uuid,domain_uuid,principal_uuid,created_at_ms) VALUES(%s,%s,%s,1) ON CONFLICT DO NOTHING`, domain+":"+user, f.domains[domain], user)
|
||||||
|
}
|
||||||
var id string
|
var id string
|
||||||
if err := f.row(`SELECT uuid FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid=%s`, f.domains[domain], user).Scan(&id); err != nil {
|
if err := f.row(`SELECT uuid FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid=%s`, f.domains[domain], user).Scan(&id); err != nil {
|
||||||
f.t.Fatal(err)
|
f.t.Fatal(err)
|
||||||
@@ -111,7 +126,7 @@ func (f *adminBackendFixture) membership(domain, user string, want bool) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
func forAdminBackends(t *testing.T, fn func(*testing.T, *adminBackendFixture)) {
|
func forAdminBackends(t *testing.T, fn func(*testing.T, *adminBackendFixture)) {
|
||||||
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} {
|
for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
t.Run(fmt.Sprint(b), func(t *testing.T) { fn(t, newAdminBackendFixture(t, b)) })
|
t.Run(fmt.Sprint(b), func(t *testing.T) { fn(t, newAdminBackendFixture(t, b)) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -265,6 +265,13 @@ func TestGeneralGroupBackendCancellationAndErrorBoundary(t *testing.T) {
|
|||||||
t.Fatalf("unsafe PostgreSQL error: %v", err)
|
t.Fatalf("unsafe PostgreSQL error: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if f.s.sqlBackend == storeMySQL {
|
||||||
|
f.exec(`ALTER TABLE groups ADD CONSTRAINT synthetic_title_check CHECK(display_name!='private-test-title')`)
|
||||||
|
_, err := f.s.CreateGroup(f.domains["a"], "alice", "rejected", "private-test-title", "", "public")
|
||||||
|
if err == nil || strings.Contains(err.Error(), "private-test-title") {
|
||||||
|
t.Fatalf("unsafe MySQL error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ func (s *Store) ensureCampusAdminInheritanceSchema() error {
|
|||||||
if _, err = tx.Exec(`INSERT OR IGNORE INTO campus_admin_grants
|
if _, err = tx.Exec(`INSERT OR IGNORE INTO campus_admin_grants
|
||||||
(group_uuid,membership_uuid,source,member_role,created_at_ms)
|
(group_uuid,membership_uuid,source,member_role,created_at_ms)
|
||||||
SELECT gm.group_uuid,gm.membership_uuid,gm.source,gm.member_role,gm.created_at_ms
|
SELECT gm.group_uuid,gm.membership_uuid,gm.source,gm.member_role,gm.created_at_ms
|
||||||
FROM group_members gm JOIN groups g ON g.uuid=gm.group_uuid
|
FROM group_members gm JOIN ` + s.sqlGroupTable() + ` g ON g.uuid=gm.group_uuid
|
||||||
WHERE g.builtin_key='campus_admin' AND substr(gm.source,1,21)!='campus_admin_inherit:'
|
WHERE g.builtin_key='campus_admin' AND substr(gm.source,1,21)!='campus_admin_inherit:'
|
||||||
AND NOT EXISTS(SELECT 1 FROM campus_admin_migrations WHERE key='direct-grants-v1')`); err != nil {
|
AND NOT EXISTS(SELECT 1 FROM campus_admin_migrations WHERE key='direct-grants-v1')`); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -54,8 +54,8 @@ func (s *Store) ensureCampusAdminInheritanceSchema() error {
|
|||||||
// Domain administrator binding. A later explicit group removal must not be
|
// Domain administrator binding. A later explicit group removal must not be
|
||||||
// undone by restarting the server or creating another Domain.
|
// undone by restarting the server or creating another Domain.
|
||||||
func (s *Store) seedCampusAdminRoleGrantsContext(ctx context.Context, tx *sql.Tx, now int64) error {
|
func (s *Store) seedCampusAdminRoleGrantsContext(ctx context.Context, tx *sql.Tx, now int64) error {
|
||||||
const candidates = `SELECT DISTINCT g.uuid AS group_uuid,m.uuid AS membership_uuid
|
candidates := `SELECT DISTINCT g.uuid AS group_uuid,m.uuid AS membership_uuid
|
||||||
FROM groups g JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid
|
FROM ` + s.sqlGroupTable() + ` g JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid
|
||||||
JOIN auth_role_bindings b ON b.membership_uuid=m.uuid
|
JOIN auth_role_bindings b ON b.membership_uuid=m.uuid
|
||||||
JOIN auth_roles r ON r.uuid=b.role_uuid AND r.domain_uuid=m.domain_uuid
|
JOIN auth_roles r ON r.uuid=b.role_uuid AND r.domain_uuid=m.domain_uuid
|
||||||
JOIN auth_capability_grants c ON c.role_uuid=r.uuid
|
JOIN auth_capability_grants c ON c.role_uuid=r.uuid
|
||||||
@@ -66,11 +66,11 @@ func (s *Store) seedCampusAdminRoleGrantsContext(ctx context.Context, tx *sql.Tx
|
|||||||
(group_uuid,membership_uuid,source,member_role,created_at_ms)
|
(group_uuid,membership_uuid,source,member_role,created_at_ms)
|
||||||
SELECT group_uuid,membership_uuid,'migration','owner',%s FROM (`+candidates+`) AS candidates
|
SELECT group_uuid,membership_uuid,'migration','owner',%s FROM (`+candidates+`) AS candidates
|
||||||
WHERE NOT EXISTS(SELECT 1 FROM campus_admin_migrations
|
WHERE NOT EXISTS(SELECT 1 FROM campus_admin_migrations
|
||||||
WHERE key='role:'||group_uuid||':'||membership_uuid) ON CONFLICT(group_uuid,membership_uuid,source) DO NOTHING`, s.sqlParam(1)), now); err != nil {
|
WHERE `+s.sqlConfigKey()+`=`+s.sqlConcat("'role:'", "group_uuid", "':'", "membership_uuid")+`)`+s.sqlConflictDoNothing("campus_admin_grants", "group_uuid", "group_uuid,membership_uuid,source"), s.sqlParam(1)), now); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_migrations(key)
|
_, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_migrations(`+s.sqlConfigKey()+`)
|
||||||
SELECT 'role:'||group_uuid||':'||membership_uuid FROM (`+candidates+`) AS candidates WHERE 1=1 ON CONFLICT(key) DO NOTHING`)
|
SELECT `+s.sqlConcat("'role:'", "group_uuid", "':'", "membership_uuid")+` FROM (`+candidates+`) AS candidates WHERE 1=1`+s.sqlConflictDoNothing("campus_admin_migrations", "key", "key"))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,12 +103,12 @@ func (s *Store) projectCampusAdminMembershipsContext(ctx context.Context, tx *sq
|
|||||||
if _, err := tx.ExecContext(ctx, `DELETE FROM campus_admin_grants WHERE substr(source,1,21)='campus_admin_inherit:'`); err != nil {
|
if _, err := tx.ExecContext(ctx, `DELETE FROM campus_admin_grants WHERE substr(source,1,21)='campus_admin_inherit:'`); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
const roots = `SELECT src.uuid AS source_group_uuid,origin.uuid AS source_domain_uuid,
|
roots := `SELECT src.uuid AS source_group_uuid,origin.uuid AS source_domain_uuid,
|
||||||
origin.campus_uuid,srcm.principal_uuid,MIN(gr.created_at_ms) AS created_at_ms,
|
origin.campus_uuid,srcm.principal_uuid,MIN(gr.created_at_ms) AS created_at_ms,
|
||||||
CASE MAX(CASE gr.member_role WHEN 'owner' THEN 3 WHEN 'manager' THEN 2 ELSE 1 END)
|
CASE MAX(CASE gr.member_role WHEN 'owner' THEN 3 WHEN 'manager' THEN 2 ELSE 1 END)
|
||||||
WHEN 3 THEN 'owner' WHEN 2 THEN 'manager' ELSE 'member' END AS member_role
|
WHEN 3 THEN 'owner' WHEN 2 THEN 'manager' ELSE 'member' END AS member_role
|
||||||
FROM campus_admin_grants gr
|
FROM campus_admin_grants gr
|
||||||
JOIN groups src ON src.uuid=gr.group_uuid AND src.builtin_key='campus_admin'
|
JOIN ` + s.sqlGroupTable() + ` src ON src.uuid=gr.group_uuid AND src.builtin_key='campus_admin'
|
||||||
AND src.state='active' AND src.inherit_members=1
|
AND src.state='active' AND src.inherit_members=1
|
||||||
JOIN domains origin ON origin.uuid=src.domain_uuid AND origin.enabled=1
|
JOIN domains origin ON origin.uuid=src.domain_uuid AND origin.enabled=1
|
||||||
JOIN domain_memberships srcm ON srcm.uuid=gr.membership_uuid
|
JOIN domain_memberships srcm ON srcm.uuid=gr.membership_uuid
|
||||||
@@ -121,35 +121,37 @@ func (s *Store) projectCampusAdminMembershipsContext(ctx context.Context, tx *sq
|
|||||||
newUUID := `lower(hex(randomblob(4)))||'-'||lower(hex(randomblob(2)))||'-4'||substr(lower(hex(randomblob(2))),2)||'-a'||substr(lower(hex(randomblob(2))),2)||'-'||lower(hex(randomblob(6)))`
|
newUUID := `lower(hex(randomblob(4)))||'-'||lower(hex(randomblob(2)))||'-4'||substr(lower(hex(randomblob(2))),2)||'-a'||substr(lower(hex(randomblob(2))),2)||'-'||lower(hex(randomblob(6)))`
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend == storePostgreSQL {
|
||||||
newUUID = `gen_random_uuid()::text`
|
newUUID = `gen_random_uuid()::text`
|
||||||
|
} else if s.sqlBackend == storeMySQL {
|
||||||
|
newUUID = `UUID()`
|
||||||
}
|
}
|
||||||
if _, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_membership_origins
|
if _, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_membership_origins
|
||||||
(membership_uuid,domain_uuid,principal_uuid)
|
(membership_uuid,domain_uuid,principal_uuid)
|
||||||
SELECT `+newUUID+`,domain_uuid,principal_uuid FROM (
|
SELECT `+newUUID+`,domain_uuid,principal_uuid FROM (
|
||||||
SELECT DISTINCT dst.uuid AS domain_uuid,root.principal_uuid FROM (`+roots+`) root
|
SELECT DISTINCT dst.uuid AS domain_uuid,root.principal_uuid FROM (`+roots+`) root
|
||||||
JOIN domains dst ON dst.campus_uuid=root.campus_uuid AND dst.uuid!=root.source_domain_uuid AND dst.enabled=1
|
JOIN domains dst ON dst.campus_uuid=root.campus_uuid AND dst.uuid!=root.source_domain_uuid AND dst.enabled=1
|
||||||
JOIN groups dstg ON dstg.domain_uuid=dst.uuid AND dstg.builtin_key='campus_admin' AND dstg.state='active'
|
JOIN `+s.sqlGroupTable()+` dstg ON dstg.domain_uuid=dst.uuid AND dstg.builtin_key='campus_admin' AND dstg.state='active'
|
||||||
WHERE NOT EXISTS(SELECT 1 FROM domain_memberships m
|
WHERE NOT EXISTS(SELECT 1 FROM domain_memberships m
|
||||||
WHERE m.domain_uuid=dst.uuid AND m.principal_uuid=root.principal_uuid)) AS missing_memberships WHERE 1=1 ON CONFLICT(domain_uuid,principal_uuid) DO NOTHING`); err != nil {
|
WHERE m.domain_uuid=dst.uuid AND m.principal_uuid=root.principal_uuid)) AS missing_memberships WHERE 1=1`+s.sqlConflictDoNothing("campus_admin_membership_origins", "membership_uuid", "domain_uuid,principal_uuid")); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := tx.ExecContext(ctx, `INSERT INTO domain_memberships
|
if _, err := tx.ExecContext(ctx, `INSERT INTO domain_memberships
|
||||||
(uuid,domain_uuid,principal_uuid,state,created_at_ms)
|
(uuid,domain_uuid,principal_uuid,state,created_at_ms)
|
||||||
SELECT membership_uuid,domain_uuid,principal_uuid,'active',`+s.sqlParam(1)+`
|
SELECT membership_uuid,domain_uuid,principal_uuid,'active',`+s.sqlParam(1)+`
|
||||||
FROM campus_admin_membership_origins WHERE 1=1 ON CONFLICT(domain_uuid,principal_uuid) DO NOTHING`, now); err != nil {
|
FROM campus_admin_membership_origins WHERE 1=1`+s.sqlConflictDoNothing("domain_memberships", "uuid", "domain_uuid,principal_uuid"), now); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_grants
|
if _, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_grants
|
||||||
(group_uuid,membership_uuid,source,member_role,created_at_ms)
|
(group_uuid,membership_uuid,source,member_role,created_at_ms)
|
||||||
SELECT dstg.uuid,dstm.uuid,'campus_admin_inherit:'||root.source_group_uuid,root.member_role,root.created_at_ms
|
SELECT dstg.uuid,dstm.uuid,`+s.sqlConcat("'campus_admin_inherit:'", "root.source_group_uuid")+`,root.member_role,root.created_at_ms
|
||||||
FROM (`+roots+`) root
|
FROM (`+roots+`) root
|
||||||
JOIN domains dst ON dst.campus_uuid=root.campus_uuid AND dst.uuid!=root.source_domain_uuid AND dst.enabled=1
|
JOIN domains dst ON dst.campus_uuid=root.campus_uuid AND dst.uuid!=root.source_domain_uuid AND dst.enabled=1
|
||||||
JOIN groups dstg ON dstg.domain_uuid=dst.uuid AND dstg.builtin_key='campus_admin' AND dstg.state='active'
|
JOIN `+s.sqlGroupTable()+` dstg ON dstg.domain_uuid=dst.uuid AND dstg.builtin_key='campus_admin' AND dstg.state='active'
|
||||||
JOIN domain_memberships dstm ON dstm.domain_uuid=dst.uuid AND dstm.principal_uuid=root.principal_uuid
|
JOIN domain_memberships dstm ON dstm.domain_uuid=dst.uuid AND dstm.principal_uuid=root.principal_uuid
|
||||||
AND dstm.state='active'`); err != nil {
|
AND dstm.state='active'`); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := tx.ExecContext(ctx, `DELETE FROM group_members WHERE
|
if _, err := tx.ExecContext(ctx, `DELETE FROM group_members WHERE
|
||||||
group_uuid IN (SELECT uuid FROM groups WHERE builtin_key='campus_admin')
|
group_uuid IN (SELECT uuid FROM `+s.sqlGroupTable()+` WHERE builtin_key='campus_admin')
|
||||||
OR substr(source,1,21)='campus_admin_inherit:'`); err != nil {
|
OR substr(source,1,21)='campus_admin_inherit:'`); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -160,11 +162,11 @@ func (s *Store) projectCampusAdminMembershipsContext(ctx context.Context, tx *sq
|
|||||||
SELECT gr.*,ROW_NUMBER() OVER(PARTITION BY gr.group_uuid,gr.membership_uuid
|
SELECT gr.*,ROW_NUMBER() OVER(PARTITION BY gr.group_uuid,gr.membership_uuid
|
||||||
ORDER BY CASE gr.member_role WHEN 'owner' THEN 3 WHEN 'manager' THEN 2 ELSE 1 END DESC,
|
ORDER BY CASE gr.member_role WHEN 'owner' THEN 3 WHEN 'manager' THEN 2 ELSE 1 END DESC,
|
||||||
CASE WHEN substr(gr.source,1,21)='campus_admin_inherit:' THEN 1 ELSE 0 END,
|
CASE WHEN substr(gr.source,1,21)='campus_admin_inherit:' THEN 1 ELSE 0 END,
|
||||||
gr.source) AS rank
|
gr.source) AS grant_rank
|
||||||
FROM campus_admin_grants gr JOIN groups g ON g.uuid=gr.group_uuid
|
FROM campus_admin_grants gr JOIN `+s.sqlGroupTable()+` g ON g.uuid=gr.group_uuid
|
||||||
JOIN domains d ON d.uuid=g.domain_uuid
|
JOIN domains d ON d.uuid=g.domain_uuid
|
||||||
JOIN domain_memberships m ON m.uuid=gr.membership_uuid AND m.domain_uuid=g.domain_uuid
|
JOIN domain_memberships m ON m.uuid=gr.membership_uuid AND m.domain_uuid=g.domain_uuid
|
||||||
) AS ranked_grants WHERE rank=1`); err != nil {
|
) AS ranked_grants WHERE grant_rank=1`); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// A newly added independent group/role grant adopts an inherited membership
|
// A newly added independent group/role grant adopts an inherited membership
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// All helpers are called under the same transactional administrative lock as
|
||||||
|
// SQLite/PostgreSQL. Never use MySQL RowsAffected to infer existence on UPSERT:
|
||||||
|
// unchanged/update/insert can report 0/2/1 respectively.
|
||||||
|
func (s *Store) ensureMySQLBuiltinGroups(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
rows, err := tx.QueryContext(ctx, `SELECT uuid FROM domains ORDER BY uuid`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var domains []string
|
||||||
|
for rows.Next() {
|
||||||
|
var id string
|
||||||
|
if err := rows.Scan(&id); err != nil {
|
||||||
|
rows.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
domains = append(domains, id)
|
||||||
|
}
|
||||||
|
err = rows.Err()
|
||||||
|
rows.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
now := time.Now().UnixMilli()
|
||||||
|
for _, domain := range domains {
|
||||||
|
for _, key := range []string{"campus_admin", "domain_admin"} {
|
||||||
|
inherit := 0
|
||||||
|
if key == "campus_admin" {
|
||||||
|
inherit = 1
|
||||||
|
}
|
||||||
|
_, err := tx.ExecContext(ctx, "INSERT INTO `groups`(uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms) VALUES(?,?,?,?,?,'members','active',?,?,?,?) ON DUPLICATE KEY UPDATE builtin_key=?", uuid.NewString(), domain, key, strings.ReplaceAll(key, "_", " "), "Built-in administrative group", key, inherit, now, now, key)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, err := tx.ExecContext(ctx, `INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms)
|
||||||
|
SELECT g.uuid,m.uuid,'owner','migration',? FROM `+"`groups`"+` g
|
||||||
|
JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid
|
||||||
|
JOIN auth_role_bindings b ON b.membership_uuid=m.uuid
|
||||||
|
JOIN auth_roles r ON r.uuid=b.role_uuid AND r.domain_uuid=m.domain_uuid
|
||||||
|
JOIN auth_capability_grants c ON c.role_uuid=r.uuid AND c.capability='manage' AND c.target_type='domain' AND (c.target_id=m.domain_uuid OR c.target_id='*')
|
||||||
|
WHERE g.domain_uuid=? AND g.builtin_key='domain_admin'
|
||||||
|
ON DUPLICATE KEY UPDATE group_uuid=group_members.group_uuid`, now, domain)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := s.seedCampusAdminRoleGrantsContext(ctx, tx, now); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.projectCampusAdminMembershipsContext(ctx, tx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mysqlAddGroupMember(ctx context.Context, tx *sql.Tx, group, member, role string) error {
|
||||||
|
var previous string
|
||||||
|
err := tx.QueryRowContext(ctx, `SELECT member_role FROM group_members WHERE group_uuid=? AND membership_uuid=?`, group, member).Scan(&previous)
|
||||||
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if previous == "owner" && role != "owner" {
|
||||||
|
return namespaceValidationError("owner role cannot be downgraded by a member update")
|
||||||
|
}
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(?,?,?,'local',?) ON DUPLICATE KEY UPDATE member_role=?,source='local'`, group, member, role, time.Now().UnixMilli(), role)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func mysqlRemoveGroupMember(ctx context.Context, tx *sql.Tx, group, member string, authority bool) error {
|
||||||
|
var role string
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT member_role FROM group_members WHERE group_uuid=? AND membership_uuid=?`, group, member).Scan(&role); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !authority && role != "member" {
|
||||||
|
return namespaceValidationError("member removal requires sufficient authority")
|
||||||
|
}
|
||||||
|
if role == "owner" {
|
||||||
|
var other bool
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM group_members gm JOIN `+"`groups`"+` g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=? AND gm.membership_uuid!=? AND gm.member_role='owner')`, group, member).Scan(&other); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !other {
|
||||||
|
return namespaceValidationError("member removal requires at least one remaining owner")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, err := tx.ExecContext(ctx, `DELETE FROM group_members WHERE group_uuid=? AND membership_uuid=?`, group, member)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/machinelearning"
|
||||||
|
)
|
||||||
|
|
||||||
|
const machineLearningConfigKey = "machine_learning_policy_v1"
|
||||||
|
|
||||||
|
var ErrMachineLearningConflict = errors.New("machine learning configuration changed; reload before saving")
|
||||||
|
|
||||||
|
// MachineLearningPolicy returns disabled-by-default configuration. Invalid
|
||||||
|
// persisted data fails closed; it must not silently become a usable default.
|
||||||
|
func (s *Store) MachineLearningPolicy(ctx context.Context, domain string) (machinelearning.Policy, error) {
|
||||||
|
raw, err := s.mlConfig(ctx, domain)
|
||||||
|
if err != nil {
|
||||||
|
return machinelearning.Policy{}, err
|
||||||
|
}
|
||||||
|
if raw == "" {
|
||||||
|
return machinelearning.Policy{}, nil
|
||||||
|
}
|
||||||
|
var p machinelearning.Policy
|
||||||
|
if json.Unmarshal([]byte(raw), &p) != nil || p.Validate() != nil {
|
||||||
|
return machinelearning.Policy{}, machinelearning.ErrPolicy
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveMachineLearningPolicy is an internal persistence primitive. Its caller
|
||||||
|
// must authorize Domain administration (enforced by the settings API).
|
||||||
|
// Generation is server-assigned and updates use an atomic compare-and-swap.
|
||||||
|
func (s *Store) SaveMachineLearningPolicy(ctx context.Context, domain, baseGeneration string, p machinelearning.Policy) (machinelearning.Policy, error) {
|
||||||
|
id, err := uuid.Parse(domain)
|
||||||
|
if err != nil || id.String() != domain {
|
||||||
|
return machinelearning.Policy{}, machinelearning.ErrPolicy
|
||||||
|
}
|
||||||
|
raw, err := s.mlConfig(ctx, domain)
|
||||||
|
if err != nil {
|
||||||
|
return machinelearning.Policy{}, err
|
||||||
|
}
|
||||||
|
if raw == "" {
|
||||||
|
if baseGeneration != "" {
|
||||||
|
return machinelearning.Policy{}, ErrMachineLearningConflict
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var old machinelearning.Policy
|
||||||
|
if json.Unmarshal([]byte(raw), &old) != nil || old.Validate() != nil {
|
||||||
|
return machinelearning.Policy{}, machinelearning.ErrPolicy
|
||||||
|
}
|
||||||
|
if old.Generation != baseGeneration {
|
||||||
|
return machinelearning.Policy{}, ErrMachineLearningConflict
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.Generation = uuid.NewString()
|
||||||
|
if err = p.Validate(); err != nil {
|
||||||
|
return machinelearning.Policy{}, err
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(p)
|
||||||
|
if err != nil {
|
||||||
|
return machinelearning.Policy{}, err
|
||||||
|
}
|
||||||
|
var affected int64
|
||||||
|
if raw == "" {
|
||||||
|
query := `INSERT INTO config(domain_uuid,` + s.sqlConfigKey() + `,value,updated_at) VALUES (` + s.sqlValues(4) + `) ON CONFLICT(domain_uuid,key) DO NOTHING`
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
query = `INSERT INTO config(domain_uuid,` + s.sqlConfigKey() + `,value,updated_at) VALUES (?,?,?,?)`
|
||||||
|
}
|
||||||
|
result, e := s.DB.ExecContext(ctx, query, domain, machineLearningConfigKey, string(data), time.Now().Unix())
|
||||||
|
if e != nil {
|
||||||
|
if s.sqlBackend == storeMySQL && mysqlDuplicate(e) {
|
||||||
|
return machinelearning.Policy{}, ErrMachineLearningConflict
|
||||||
|
}
|
||||||
|
return machinelearning.Policy{}, s.sqlError("create ML policy", e)
|
||||||
|
}
|
||||||
|
affected, err = result.RowsAffected()
|
||||||
|
} else {
|
||||||
|
comparison := `value=` + s.sqlParam(5)
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
comparison = `BINARY value=BINARY ?`
|
||||||
|
}
|
||||||
|
result, e := s.DB.ExecContext(ctx, `UPDATE config SET value=`+s.sqlParam(1)+`,updated_at=`+s.sqlParam(2)+` WHERE domain_uuid=`+s.sqlParam(3)+` AND `+s.sqlConfigKey()+`=`+s.sqlParam(4)+` AND `+comparison, string(data), time.Now().Unix(), domain, machineLearningConfigKey, raw)
|
||||||
|
if e != nil {
|
||||||
|
return machinelearning.Policy{}, s.sqlError("update ML policy", e)
|
||||||
|
}
|
||||||
|
affected, err = result.RowsAffected()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return machinelearning.Policy{}, err
|
||||||
|
}
|
||||||
|
if affected != 1 {
|
||||||
|
return machinelearning.Policy{}, ErrMachineLearningConflict
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
"pageswiki/internal/machinelearning"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrMLBudget = errors.New("machine learning daily input budget exhausted or not configured")
|
||||||
|
var ErrMLAlreadyReserved = errors.New("machine learning request already reserved; do not resend")
|
||||||
|
|
||||||
|
var mlBudgetStatements = []string{
|
||||||
|
`CREATE TABLE ml_daily_budget(domain_uuid TEXT NOT NULL,day TEXT NOT NULL,reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>=0),PRIMARY KEY(domain_uuid,day))`,
|
||||||
|
`CREATE TABLE ml_budget_receipts(domain_uuid TEXT NOT NULL,request_uuid TEXT NOT NULL,day TEXT NOT NULL,input_hash TEXT NOT NULL,generation TEXT NOT NULL,reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>0),state TEXT NOT NULL CHECK(state IN ('reserved','completed','unknown')),actual_tokens BIGINT NOT NULL DEFAULT 0 CHECK(actual_tokens>=0),PRIMARY KEY(domain_uuid,request_uuid))`,
|
||||||
|
}
|
||||||
|
|
||||||
|
var mlBudgetMigrations = []db.SQLMigration{{Version: 1, Name: "ML daily reservations", Statements: mlBudgetStatements, Assertions: []string{
|
||||||
|
schemaColumns("ml_daily_budget", "domain_uuid,day,reserved_bytes"),
|
||||||
|
schemaUnique("ml_daily_budget", "domain_uuid,day"),
|
||||||
|
schemaColumns("ml_budget_receipts", "domain_uuid,request_uuid,day,input_hash,generation,reserved_bytes,state,actual_tokens"),
|
||||||
|
schemaUnique("ml_budget_receipts", "domain_uuid,request_uuid"),
|
||||||
|
}}}
|
||||||
|
|
||||||
|
// Explicit preparation for the future worker. Not called by ordinary settings
|
||||||
|
// reads/writes, and not automatically applied to production on this change.
|
||||||
|
func (s *Store) EnsureMLBudgetSchema(ctx context.Context) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return errors.New("use isolated MySQL ML schema preparation")
|
||||||
|
}
|
||||||
|
if s.sqlBackend == storePostgreSQL {
|
||||||
|
return db.ApplyPostgreSQLMigrations(ctx, s.DB, "machine-learning-budget", []db.PostgreSQLMigration{{Version: 1, Name: "ML daily reservations", Statements: mlBudgetStatements}})
|
||||||
|
}
|
||||||
|
return db.ApplySQLiteMigrations(ctx, s.DB, "machine-learning-budget", mlBudgetMigrations)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReserveMLInput prepares a request from CURRENT settings and reserves its byte
|
||||||
|
// cost atomically. Caller must authorize the document and learning cohort first.
|
||||||
|
// A returned request is permission for ONE attempt, never a retry receipt.
|
||||||
|
func (s *Store) ReserveMLInput(ctx context.Context, domain, requestID, logicalPath, generation string, inputs []machinelearning.Input) (machinelearning.Request, error) {
|
||||||
|
return s.reserveMLInputAt(ctx, domain, requestID, logicalPath, generation, inputs, time.Now())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) reserveMLInputAt(ctx context.Context, domain, requestID, logicalPath, generation string, inputs []machinelearning.Input, now time.Time) (machinelearning.Request, error) {
|
||||||
|
var empty machinelearning.Request
|
||||||
|
id, e := uuid.Parse(requestID)
|
||||||
|
if e != nil || id.String() != requestID {
|
||||||
|
return empty, machinelearning.ErrPolicy
|
||||||
|
}
|
||||||
|
var options *sql.TxOptions
|
||||||
|
if s.sqlBackend != storeSQLite {
|
||||||
|
options = &sql.TxOptions{Isolation: sql.LevelReadCommitted}
|
||||||
|
}
|
||||||
|
tx, e := s.DB.BeginTx(ctx, options)
|
||||||
|
if e != nil {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
// Lock the same configuration row that settings updates modify. This also
|
||||||
|
// serializes budget writers across processes, including policy generations.
|
||||||
|
if s.sqlBackend == storeSQLite {
|
||||||
|
if _, e = tx.ExecContext(ctx, `UPDATE config SET value=value WHERE domain_uuid=? AND key=?`, domain, machineLearningConfigKey); e != nil {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var raw string
|
||||||
|
lockQuery := `SELECT value FROM config WHERE domain_uuid=` + s.sqlParam(1) + ` AND ` + s.sqlConfigKey() + `=` + s.sqlParam(2)
|
||||||
|
if s.sqlBackend != storeSQLite {
|
||||||
|
lockQuery += ` FOR UPDATE`
|
||||||
|
}
|
||||||
|
if e = tx.QueryRowContext(ctx, lockQuery, domain, machineLearningConfigKey).Scan(&raw); e != nil {
|
||||||
|
if errors.Is(e, sql.ErrNoRows) {
|
||||||
|
return empty, machinelearning.ErrNotAllowed
|
||||||
|
}
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
var p machinelearning.Policy
|
||||||
|
if json.Unmarshal([]byte(raw), &p) != nil {
|
||||||
|
return empty, machinelearning.ErrPolicy
|
||||||
|
}
|
||||||
|
req, e := p.Prepare(domain, logicalPath, generation, inputs)
|
||||||
|
if e != nil {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
if p.DailyInputBytes <= 0 {
|
||||||
|
return empty, ErrMLBudget
|
||||||
|
}
|
||||||
|
var oldHash string
|
||||||
|
e = tx.QueryRowContext(ctx, `SELECT input_hash FROM ml_budget_receipts WHERE domain_uuid=`+s.sqlParam(1)+` AND request_uuid=`+s.sqlParam(2), domain, requestID).Scan(&oldHash)
|
||||||
|
if e == nil {
|
||||||
|
return empty, ErrMLAlreadyReserved
|
||||||
|
}
|
||||||
|
if !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
day := now.UTC().Format("2006-01-02")
|
||||||
|
var used int64
|
||||||
|
e = tx.QueryRowContext(ctx, `SELECT reserved_bytes FROM ml_daily_budget WHERE domain_uuid=`+s.sqlParam(1)+` AND day=`+s.sqlParam(2), domain, day).Scan(&used)
|
||||||
|
if e != nil && !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
var cost int64
|
||||||
|
for _, input := range req.Inputs {
|
||||||
|
cost += int64(len(input.Text))
|
||||||
|
}
|
||||||
|
if used > p.DailyInputBytes || cost > p.DailyInputBytes-used {
|
||||||
|
return empty, ErrMLBudget
|
||||||
|
}
|
||||||
|
budgetQuery := `INSERT INTO ml_daily_budget(domain_uuid,day,reserved_bytes) VALUES (` + s.sqlValues(3) + `) ON CONFLICT(domain_uuid,day) DO UPDATE SET reserved_bytes=excluded.reserved_bytes`
|
||||||
|
args := []any{domain, day, used + cost}
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
budgetQuery = `INSERT INTO ml_daily_budget(domain_uuid,day,reserved_bytes) VALUES (?,?,?) ON DUPLICATE KEY UPDATE reserved_bytes=?`
|
||||||
|
args = append(args, used+cost)
|
||||||
|
}
|
||||||
|
_, e = tx.ExecContext(ctx, budgetQuery, args...)
|
||||||
|
if e != nil {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
encoded, e := json.Marshal(req)
|
||||||
|
if e != nil {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
hash := sha256.Sum256(encoded)
|
||||||
|
_, e = tx.ExecContext(ctx, `INSERT INTO ml_budget_receipts(domain_uuid,request_uuid,day,input_hash,generation,reserved_bytes,state) VALUES (`+s.sqlValues(7)+`)`, domain, requestID, day, hex.EncodeToString(hash[:]), generation, cost, "reserved")
|
||||||
|
if e != nil {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
if e = tx.Commit(); e != nil {
|
||||||
|
return empty, e
|
||||||
|
}
|
||||||
|
return req, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FinishMLInput does not release reservations, including on timeout/crash.
|
||||||
|
// Actual token usage is informational and never increases the byte allowance.
|
||||||
|
func (s *Store) FinishMLInput(ctx context.Context, domain, requestID string, completed bool, actualTokens int64) error {
|
||||||
|
if actualTokens < 0 {
|
||||||
|
return machinelearning.ErrPolicy
|
||||||
|
}
|
||||||
|
state := "unknown"
|
||||||
|
if completed {
|
||||||
|
state = "completed"
|
||||||
|
}
|
||||||
|
r, e := s.DB.ExecContext(ctx, `UPDATE ml_budget_receipts SET state=`+s.sqlParam(1)+`,actual_tokens=`+s.sqlParam(2)+` WHERE domain_uuid=`+s.sqlParam(3)+` AND request_uuid=`+s.sqlParam(4)+` AND state='reserved'`, state, actualTokens, domain, requestID)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
n, e := r.RowsAffected()
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
return ErrMLAlreadyReserved
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/machinelearning"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMLBudget(t *testing.T) {
|
||||||
|
for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
|
t.Run(fmt.Sprint(backend), func(t *testing.T) {
|
||||||
|
s, d := mlTestStore(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
if backend != storeMySQL {
|
||||||
|
if e := s.EnsureMLBudgetSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := s.EnsureMLBudgetSchema(ctx); e != nil {
|
||||||
|
t.Fatal("migration rerun", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p, e := s.SaveMachineLearningPolicy(ctx, d.UUID, "", machinelearning.Policy{Enabled: true, ScopeUUID: uuid.NewString(), Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, MaxBatchBytes: 6000, DailyInputBytes: 10})
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
day := time.Date(2026, 11, 28, 23, 59, 0, 0, time.UTC)
|
||||||
|
inputs := []machinelearning.Input{{ID: "chunk", Text: "abcdef"}}
|
||||||
|
reserve := func(id string, at time.Time) error {
|
||||||
|
_, err := s.reserveMLInputAt(ctx, d.UUID, id, "/lab/doc", p.Generation, inputs, at)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id := uuid.NewString()
|
||||||
|
if e = reserve(id, day); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = reserve(id, day); !errors.Is(e, ErrMLAlreadyReserved) {
|
||||||
|
t.Fatal("duplicate", e)
|
||||||
|
}
|
||||||
|
if e = s.FinishMLInput(ctx, d.UUID, id, false, 0); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = s.FinishMLInput(ctx, d.UUID, id, true, 1); !errors.Is(e, ErrMLAlreadyReserved) {
|
||||||
|
t.Fatal("settled receipt changed", e)
|
||||||
|
}
|
||||||
|
if e = reserve(uuid.NewString(), day); !errors.Is(e, ErrMLBudget) {
|
||||||
|
t.Fatal("unknown refunded", e)
|
||||||
|
}
|
||||||
|
// New UTC day resets allowance, not idempotency receipts.
|
||||||
|
if e = reserve(id, day.Add(time.Minute)); !errors.Is(e, ErrMLAlreadyReserved) {
|
||||||
|
t.Fatal("old ID reused", e)
|
||||||
|
}
|
||||||
|
start := make(chan struct{})
|
||||||
|
results := make(chan error, 2)
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
go func() { <-start; results <- reserve(uuid.NewString(), day.Add(time.Minute)) }()
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
wins := 0
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
e = <-results
|
||||||
|
if e == nil {
|
||||||
|
wins++
|
||||||
|
} else if !errors.Is(e, ErrMLBudget) {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if wins != 1 {
|
||||||
|
t.Fatal("concurrent overspend", wins)
|
||||||
|
}
|
||||||
|
// Policy generations never reset usage. Reducing limits fails closed.
|
||||||
|
old := p.Generation
|
||||||
|
p.DailyInputBytes = 5
|
||||||
|
p, e = s.SaveMachineLearningPolicy(ctx, d.UUID, old, p)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = reserve(uuid.NewString(), day); !errors.Is(e, ErrMLBudget) {
|
||||||
|
t.Fatal("policy reset budget", e)
|
||||||
|
}
|
||||||
|
_, e = s.reserveMLInputAt(ctx, d.UUID, uuid.NewString(), "/lab/doc", old, inputs, day)
|
||||||
|
if !errors.Is(e, machinelearning.ErrNotAllowed) {
|
||||||
|
t.Fatal("old consent", e)
|
||||||
|
}
|
||||||
|
p.DailyInputBytes = 0
|
||||||
|
p, e = s.SaveMachineLearningPolicy(ctx, d.UUID, p.Generation, p)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = reserve(uuid.NewString(), day.Add(48*time.Hour)); !errors.Is(e, ErrMLBudget) {
|
||||||
|
t.Fatal("zero allows execution", e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"github.com/go-sql-driver/mysql"
|
||||||
|
"pageswiki/internal/machinelearning"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mysqlDuplicate(err error) bool {
|
||||||
|
var e *mysql.MySQLError
|
||||||
|
return errors.As(err, &e) && e.Number == 1062
|
||||||
|
}
|
||||||
|
func (s *Store) mlConfig(ctx context.Context, domain string) (string, error) {
|
||||||
|
return s.GetConfigInDomainContext(ctx, domain, machineLearningConfigKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MySQLMLRepository deliberately exposes ONLY the ported ML component. Returning
|
||||||
|
// *Store would allow unported methods to silently execute SQLite-specific SQL.
|
||||||
|
// Caller supplies a separately prepared MySQL 8.4+ InnoDB pilot database.
|
||||||
|
// This is not a Pages server constructor, whole-app migration or deployment option.
|
||||||
|
type MySQLMLRepository struct{ store *Store }
|
||||||
|
|
||||||
|
func NewMySQLMLRepository(database *sql.DB) *MySQLMLRepository {
|
||||||
|
return &MySQLMLRepository{store: &Store{DB: database, sqlBackend: storeMySQL}}
|
||||||
|
}
|
||||||
|
func mlMySQLError(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, known := range []error{ErrMachineLearningConflict, ErrMLAlreadyReserved, ErrMLBudget, machinelearning.ErrNotAllowed, machinelearning.ErrPolicy, context.Canceled, context.DeadlineExceeded} {
|
||||||
|
if errors.Is(err, known) {
|
||||||
|
return known
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.New("MySQL ML operation failed")
|
||||||
|
}
|
||||||
|
func (r *MySQLMLRepository) Policy(ctx context.Context, domain string) (machinelearning.Policy, error) {
|
||||||
|
p, e := r.store.MachineLearningPolicy(ctx, domain)
|
||||||
|
return p, mlMySQLError(e)
|
||||||
|
}
|
||||||
|
func (r *MySQLMLRepository) SavePolicy(ctx context.Context, domain, base string, p machinelearning.Policy) (machinelearning.Policy, error) {
|
||||||
|
p, e := r.store.SaveMachineLearningPolicy(ctx, domain, base, p)
|
||||||
|
return p, mlMySQLError(e)
|
||||||
|
}
|
||||||
|
func (r *MySQLMLRepository) Reserve(ctx context.Context, domain, id, path, generation string, inputs []machinelearning.Input) (machinelearning.Request, error) {
|
||||||
|
q, e := r.store.ReserveMLInput(ctx, domain, id, path, generation, inputs)
|
||||||
|
return q, mlMySQLError(e)
|
||||||
|
}
|
||||||
|
func (r *MySQLMLRepository) Finish(ctx context.Context, domain, id string, completed bool, tokens int64) error {
|
||||||
|
return mlMySQLError(r.store.FinishMLInput(ctx, domain, id, completed, tokens))
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed mysql_ml_schema.sql
|
||||||
|
var mysqlMLSchema string
|
||||||
|
|
||||||
|
// All identifiers/signatures are owned constants. Check column shape, PK order,
|
||||||
|
// engine and CHECK count. This is not a comparison of all constraint semantics.
|
||||||
|
func mysqlMLTableCheck(table, columns, pk string, checks int) string {
|
||||||
|
return fmt.Sprintf(`SELECT
|
||||||
|
(SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='%s' AND engine='InnoDB')=1
|
||||||
|
AND (SELECT GROUP_CONCAT(CONCAT(column_name,':',column_type,':',is_nullable,':',COALESCE(collation_name,'')) ORDER BY ordinal_position SEPARATOR '|') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='%s')='%s'
|
||||||
|
AND (SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index SEPARATOR ',') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='%s' AND index_name='PRIMARY')='%s'
|
||||||
|
AND (SELECT COUNT(*) FROM information_schema.table_constraints WHERE constraint_schema=DATABASE() AND table_name='%s' AND constraint_type='CHECK')=%d`, table, table, columns, table, pk, table, checks)
|
||||||
|
}
|
||||||
|
|
||||||
|
var mysqlMLChecks = []string{
|
||||||
|
mysqlMLTableCheck("config", "domain_uuid:varchar(36):NO:ascii_bin|key:varchar(128):NO:ascii_bin|value:longtext:NO:utf8mb4_bin|updated_at:bigint:NO:", "domain_uuid,key", 0),
|
||||||
|
mysqlMLTableCheck("ml_daily_budget", "domain_uuid:varchar(36):NO:ascii_bin|day:char(10):NO:ascii_bin|reserved_bytes:bigint:NO:", "domain_uuid,day", 1),
|
||||||
|
mysqlMLTableCheck("ml_budget_receipts", "domain_uuid:varchar(36):NO:ascii_bin|request_uuid:varchar(36):NO:ascii_bin|day:char(10):NO:ascii_bin|input_hash:char(64):NO:ascii_bin|generation:varchar(36):NO:ascii_bin|reserved_bytes:bigint:NO:|state:varchar(16):NO:ascii_bin|actual_tokens:bigint:NO:", "domain_uuid,request_uuid", 3),
|
||||||
|
}
|
||||||
|
|
||||||
|
func mysqlMLMigrations() []db.MySQLMigration {
|
||||||
|
var ops []db.MySQLOperation
|
||||||
|
// This owned bundle contains three CREATE TABLE statements without stored
|
||||||
|
// procedures or semicolon-containing literals. Not a general SQL parser.
|
||||||
|
for _, statement := range strings.Split(mysqlMLSchema, ";") {
|
||||||
|
if strings.TrimSpace(statement) != "" {
|
||||||
|
ops = append(ops, db.MySQLOperation{SQL: strings.TrimSpace(statement), Check: mysqlMLChecks[len(ops)], ReplaySafe: true})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Preserve the v1 checksum. Core configuration needs Unicode keys and
|
||||||
|
// NO PAD comparisons ("key" and "key " must remain distinct).
|
||||||
|
configV2 := mysqlMLTableCheck("config", "domain_uuid:varchar(36):NO:ascii_bin|key:varchar(255):NO:utf8mb4_0900_bin|value:longtext:NO:utf8mb4_bin|updated_at:bigint:NO:", "domain_uuid,key", 0)
|
||||||
|
return []db.MySQLMigration{
|
||||||
|
{Version: 1, Name: "ML configuration and reservations", Operations: ops, Assertions: mysqlMLChecks},
|
||||||
|
{Version: 2, Name: "Unicode exact configuration keys", Operations: []db.MySQLOperation{{SQL: "ALTER TABLE config MODIFY COLUMN `key` VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin NOT NULL", Check: configV2, ReplaySafe: true}}, Assertions: []string{configV2, mysqlMLChecks[1], mysqlMLChecks[2]}},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (r *MySQLMLRepository) PrepareSchema(ctx context.Context) error {
|
||||||
|
return db.ApplyMySQLMigrations(ctx, r.store.DB, "machine-learning", mysqlMLMigrations())
|
||||||
|
}
|
||||||
|
func (r *MySQLMLRepository) InspectSchema(ctx context.Context) (db.MySQLMigrationStatus, error) {
|
||||||
|
return db.InspectMySQLMigrations(ctx, r.store.DB, "machine-learning", mysqlMLMigrations())
|
||||||
|
}
|
||||||
|
func (r *MySQLMLRepository) ResumeSchema(ctx context.Context) error {
|
||||||
|
return db.ResumeMySQLMigrations(ctx, r.store.DB, "machine-learning", mysqlMLMigrations())
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-sql-driver/mysql"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mlTestStore(t *testing.T, backend storeSQLBackend) (*Store, *Domain) {
|
||||||
|
t.Helper()
|
||||||
|
if backend != storeMySQL {
|
||||||
|
s := testNamespaceStore(t, backend)
|
||||||
|
d, e := s.GetDefaultDomain()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
return s, d
|
||||||
|
}
|
||||||
|
database := mysqlTestDatabase(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
repo := NewMySQLMLRepository(database)
|
||||||
|
status, e := repo.InspectSchema(ctx)
|
||||||
|
if e != nil || status.Applied != 0 || status.Pending != len(mysqlMLMigrations()) {
|
||||||
|
t.Fatal("fresh inspection", status, e)
|
||||||
|
}
|
||||||
|
if e = repo.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = repo.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal("repeat migration", e)
|
||||||
|
}
|
||||||
|
status, e = repo.InspectSchema(ctx)
|
||||||
|
if e != nil || status.Applied != len(mysqlMLMigrations()) || status.Dirty {
|
||||||
|
t.Fatal("applied inspection", status, e)
|
||||||
|
}
|
||||||
|
return repo.store, &Domain{UUID: uuid.NewString()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mysqlTestDatabase(t *testing.T) *sql.DB {
|
||||||
|
t.Helper()
|
||||||
|
dsn := os.Getenv("PAGESWIKI_TEST_MYSQL_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("set PAGESWIKI_TEST_MYSQL_DSN to a disposable MySQL server")
|
||||||
|
}
|
||||||
|
c, e := mysql.ParseDSN(dsn)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal("invalid test DSN")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
admin, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: dsn, AllowInsecure: true})
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
name := "pages_ml_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||||
|
if _, e = admin.ExecContext(ctx, "CREATE DATABASE "+name+" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); e != nil {
|
||||||
|
admin.Close()
|
||||||
|
t.Fatal("create isolated MySQL database failed")
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if _, e := admin.ExecContext(ctx, "DROP DATABASE "+name); e != nil {
|
||||||
|
t.Error("remove test database failed")
|
||||||
|
}
|
||||||
|
admin.Close()
|
||||||
|
})
|
||||||
|
c.DBName = name
|
||||||
|
database, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: c.FormatDSN(), AllowInsecure: true})
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { database.Close() })
|
||||||
|
return database
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/machinelearning"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMachineLearningPolicyPersistence(t *testing.T) {
|
||||||
|
for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
|
t.Run(fmt.Sprint(backend), func(t *testing.T) { testMachineLearningPolicyPersistence(t, backend) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testMachineLearningPolicyPersistence(t *testing.T, backend storeSQLBackend) {
|
||||||
|
s, domain := mlTestStore(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
empty, err := s.MachineLearningPolicy(ctx, domain.UUID)
|
||||||
|
if err != nil || empty.Enabled || empty.Generation != "" {
|
||||||
|
t.Fatal("not disabled by default", err)
|
||||||
|
}
|
||||||
|
p := machinelearning.Policy{Enabled: true, ScopeUUID: uuid.NewString(), Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, MaxBatchBytes: 6000}
|
||||||
|
saved, err := s.SaveMachineLearningPolicy(ctx, domain.UUID, "", p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if saved.Generation == "" || saved.Generation == p.Generation {
|
||||||
|
t.Fatal("generation not assigned")
|
||||||
|
}
|
||||||
|
if _, err = s.SaveMachineLearningPolicy(ctx, domain.UUID, "", p); !errors.Is(err, ErrMachineLearningConflict) {
|
||||||
|
t.Fatal("lost update", err)
|
||||||
|
}
|
||||||
|
loaded, err := s.MachineLearningPolicy(ctx, domain.UUID)
|
||||||
|
if err != nil || loaded.Generation != saved.Generation {
|
||||||
|
t.Fatal("roundtrip", err)
|
||||||
|
}
|
||||||
|
other, err := s.MachineLearningPolicy(ctx, uuid.NewString())
|
||||||
|
if err != nil || other.Enabled {
|
||||||
|
t.Fatal("cross domain leak", err)
|
||||||
|
}
|
||||||
|
p.Enabled = false
|
||||||
|
disabled, err := s.SaveMachineLearningPolicy(ctx, domain.UUID, saved.Generation, p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if disabled.Generation == saved.Generation || disabled.Allows("/lab", saved.Generation) {
|
||||||
|
t.Fatal("disable did not invalidate")
|
||||||
|
}
|
||||||
|
p.Enabled = true
|
||||||
|
reenabled, err := s.SaveMachineLearningPolicy(ctx, domain.UUID, disabled.Generation, p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if reenabled.Allows("/lab", saved.Generation) {
|
||||||
|
t.Fatal("old consent resurrected")
|
||||||
|
}
|
||||||
|
start := make(chan struct{})
|
||||||
|
results := make(chan error, 2)
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
go func() {
|
||||||
|
<-start
|
||||||
|
_, err := s.SaveMachineLearningPolicy(ctx, domain.UUID, reenabled.Generation, p)
|
||||||
|
results <- err
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
winners := 0
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
err := <-results
|
||||||
|
if err == nil {
|
||||||
|
winners++
|
||||||
|
} else if !errors.Is(err, ErrMachineLearningConflict) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if winners != 1 {
|
||||||
|
t.Fatal("concurrent configuration lost update", winners)
|
||||||
|
}
|
||||||
|
if _, err = s.DB.ExecContext(ctx, `UPDATE config SET value=`+s.sqlParam(1)+` WHERE domain_uuid=`+s.sqlParam(2)+` AND `+s.sqlConfigKey()+`=`+s.sqlParam(3), `{"enabled":true}`, domain.UUID, machineLearningConfigKey); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = s.MachineLearningPolicy(ctx, domain.UUID); !errors.Is(err, machinelearning.ErrPolicy) {
|
||||||
|
t.Fatal("corrupt policy did not fail closed", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mysqlProbe(name string) db.MySQLOperation {
|
||||||
|
return db.MySQLOperation{SQL: "CREATE TABLE " + name + "(id BIGINT PRIMARY KEY) ENGINE=InnoDB", Check: "SELECT COUNT(*)=1 FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='" + name + "'", ReplaySafe: true}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLMigrationRecovery(t *testing.T) {
|
||||||
|
s, _ := mlTestStore(t, storeMySQL)
|
||||||
|
ctx := context.Background()
|
||||||
|
a, b := mysqlProbe("migration_a"), mysqlProbe("migration_b")
|
||||||
|
// Second operation fails until an operator repairs the missing prerequisite.
|
||||||
|
b.SQL = "CREATE TABLE migration_b(id BIGINT PRIMARY KEY, parent BIGINT, FOREIGN KEY(parent) REFERENCES migration_parent(id)) ENGINE=InnoDB"
|
||||||
|
steps := []db.MySQLMigration{{Version: 1, Name: "recovery", Operations: []db.MySQLOperation{a, b}, Assertions: []string{a.Check, b.Check}}}
|
||||||
|
status, e := db.InspectMySQLMigrations(ctx, s.DB, "recovery", steps)
|
||||||
|
if e != nil || status.Applied != 0 || status.Pending != 1 {
|
||||||
|
t.Fatal(status, e)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if e = s.DB.QueryRow(`SELECT COUNT(*) FROM schema_mysql_migrations WHERE component='recovery'`).Scan(&count); e != nil || count != 0 {
|
||||||
|
t.Fatal("inspection wrote history", e)
|
||||||
|
}
|
||||||
|
if e = db.ApplyMySQLMigrations(ctx, s.DB, "recovery", steps); e == nil {
|
||||||
|
t.Fatal("expected DDL failure")
|
||||||
|
}
|
||||||
|
status, e = db.InspectMySQLMigrations(ctx, s.DB, "recovery", steps)
|
||||||
|
if e != nil || !status.Dirty || status.NextOperation != 1 {
|
||||||
|
t.Fatal("missing dirty progress", status, e)
|
||||||
|
}
|
||||||
|
if e = db.ApplyMySQLMigrations(ctx, s.DB, "recovery", steps); !errors.Is(e, db.ErrMySQLMigrationDirty) {
|
||||||
|
t.Fatal("silent retry", e)
|
||||||
|
}
|
||||||
|
if _, e = s.DB.Exec(`CREATE TABLE migration_parent(id BIGINT PRIMARY KEY) ENGINE=InnoDB`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = db.ResumeMySQLMigrations(ctx, s.DB, "recovery", steps); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = db.ApplyMySQLMigrations(ctx, s.DB, "recovery", steps); e != nil {
|
||||||
|
t.Fatal("repeat apply", e)
|
||||||
|
}
|
||||||
|
// Simulate loss of journal acknowledgement after DDL committed. Resume must
|
||||||
|
// verify the postcondition and skip CREATE, not blindly replay it.
|
||||||
|
if _, e = s.DB.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=0 WHERE component='recovery'`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e = db.ResumeMySQLMigrations(ctx, s.DB, "recovery", steps); e != nil {
|
||||||
|
t.Fatal("DDL-before-journal recovery", e)
|
||||||
|
}
|
||||||
|
changed := append([]db.MySQLMigration(nil), steps...)
|
||||||
|
changed[0].Name = "changed"
|
||||||
|
if e = db.ApplyMySQLMigrations(ctx, s.DB, "recovery", changed); !errors.Is(e, db.ErrMySQLMigrationMismatch) {
|
||||||
|
t.Fatal("checksum mismatch accepted", e)
|
||||||
|
}
|
||||||
|
// Unknown future version must not be silently downgraded.
|
||||||
|
if _, e = s.DB.Exec(`UPDATE schema_mysql_migrations SET version=9 WHERE component='recovery'`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e = db.InspectMySQLMigrations(ctx, s.DB, "recovery", steps); !errors.Is(e, db.ErrMySQLMigrationMismatch) {
|
||||||
|
t.Fatal("future version accepted", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLMigrationConcurrencyAndDrift(t *testing.T) {
|
||||||
|
s, _ := mlTestStore(t, storeMySQL)
|
||||||
|
ctx := context.Background()
|
||||||
|
op := mysqlProbe("migration_concurrent")
|
||||||
|
steps := []db.MySQLMigration{{Version: 1, Name: "concurrent", Operations: []db.MySQLOperation{op}, Assertions: []string{op.Check}}}
|
||||||
|
start := make(chan struct{})
|
||||||
|
results := make(chan error, 2)
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
go func() { <-start; results <- db.ApplyMySQLMigrations(ctx, s.DB, "concurrent", steps) }()
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if e := <-results; e != nil {
|
||||||
|
t.Fatal("concurrent apply", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, e := s.DB.Exec(`ALTER TABLE config DROP PRIMARY KEY`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := NewMySQLMLRepository(s.DB).InspectSchema(ctx); e == nil {
|
||||||
|
t.Fatal("schema drift accepted")
|
||||||
|
}
|
||||||
|
// Error responses must not include full SQL/driver data.
|
||||||
|
bad := mysqlProbe("secret_probe")
|
||||||
|
bad.SQL = "INVALID SQL private-secret"
|
||||||
|
broken := []db.MySQLMigration{{Version: 1, Name: "bad", Operations: []db.MySQLOperation{bad}, Assertions: []string{bad.Check}}}
|
||||||
|
if e := db.ApplyMySQLMigrations(ctx, s.DB, "bad", broken); e == nil || strings.Contains(e.Error(), "private-secret") {
|
||||||
|
t.Fatal("unsafe error", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLMigrationRefusesUnsafeResumeAndAdoption(t *testing.T) {
|
||||||
|
s, _ := mlTestStore(t, storeMySQL)
|
||||||
|
ctx := context.Background()
|
||||||
|
op := mysqlProbe("migration_existing")
|
||||||
|
steps := []db.MySQLMigration{{Version: 1, Name: "existing", Operations: []db.MySQLOperation{op}, Assertions: []string{op.Check}}}
|
||||||
|
if _, e := s.DB.Exec(op.SQL); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := db.ApplyMySQLMigrations(ctx, s.DB, "adopt", steps); !errors.Is(e, db.ErrMySQLMigrationMismatch) {
|
||||||
|
t.Fatal("implicit adoption", e)
|
||||||
|
}
|
||||||
|
unsafe := mysqlProbe("migration_unsafe")
|
||||||
|
unsafe.SQL = "INVALID SQL"
|
||||||
|
unsafe.ReplaySafe = false
|
||||||
|
steps = []db.MySQLMigration{{Version: 1, Name: "unsafe", Operations: []db.MySQLOperation{unsafe}, Assertions: []string{unsafe.Check}}}
|
||||||
|
if e := db.ApplyMySQLMigrations(ctx, s.DB, "unsafe", steps); e == nil {
|
||||||
|
t.Fatal("expected failure")
|
||||||
|
}
|
||||||
|
if e := db.ResumeMySQLMigrations(ctx, s.DB, "unsafe", steps); !errors.Is(e, db.ErrMySQLMigrationDirty) {
|
||||||
|
t.Fatal("unsafe replay", e)
|
||||||
|
}
|
||||||
|
cancelCtx, cancel := context.WithCancel(ctx)
|
||||||
|
cancel()
|
||||||
|
if e := db.ApplyMySQLMigrations(cancelCtx, s.DB, "unsafe", steps); e == nil {
|
||||||
|
t.Fatal("cancel ignored")
|
||||||
|
}
|
||||||
|
// A canceled caller must not retain the session lock in the connection pool.
|
||||||
|
if _, e := db.InspectMySQLMigrations(ctx, s.DB, "unsafe", steps); e != nil {
|
||||||
|
t.Fatal("lock not released", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLMigrationVersionUpgrade(t *testing.T) {
|
||||||
|
s, _ := mlTestStore(t, storeMySQL)
|
||||||
|
ctx := context.Background()
|
||||||
|
op := mysqlProbe("migration_versioned")
|
||||||
|
firstCheck := `SELECT COUNT(*)=1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='migration_versioned'`
|
||||||
|
steps := []db.MySQLMigration{{Version: 1, Name: "initial", Operations: []db.MySQLOperation{op}, Assertions: []string{firstCheck}}}
|
||||||
|
if e := db.ApplyMySQLMigrations(ctx, s.DB, "versioned", steps); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
added := db.MySQLOperation{SQL: `ALTER TABLE migration_versioned ADD COLUMN label VARCHAR(64) NOT NULL DEFAULT ''`, Check: `SELECT COUNT(*)=1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='migration_versioned' AND column_name='label'`, ReplaySafe: true}
|
||||||
|
steps = append(steps, db.MySQLMigration{Version: 2, Name: "label", Operations: []db.MySQLOperation{added}, Assertions: []string{op.Check, added.Check}})
|
||||||
|
if e := db.ApplyMySQLMigrations(ctx, s.DB, "versioned", steps); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
// Version 1's shape assertion is intentionally obsolete after the upgrade.
|
||||||
|
status, e := db.InspectMySQLMigrations(ctx, s.DB, "versioned", steps)
|
||||||
|
if e != nil || status.Applied != 2 || status.Pending != 0 || status.Dirty {
|
||||||
|
t.Fatal(status, e)
|
||||||
|
}
|
||||||
|
if e := db.ApplyMySQLMigrations(ctx, s.DB, "versioned", steps); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := db.InspectMySQLMigrations(ctx, s.DB, "versioned", steps[:1]); !errors.Is(e, db.ErrMySQLMigrationMismatch) {
|
||||||
|
t.Fatal("downgrade accepted", e)
|
||||||
|
}
|
||||||
|
if _, e := s.DB.Exec(`ALTER TABLE schema_mysql_migrations DROP PRIMARY KEY`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := db.InspectMySQLMigrations(ctx, s.DB, "versioned", steps); !errors.Is(e, db.ErrMySQLMigrationMismatch) {
|
||||||
|
t.Fatal("damaged journal accepted", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- Native MySQL ML component schema. Applied only by the journaled runner.
|
||||||
|
CREATE TABLE config (
|
||||||
|
domain_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
`key` VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
value LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
|
||||||
|
updated_at BIGINT NOT NULL,
|
||||||
|
PRIMARY KEY(domain_uuid,`key`)
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
CREATE TABLE ml_daily_budget (
|
||||||
|
domain_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
day CHAR(10) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>=0),
|
||||||
|
PRIMARY KEY(domain_uuid,day)
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
CREATE TABLE ml_budget_receipts (
|
||||||
|
domain_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
request_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
day CHAR(10) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
input_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
generation VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||||
|
reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>0),
|
||||||
|
state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL CHECK(state IN ('reserved','completed','unknown')),
|
||||||
|
actual_tokens BIGINT NOT NULL DEFAULT 0 CHECK(actual_tokens>=0),
|
||||||
|
PRIMARY KEY(domain_uuid,request_uuid)
|
||||||
|
) ENGINE=InnoDB;
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MySQLNamespaceRepository exposes only the ported subset. In particular Domain
|
||||||
|
// mutations and Campus deletion require auth/federation repositories which are
|
||||||
|
// not ported yet. No *Store escapes and no server backend is enabled here.
|
||||||
|
type MySQLNamespaceRepository struct{ store *Store }
|
||||||
|
|
||||||
|
func NewMySQLNamespaceRepository(database *sql.DB) *MySQLNamespaceRepository {
|
||||||
|
return &MySQLNamespaceRepository{store: &Store{DB: database, sqlBackend: storeMySQL}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mysqlStoreError(operation string, err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, known := range []error{sql.ErrNoRows, context.Canceled, context.DeadlineExceeded, ErrReadOnly, ErrBackendFeatureUnavailable, ErrAccessDenied} {
|
||||||
|
if errors.Is(err, known) {
|
||||||
|
return known
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var validation namespaceValidationError
|
||||||
|
if errors.As(err, &validation) {
|
||||||
|
return validation
|
||||||
|
}
|
||||||
|
// Duplicate/truncation/encoding errors may contain private names or values.
|
||||||
|
// operation is an owned constant, not a request parameter.
|
||||||
|
return errors.New("MySQL " + operation + " failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MySQLNamespaceRepository) Campuses(ctx context.Context) ([]Campus, error) {
|
||||||
|
return r.store.ListCampusesContext(ctx)
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) Domains(ctx context.Context) ([]Domain, error) {
|
||||||
|
return r.store.ListDomainsContext(ctx)
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) ResolveHost(ctx context.Context, host string) (*Domain, error) {
|
||||||
|
return r.store.GetDomainByHostContext(ctx, host)
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) EffectiveHost(ctx context.Context, domain string) (string, error) {
|
||||||
|
if err := mysqlNamespaceUUID(domain); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return r.store.GetDomainEffectiveHostContext(ctx, domain)
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) CreateCampus(ctx context.Context, name, title, language, mode, fqdn string, enabled bool) error {
|
||||||
|
if utf8.RuneCountInString(normalizeCampusName(name)) > 255 {
|
||||||
|
return namespaceValidationError("campus name too long")
|
||||||
|
}
|
||||||
|
return r.store.CreateCampusContext(ctx, name, title, language, mode, fqdn, enabled)
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) UpdateCampus(ctx context.Context, id int64, name, title, language, mode, fqdn string, enabled bool) error {
|
||||||
|
if strings.EqualFold(strings.TrimSpace(mode), "managed") {
|
||||||
|
return namespaceValidationError("managed campus must be added through controller enrollment")
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(normalizeCampusName(name)) > 255 {
|
||||||
|
return namespaceValidationError("campus name too long")
|
||||||
|
}
|
||||||
|
return r.store.UpdateCampusContext(ctx, id, name, title, language, mode, fqdn, enabled)
|
||||||
|
}
|
||||||
|
func mysqlNamespaceUUID(value string) error {
|
||||||
|
id, err := uuid.Parse(value)
|
||||||
|
if err != nil || id.String() != value {
|
||||||
|
return namespaceValidationError("canonical domain UUID required")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func mysqlNamespaceConfigKey(domain, key string) error {
|
||||||
|
if err := mysqlNamespaceUUID(domain); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !utf8.ValidString(key) || utf8.RuneCountInString(key) > 255 {
|
||||||
|
return namespaceValidationError("configuration key invalid or too long")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) Config(ctx context.Context, domain, key string) (string, error) {
|
||||||
|
if err := mysqlNamespaceConfigKey(domain, key); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if _, err := r.store.GetDomainByUUIDContext(ctx, domain); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return r.store.GetConfigInDomainContext(ctx, domain, key)
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) SetConfig(ctx context.Context, domain, key, value string) error {
|
||||||
|
if r.store.ReadOnly {
|
||||||
|
return ErrReadOnly
|
||||||
|
}
|
||||||
|
if err := mysqlNamespaceConfigKey(domain, key); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// ML policy writes must retain generation CAS; the generic config API is
|
||||||
|
// not a second way to overwrite an active reservation's policy.
|
||||||
|
if key == machineLearningConfigKey {
|
||||||
|
return namespaceValidationError("use ML policy compare-and-swap")
|
||||||
|
}
|
||||||
|
return r.store.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
var found int
|
||||||
|
if err := tx.QueryRowContext(ctx, `SELECT 1 FROM domains WHERE uuid=?`, domain).Scan(&found); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.store.setConfigWith(ctx, tx, domain, key, value)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mysqlNamespaceMigrations() []db.MySQLMigration {
|
||||||
|
// config remains owned by the existing machine-learning migration ledger;
|
||||||
|
// do not adopt it into a second history or change the published v1 checksum.
|
||||||
|
statements := []string{
|
||||||
|
`CREATE TABLE campuses(id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE,name VARCHAR(255) NOT NULL UNIQUE,title LONGTEXT NOT NULL,default_lang VARCHAR(64) NOT NULL DEFAULT 'en',authority_mode VARCHAR(32) NOT NULL DEFAULT 'standalone',fqdn VARCHAR(253) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'localhost',controller_transport VARCHAR(8) NOT NULL DEFAULT 'https',last_contact_at BIGINT NOT NULL DEFAULT 0,last_contact_error TEXT NOT NULL DEFAULT (''),enabled INTEGER NOT NULL DEFAULT 1,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin`,
|
||||||
|
`CREATE TABLE domains(id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE,name VARCHAR(255) NOT NULL UNIQUE,title LONGTEXT NOT NULL,domain VARCHAR(253) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',enabled INTEGER NOT NULL DEFAULT 1,created_at BIGINT NOT NULL,campus_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin,placement VARCHAR(32) NOT NULL DEFAULT 'local',instance_fqdn VARCHAR(253) NOT NULL DEFAULT '',instance_fingerprint VARCHAR(255) NOT NULL DEFAULT '',INDEX idx_domains_campus_uuid(campus_uuid)) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin`,
|
||||||
|
`CREATE TABLE namespace_write_lock(id INTEGER NOT NULL PRIMARY KEY,CHECK(id=1)) ENGINE=InnoDB`,
|
||||||
|
}
|
||||||
|
// The postconditions cover columns, keys, identities and the lock table.
|
||||||
|
checks := []string{
|
||||||
|
mysqlNamespaceTableCheck("campuses", "id:bigint:NO:|uuid:varchar(36):NO:ascii_bin|name:varchar(255):NO:utf8mb4_0900_bin|title:longtext:NO:utf8mb4_0900_bin|default_lang:varchar(64):NO:utf8mb4_0900_bin|authority_mode:varchar(32):NO:utf8mb4_0900_bin|fqdn:varchar(253):NO:ascii_bin|controller_transport:varchar(8):NO:utf8mb4_0900_bin|last_contact_at:bigint:NO:|last_contact_error:text:NO:utf8mb4_0900_bin|enabled:int:NO:|created_at:bigint:NO:"),
|
||||||
|
mysqlNamespaceTableCheck("domains", "id:bigint:NO:|uuid:varchar(36):NO:ascii_bin|name:varchar(255):NO:utf8mb4_0900_bin|title:longtext:NO:utf8mb4_0900_bin|domain:varchar(253):NO:ascii_bin|enabled:int:NO:|created_at:bigint:NO:|campus_uuid:varchar(36):YES:ascii_bin|placement:varchar(32):NO:utf8mb4_0900_bin|instance_fqdn:varchar(253):NO:utf8mb4_0900_bin|instance_fingerprint:varchar(255):NO:utf8mb4_0900_bin"),
|
||||||
|
mysqlMLTableCheck("namespace_write_lock", "id:int:NO:", "id", 1),
|
||||||
|
}
|
||||||
|
var ops []db.MySQLOperation
|
||||||
|
for i, statement := range statements {
|
||||||
|
ops = append(ops, db.MySQLOperation{SQL: statement, Check: checks[i], ReplaySafe: true})
|
||||||
|
}
|
||||||
|
return []db.MySQLMigration{{Version: 1, Name: "Campus and Domain read model", Operations: ops, Assertions: checks}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Owned identifiers only. No user SQL is interpolated here.
|
||||||
|
func mysqlNamespaceTableCheck(table, columns string) string {
|
||||||
|
return mysqlMLTableCheck(table, columns, "id", 0) + ` AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='` + table + `' AND column_name='id' AND extra='auto_increment')=1
|
||||||
|
AND (SELECT COUNT(*) FROM (SELECT index_name FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='` + table + `' AND non_unique=0 GROUP BY index_name HAVING COUNT(*)=1 AND MAX(column_name) IN ('uuid','name')) AS unique_keys)=2`
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) PrepareSchema(ctx context.Context) error {
|
||||||
|
if err := NewMySQLMLRepository(r.store.DB).PrepareSchema(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return db.ApplyMySQLMigrations(ctx, r.store.DB, "store-namespaces", mysqlNamespaceMigrations())
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) InspectSchema(ctx context.Context) (db.MySQLMigrationStatus, error) {
|
||||||
|
base, err := NewMySQLMLRepository(r.store.DB).InspectSchema(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return db.MySQLMigrationStatus{}, err
|
||||||
|
}
|
||||||
|
namespace, err := db.InspectMySQLMigrations(ctx, r.store.DB, "store-namespaces", mysqlNamespaceMigrations())
|
||||||
|
if err != nil {
|
||||||
|
return namespace, err
|
||||||
|
}
|
||||||
|
// Counts include dependencies; identify the first component to repair.
|
||||||
|
combined := db.MySQLMigrationStatus{Applied: base.Applied + namespace.Applied, Pending: base.Pending + namespace.Pending, Dirty: base.Dirty || namespace.Dirty}
|
||||||
|
if base.Dirty {
|
||||||
|
combined.DirtyComponent, combined.NextOperation = base.DirtyComponent, base.NextOperation
|
||||||
|
} else if namespace.Dirty {
|
||||||
|
combined.DirtyComponent, combined.NextOperation = namespace.DirtyComponent, namespace.NextOperation
|
||||||
|
}
|
||||||
|
return combined, nil
|
||||||
|
}
|
||||||
|
func (r *MySQLNamespaceRepository) ResumeSchema(ctx context.Context) error {
|
||||||
|
status, err := NewMySQLMLRepository(r.store.DB).InspectSchema(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if status.Dirty || status.Pending != 0 {
|
||||||
|
return db.ErrMySQLMigrationMismatch
|
||||||
|
}
|
||||||
|
return db.ResumeMySQLMigrations(ctx, r.store.DB, "store-namespaces", mysqlNamespaceMigrations())
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"pageswiki/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Bootstrap is fixture-only. The public facade intentionally cannot create a
|
||||||
|
// Domain until built-in groups and inherited permissions are ported together.
|
||||||
|
func testNamespaceCoreStore(t *testing.T, backend storeSQLBackend) *Store {
|
||||||
|
t.Helper()
|
||||||
|
if backend != storeMySQL {
|
||||||
|
return testNamespaceStore(t, backend)
|
||||||
|
}
|
||||||
|
s, _ := mlTestStore(t, backend)
|
||||||
|
r := &MySQLNamespaceRepository{store: s}
|
||||||
|
ctx := context.Background()
|
||||||
|
if e := r.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal("repeat prepare", e)
|
||||||
|
}
|
||||||
|
if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 0 || status.Dirty {
|
||||||
|
t.Fatal("inspect", status, e)
|
||||||
|
}
|
||||||
|
if e := r.CreateCampus(ctx, "default", "Default Campus", "en", "standalone", "localhost", true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
campus, e := s.GetDefaultCampus()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
seedNamespaceDomain(t, s, campus.UUID, "default", "")
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNamespaceCoreThreeBackendContract(t *testing.T) {
|
||||||
|
for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} {
|
||||||
|
t.Run(fmt.Sprint(backend), func(t *testing.T) {
|
||||||
|
s := testNamespaceCoreStore(t, backend)
|
||||||
|
ctx := context.Background()
|
||||||
|
create, update := s.CreateCampusContext, s.UpdateCampusContext
|
||||||
|
read, write := s.GetConfigInDomainContext, s.SetConfigInDomainContext
|
||||||
|
resolve, effective := s.GetDomainByHostContext, s.GetDomainEffectiveHostContext
|
||||||
|
if backend == storeMySQL {
|
||||||
|
r := &MySQLNamespaceRepository{store: s}
|
||||||
|
create, update, read, write, resolve, effective = r.CreateCampus, r.UpdateCampus, r.Config, r.SetConfig, r.ResolveHost, r.EffectiveHost
|
||||||
|
}
|
||||||
|
campus, e := s.GetDefaultCampus()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
domain, e := s.GetDefaultDomain()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := update(ctx, campus.ID, "default", "キャンパス 🏫", "ja", "standalone", "pages.example.test", true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := create(ctx, "OTHER", "別キャンパス", "en", "standalone", "other.example.test", true); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
campuses, e := s.ListCampusesContext(ctx)
|
||||||
|
if e != nil || len(campuses) != 2 {
|
||||||
|
t.Fatal(campuses, e)
|
||||||
|
}
|
||||||
|
var other Campus
|
||||||
|
for _, c := range campuses {
|
||||||
|
if c.UUID != campus.UUID {
|
||||||
|
other = c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
short := seedNamespaceDomain(t, s, campus.UUID, "short", "www")
|
||||||
|
absolute := seedNamespaceDomain(t, s, other.UUID, "absolute", "www.example.test")
|
||||||
|
for host, want := range map[string]string{"PAGES.EXAMPLE.TEST:443": domain.UUID, "www.pages.example.test": short.UUID, "www.example.test": absolute.UUID} {
|
||||||
|
got, e := resolve(ctx, host)
|
||||||
|
if e != nil || got.UUID != want {
|
||||||
|
t.Fatal("host resolution", host, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, e := effective(ctx, short.UUID); e != nil || got != "www.pages.example.test" {
|
||||||
|
t.Fatal(got, e)
|
||||||
|
}
|
||||||
|
if _, e := resolve(ctx, "absent.example.test"); !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
t.Fatal("fallback", e)
|
||||||
|
}
|
||||||
|
if e := update(ctx, campus.ID, "default", "must rollback", "en", "standalone", "example.test", true); e == nil {
|
||||||
|
t.Fatal("host collision accepted")
|
||||||
|
}
|
||||||
|
current, e := s.GetCampusByUUIDContext(ctx, campus.UUID)
|
||||||
|
if e != nil || current.Title != "キャンパス 🏫" || current.FQDN != "pages.example.test" {
|
||||||
|
t.Fatal("failed update persisted", current, e)
|
||||||
|
}
|
||||||
|
if e := update(ctx, campus.ID, "default", "disabled", "en", "standalone", "pages.example.test", false); e == nil {
|
||||||
|
t.Fatal("referenced Campus disabled")
|
||||||
|
}
|
||||||
|
if e := create(ctx, "managed", "Managed", "en", "managed", "managed.example.test", true); e == nil {
|
||||||
|
t.Fatal("managed creation bypassed enrollment")
|
||||||
|
}
|
||||||
|
keys := []string{"Key", "key", "key ", "日本語", "é", "e\u0301"}
|
||||||
|
for i, key := range keys {
|
||||||
|
for _, id := range []string{short.UUID, absolute.UUID} {
|
||||||
|
v := fmt.Sprintf("%s-%d-本文 🗒️\n? ' \"", id, i)
|
||||||
|
if e := write(ctx, id, key, "old"); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := write(ctx, id, key, v); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i, key := range keys {
|
||||||
|
for _, id := range []string{short.UUID, absolute.UUID} {
|
||||||
|
want := fmt.Sprintf("%s-%d-本文 🗒️\n? ' \"", id, i)
|
||||||
|
if got, e := read(ctx, id, key); e != nil || got != want {
|
||||||
|
t.Fatal("config isolation/normalization", key, got, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, e := read(ctx, short.UUID, "missing"); e != nil || got != "" {
|
||||||
|
t.Fatal(got, e)
|
||||||
|
}
|
||||||
|
// Two distinct names claiming the same FQDN must not both commit.
|
||||||
|
start, results := make(chan struct{}), make(chan error, 2)
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
go func(i int) {
|
||||||
|
<-start
|
||||||
|
results <- create(ctx, fmt.Sprintf("race-%d", i), "Race", "en", "standalone", "race.example.test", true)
|
||||||
|
}(i)
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
success := 0
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if <-results == nil {
|
||||||
|
success++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if success != 1 {
|
||||||
|
t.Fatal("topology serialization", success)
|
||||||
|
}
|
||||||
|
cancelled, cancel := context.WithCancel(ctx)
|
||||||
|
cancel()
|
||||||
|
if e := create(cancelled, "cancelled", "Canceled", "en", "standalone", "cancelled.example.test", true); !errors.Is(e, context.Canceled) {
|
||||||
|
t.Fatal("create cancellation", e)
|
||||||
|
}
|
||||||
|
if e := update(cancelled, campus.ID, "default", "Canceled", "en", "standalone", "pages.example.test", true); !errors.Is(e, context.Canceled) {
|
||||||
|
t.Fatal("update cancellation", e)
|
||||||
|
}
|
||||||
|
if e := write(cancelled, short.UUID, "cancelled", "private"); !errors.Is(e, context.Canceled) {
|
||||||
|
t.Fatal("config cancellation", e)
|
||||||
|
}
|
||||||
|
if _, e := resolve(cancelled, "pages.example.test"); !errors.Is(e, context.Canceled) {
|
||||||
|
t.Fatal("read cancellation", e)
|
||||||
|
}
|
||||||
|
s.ReadOnly = true
|
||||||
|
if e := create(ctx, "readonly", "Readonly", "en", "standalone", "readonly.example.test", true); !errors.Is(e, ErrReadOnly) {
|
||||||
|
t.Fatal("readonly create", e)
|
||||||
|
}
|
||||||
|
if e := update(ctx, campus.ID, "default", "Readonly", "en", "standalone", "pages.example.test", true); !errors.Is(e, ErrReadOnly) {
|
||||||
|
t.Fatal("readonly update", e)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLNamespaceBoundaryAndRollback(t *testing.T) {
|
||||||
|
s := testNamespaceCoreStore(t, storeMySQL)
|
||||||
|
r := &MySQLNamespaceRepository{store: s}
|
||||||
|
ctx := context.Background()
|
||||||
|
domain, e := s.GetDefaultDomain()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
for _, bad := range []string{domain.UUID + " ", strings.ToUpper(domain.UUID), "invalid"} {
|
||||||
|
if e := r.SetConfig(ctx, bad, "key", "secret"); e == nil {
|
||||||
|
t.Fatal("noncanonical UUID", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e := r.SetConfig(ctx, uuid.NewString(), "key", "secret"); !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
t.Fatal("orphan config", e)
|
||||||
|
}
|
||||||
|
if e := r.SetConfig(ctx, domain.UUID, machineLearningConfigKey, "{}"); e == nil {
|
||||||
|
t.Fatal("CAS bypass")
|
||||||
|
}
|
||||||
|
if e := r.SetConfig(ctx, domain.UUID, strings.Repeat("k", 256), "secret"); e == nil {
|
||||||
|
t.Fatal("oversize key")
|
||||||
|
}
|
||||||
|
campus, e := s.GetDefaultCampus()
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.UpdateCampus(ctx, campus.ID, "default", "Inherited", "en", " MANAGED ", "controller.example.test", true); e == nil {
|
||||||
|
t.Fatal("enrollment bypassed by update")
|
||||||
|
}
|
||||||
|
for _, unsupported := range []func() error{
|
||||||
|
s.EnsureDomainsSchema, s.EnsureCampusesSchema, s.EnsureConfigTable,
|
||||||
|
func() error { return s.DeleteDomain(domain.ID) },
|
||||||
|
func() error { return s.DeleteCampus(1) },
|
||||||
|
} {
|
||||||
|
if e := unsupported(); !errors.Is(e, ErrBackendFeatureUnavailable) {
|
||||||
|
t.Fatal("unported operation not refused", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e := s.CreateDomain(domain.CampusUUID, "no-auth-schema", "No auth schema", "no-auth", "local", "", "", true); e == nil {
|
||||||
|
t.Fatal("Domain created without auth dependencies")
|
||||||
|
}
|
||||||
|
if _, e := s.GetDomainByHost("no-auth.localhost"); !errors.Is(e, sql.ErrNoRows) {
|
||||||
|
t.Fatal("partial Domain remains", e)
|
||||||
|
}
|
||||||
|
if e := r.CreateCampus(ctx, "default", "private-title", "en", "standalone", "private-host.example.test", true); e == nil || strings.Contains(e.Error(), "private") || strings.Contains(e.Error(), "Duplicate") {
|
||||||
|
t.Fatal("unsafe error", e)
|
||||||
|
}
|
||||||
|
// Reserve the topology lock, mutate, then abort. Neither changes nor lock
|
||||||
|
// survive rollback. This verifies the lock is transactional, not session-only.
|
||||||
|
e = s.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error {
|
||||||
|
if _, e := tx.ExecContext(ctx, `UPDATE domains SET title='must rollback' WHERE uuid=?`, domain.UUID); e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
return ErrReadOnly
|
||||||
|
})
|
||||||
|
if !errors.Is(e, ErrReadOnly) {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
got, e := s.GetDomainByUUID(domain.UUID)
|
||||||
|
if e != nil || got.Title != domain.Title {
|
||||||
|
t.Fatal("rollback failed", got, e)
|
||||||
|
}
|
||||||
|
deadline, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if e := r.CreateCampus(deadline, "after-rollback", "Works", "en", "standalone", "after.example.test", true); e != nil {
|
||||||
|
t.Fatal("retained lock", e)
|
||||||
|
}
|
||||||
|
s.ReadOnly = true
|
||||||
|
if e := r.SetConfig(ctx, domain.UUID, "readonly", "secret"); !errors.Is(e, ErrReadOnly) {
|
||||||
|
t.Fatal("readonly config", e)
|
||||||
|
}
|
||||||
|
s.ReadOnly = false
|
||||||
|
if _, e := s.DB.Exec(`ALTER TABLE campuses DROP INDEX name`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := r.InspectSchema(ctx); e == nil {
|
||||||
|
t.Fatal("missing unique index accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLNamespaceLockDeadline(t *testing.T) {
|
||||||
|
s := testNamespaceCoreStore(t, storeMySQL)
|
||||||
|
r := &MySQLNamespaceRepository{store: s}
|
||||||
|
ctx := context.Background()
|
||||||
|
tx, e := s.DB.BeginTx(ctx, nil)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, e := tx.ExecContext(ctx, `UPDATE namespace_write_lock SET id=id WHERE id=1`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
deadline, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
if e := r.CreateCampus(deadline, "timeout", "Private", "en", "standalone", "timeout.example.test", true); !errors.Is(e, context.DeadlineExceeded) {
|
||||||
|
t.Fatal("lock ignored deadline", e)
|
||||||
|
}
|
||||||
|
if e := tx.Rollback(); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
deadline2, cancel2 := context.WithTimeout(ctx, 3*time.Second)
|
||||||
|
defer cancel2()
|
||||||
|
if e := r.CreateCampus(deadline2, "timeout", "Works", "en", "standalone", "timeout.example.test", true); e != nil {
|
||||||
|
t.Fatal("canceled transaction retained lock/data", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLNamespaceSchemaResume(t *testing.T) {
|
||||||
|
s, _ := mlTestStore(t, storeMySQL)
|
||||||
|
ctx := context.Background()
|
||||||
|
r := &MySQLNamespaceRepository{store: s}
|
||||||
|
if e := r.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if _, e := s.DB.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=1 WHERE component='store-namespaces'`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.PrepareSchema(ctx); !errors.Is(e, db.ErrMySQLMigrationDirty) {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.ResumeSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMySQLConfigVersionOneUpgrade(t *testing.T) {
|
||||||
|
database := mysqlTestDatabase(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
steps := mysqlMLMigrations()
|
||||||
|
if e := db.ApplyMySQLMigrations(ctx, database, "machine-learning", steps[:1]); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
domain := uuid.NewString()
|
||||||
|
if _, e := database.Exec("INSERT INTO config(domain_uuid,`key`,value,updated_at) VALUES(?,'Existing','本文 📝',123)", domain); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
var originalHash string
|
||||||
|
if e := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='machine-learning' AND version=1`).Scan(&originalHash); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
r := NewMySQLNamespaceRepository(database)
|
||||||
|
status, e := r.InspectSchema(ctx)
|
||||||
|
if e != nil || status.Pending != 2 || status.Applied != 1 {
|
||||||
|
t.Fatal(status, e)
|
||||||
|
}
|
||||||
|
if e := r.PrepareSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
var value, hash string
|
||||||
|
if e := database.QueryRow("SELECT value FROM config WHERE domain_uuid=? AND `key`='Existing'", domain).Scan(&value); e != nil || value != "本文 📝" {
|
||||||
|
t.Fatal("data lost", value, e)
|
||||||
|
}
|
||||||
|
if e := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='machine-learning' AND version=1`).Scan(&hash); e != nil || hash != originalHash {
|
||||||
|
t.Fatal("v1 history changed", e)
|
||||||
|
}
|
||||||
|
// Simulate ALTER committed before its acknowledgement; the v2 resume
|
||||||
|
// checks the new collation and must not re-adopt or destroy config data.
|
||||||
|
if _, e := database.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=0 WHERE component='machine-learning' AND version=2`); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.ResumeSchema(ctx); e == nil {
|
||||||
|
t.Fatal("dirty prerequisite ignored")
|
||||||
|
}
|
||||||
|
status, e = r.InspectSchema(ctx)
|
||||||
|
if e != nil || !status.Dirty || status.DirtyComponent != "machine-learning" {
|
||||||
|
t.Fatal(status, e)
|
||||||
|
}
|
||||||
|
if e := NewMySQLMLRepository(database).ResumeSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
if e := r.ResumeSchema(ctx); e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
// Each pooled connection must refuse truncation, even if the server's
|
||||||
|
// global defaults are permissive. Hold both open to force two connections.
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
connection, e := database.Conn(ctx)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal(e)
|
||||||
|
}
|
||||||
|
defer connection.Close()
|
||||||
|
var mode string
|
||||||
|
if e := connection.QueryRowContext(ctx, `SELECT @@SESSION.sql_mode`).Scan(&mode); e != nil || !strings.Contains(mode, "STRICT_ALL_TABLES") {
|
||||||
|
t.Fatal("strict mode not set", e)
|
||||||
|
}
|
||||||
|
if _, e := connection.ExecContext(ctx, "INSERT INTO config(domain_uuid,`key`,value,updated_at) VALUES(?,?,?,0)", domain, strings.Repeat("k", 256), "must not truncate"); e == nil {
|
||||||
|
t.Fatal("silently truncated oversized key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,7 +21,9 @@ func InspectSchema(ctx context.Context, database *sql.DB) (SchemaInspection, err
|
|||||||
plans[name] = steps
|
plans[name] = steps
|
||||||
}
|
}
|
||||||
plans["document-store"] = documentBackfillMigrations
|
plans["document-store"] = documentBackfillMigrations
|
||||||
components, err := db.InspectSQLiteMigrations(ctx, database, plans)
|
components, err := db.InspectSQLiteMigrationsWithOptional(ctx, database, plans, map[string][]string{
|
||||||
|
"machine-learning-budget": {"ml_daily_budget", "ml_budget_receipts"},
|
||||||
|
})
|
||||||
return SchemaInspection{Coverage: "managed-components-only", Components: components, LegacyAreas: []string{
|
return SchemaInspection{Coverage: "managed-components-only", Components: components, LegacyAreas: []string{
|
||||||
"core-bootstrap", "campuses/domains/federation", "auth/ACL/user-space", "outbox/notifications/publication-approval",
|
"core-bootstrap", "campuses/domains/federation", "auth/ACL/user-space", "outbox/notifications/publication-approval",
|
||||||
"City", "tasks/calendars", "periodicals", "search/object-listing/assets/GC",
|
"City", "tasks/calendars", "periodicals", "search/object-listing/assets/GC",
|
||||||
|
|||||||
@@ -7,6 +7,46 @@ import (
|
|||||||
"pageswiki/internal/db"
|
"pageswiki/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestSchemaInspectionOptionalMLBudget(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
for _, mode := range []string{"absent", "partial", "installed", "missing-tables"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
s := newSchemaTestStore(t)
|
||||||
|
if mode == "partial" {
|
||||||
|
if _, err := s.DB.Exec(mlBudgetStatements[0]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else if mode != "absent" {
|
||||||
|
if err := s.EnsureMLBudgetSchema(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if mode == "missing-tables" {
|
||||||
|
if _, err := s.DB.Exec(`DROP TABLE ml_daily_budget; DROP TABLE ml_budget_receipts`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report, err := InspectSchema(ctx, s.DB)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, component := range report.Components {
|
||||||
|
if component.Component != "machine-learning-budget" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
found = true
|
||||||
|
if (component.State == "current") != (mode == "installed") {
|
||||||
|
t.Fatalf("%s: %+v", mode, component)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if found != (mode != "absent") {
|
||||||
|
t.Fatalf("optional component visibility: %s %v", mode, found)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestSchemaInspectionDoesNotRecoverJobsOrBackfill(t *testing.T) {
|
func TestSchemaInspectionDoesNotRecoverJobsOrBackfill(t *testing.T) {
|
||||||
st := newSchemaTestStore(t)
|
st := newSchemaTestStore(t)
|
||||||
for name := range managedStoreSchemas {
|
for name := range managedStoreSchemas {
|
||||||
|
|||||||
@@ -12,12 +12,13 @@ import (
|
|||||||
// Once released, add a new version; never edit an applied definition.
|
// Once released, add a new version; never edit an applied definition.
|
||||||
// Auth, City, tasks and calendars remain in their existing migration paths.
|
// Auth, City, tasks and calendars remain in their existing migration paths.
|
||||||
var managedStoreSchemas = map[string][]db.SQLMigration{
|
var managedStoreSchemas = map[string][]db.SQLMigration{
|
||||||
"feeds": feedMigrations,
|
"machine-learning-budget": mlBudgetMigrations,
|
||||||
"contacts": contactMigrations,
|
"feeds": feedMigrations,
|
||||||
"task-productivity": taskProductivityMigrations,
|
"contacts": contactMigrations,
|
||||||
"cli-auth": cliAuthMigrations,
|
"task-productivity": taskProductivityMigrations,
|
||||||
"profile-contacts": profileContactMigrations,
|
"cli-auth": cliAuthMigrations,
|
||||||
"event-jobs": eventJobMigrations,
|
"profile-contacts": profileContactMigrations,
|
||||||
|
"event-jobs": eventJobMigrations,
|
||||||
"projection-metadata": {{Version: 1, Name: "adopt_projection_metadata", Statements: []string{
|
"projection-metadata": {{Version: 1, Name: "adopt_projection_metadata", Statements: []string{
|
||||||
`CREATE TABLE IF NOT EXISTS projection_metadata (
|
`CREATE TABLE IF NOT EXISTS projection_metadata (
|
||||||
document_hash TEXT NOT NULL,kind TEXT NOT NULL,version INTEGER NOT NULL,
|
document_hash TEXT NOT NULL,kind TEXT NOT NULL,version INTEGER NOT NULL,
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ type storeSQLBackend uint8
|
|||||||
const (
|
const (
|
||||||
storeSQLite storeSQLBackend = iota
|
storeSQLite storeSQLBackend = iota
|
||||||
storePostgreSQL
|
storePostgreSQL
|
||||||
|
// Restricted to ported component facades; never used for serving Pages.
|
||||||
|
storeMySQL
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrPostgreSQLComponentNotReady = errors.New("PostgreSQL component dependencies are not ported")
|
var ErrPostgreSQLComponentNotReady = errors.New("PostgreSQL component dependencies are not ported")
|
||||||
@@ -41,6 +43,26 @@ func (s *Store) sqlValues(n int) string {
|
|||||||
}
|
}
|
||||||
return strings.Join(parts, ",")
|
return strings.Join(parts, ",")
|
||||||
}
|
}
|
||||||
|
func (s *Store) sqlConfigKey() string {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return "`key`"
|
||||||
|
}
|
||||||
|
return "key"
|
||||||
|
}
|
||||||
|
func (s *Store) sqlGroupTable() string {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return "`groups`"
|
||||||
|
}
|
||||||
|
return "groups"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Owned identifiers only. This is a statement suffix, not SQL rewriting.
|
||||||
|
func (s *Store) sqlConflictDoNothing(table, primary, conflict string) string {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return " ON DUPLICATE KEY UPDATE `" + primary + "`=`" + table + "`.`" + primary + "`"
|
||||||
|
}
|
||||||
|
return " ON CONFLICT(" + conflict + ") DO NOTHING"
|
||||||
|
}
|
||||||
func (s *Store) sqlHasDot(expression string) string {
|
func (s *Store) sqlHasDot(expression string) string {
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend == storePostgreSQL {
|
||||||
return "strpos(" + expression + ", '.') > 0"
|
return "strpos(" + expression + ", '.') > 0"
|
||||||
@@ -48,6 +70,15 @@ func (s *Store) sqlHasDot(expression string) string {
|
|||||||
return "instr(" + expression + ", '.') > 0"
|
return "instr(" + expression + ", '.') > 0"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only owned SQL expressions, never user input. MySQL's || is logical OR
|
||||||
|
// without a special sql_mode; do not change session modes to emulate SQLite.
|
||||||
|
func (s *Store) sqlConcat(expressions ...string) string {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return "CONCAT(" + strings.Join(expressions, ",") + ")"
|
||||||
|
}
|
||||||
|
return strings.Join(expressions, " || ")
|
||||||
|
}
|
||||||
|
|
||||||
// Owned expressions only. C/BINARY ordering makes '%' and '_' literal and
|
// Owned expressions only. C/BINARY ordering makes '%' and '_' literal and
|
||||||
// keeps segment ranges case-sensitive, independent of database locale.
|
// keeps segment ranges case-sensitive, independent of database locale.
|
||||||
func (s *Store) pathScopeSQL(parent, child string) string {
|
func (s *Store) pathScopeSQL(parent, child string) string {
|
||||||
@@ -70,6 +101,9 @@ func (s *Store) sqlStringPosition(expression, literal string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) sqlError(operation string, err error) error {
|
func (s *Store) sqlError(operation string, err error) error {
|
||||||
|
if s.sqlBackend == storeMySQL {
|
||||||
|
return mysqlStoreError(operation, err)
|
||||||
|
}
|
||||||
if s.sqlBackend != storePostgreSQL || err == nil {
|
if s.sqlBackend != storePostgreSQL || err == nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -143,6 +177,10 @@ func (s *Store) administrativeWrite(ctx context.Context, sqliteReservation strin
|
|||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
if s.sqlBackend == storePostgreSQL {
|
if s.sqlBackend == storePostgreSQL {
|
||||||
_, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1853058931)`)
|
_, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1853058931)`)
|
||||||
|
} else if s.sqlBackend == storeMySQL {
|
||||||
|
// A real row lock, held until commit/rollback. A WHERE 0 update does
|
||||||
|
// not reserve a writer on InnoDB. Insert also covers first-use races.
|
||||||
|
_, err = tx.ExecContext(ctx, `INSERT INTO namespace_write_lock(id) VALUES(1) ON DUPLICATE KEY UPDATE id=1`)
|
||||||
} else {
|
} else {
|
||||||
_, err = tx.ExecContext(ctx, sqliteReservation)
|
_, err = tx.ExecContext(ctx, sqliteReservation)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="535pt" height="128pt" viewBox="0 0 535 128" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">URL hierarchy as districts, streets and places: conceptual navigation</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<rect x="0" y="0" width="535" height="127" rx="2" fill="#ffffff" stroke="#244d70" stroke-width="0.6"/>
|
||||||
|
<text x="12" y="17" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="10" font-weight="700" text-anchor="start" fill="#172433">wiki.example.test</text>
|
||||||
|
<text x="523" y="17" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="400" text-anchor="end" fill="#526171">One domain / one city</text>
|
||||||
|
<rect x="12" y="29" width="161" height="86" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="21" y="44" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="9" font-weight="700" text-anchor="start" fill="#172433">Research</text>
|
||||||
|
<text x="164" y="44" font-family="DejaVu Sans Mono,monospace" font-size="7.2" font-weight="400" text-anchor="end" fill="#172433">/lab</text>
|
||||||
|
<line x1="22" y1="62" x2="163" y2="62" stroke="#b6c2cd" stroke-width="0.65"/>
|
||||||
|
<text x="21" y="57" font-family="DejaVu Sans Mono,monospace" font-size="7.1" font-weight="400" text-anchor="start" fill="#172433">/lab/web</text>
|
||||||
|
<line x1="38" y1="62" x2="38" y2="78" stroke="#244d70" stroke-width="0.65"/>
|
||||||
|
<rect x="23" y="79" width="139" height="25" rx="2" fill="#ffffff" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="92.5" y="95" font-family="DejaVu Sans Mono,monospace" font-size="7" font-weight="400" text-anchor="middle" fill="#172433">/lab/web/api</text>
|
||||||
|
<rect x="187" y="29" width="161" height="86" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="196" y="44" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="9" font-weight="700" text-anchor="start" fill="#172433">Operations</text>
|
||||||
|
<text x="339" y="44" font-family="DejaVu Sans Mono,monospace" font-size="7.2" font-weight="400" text-anchor="end" fill="#172433">/ops</text>
|
||||||
|
<line x1="197" y1="62" x2="338" y2="62" stroke="#b6c2cd" stroke-width="0.65"/>
|
||||||
|
<text x="196" y="57" font-family="DejaVu Sans Mono,monospace" font-size="7.1" font-weight="400" text-anchor="start" fill="#172433">/ops/network</text>
|
||||||
|
<line x1="213" y1="62" x2="213" y2="78" stroke="#244d70" stroke-width="0.65"/>
|
||||||
|
<rect x="198" y="79" width="139" height="25" rx="2" fill="#ffffff" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="267.5" y="95" font-family="DejaVu Sans Mono,monospace" font-size="7" font-weight="400" text-anchor="middle" fill="#172433">/ops/network/dns</text>
|
||||||
|
<rect x="362" y="29" width="161" height="86" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="371" y="44" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="9" font-weight="700" text-anchor="start" fill="#172433">Projects</text>
|
||||||
|
<text x="514" y="44" font-family="DejaVu Sans Mono,monospace" font-size="7.2" font-weight="400" text-anchor="end" fill="#172433">/projects</text>
|
||||||
|
<line x1="372" y1="62" x2="513" y2="62" stroke="#b6c2cd" stroke-width="0.65"/>
|
||||||
|
<text x="371" y="57" font-family="DejaVu Sans Mono,monospace" font-size="7.1" font-weight="400" text-anchor="start" fill="#172433">/projects/wiki</text>
|
||||||
|
<line x1="388" y1="62" x2="388" y2="78" stroke="#244d70" stroke-width="0.65"/>
|
||||||
|
<rect x="373" y="79" width="139" height="25" rx="2" fill="#ffffff" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="442.5" y="95" font-family="DejaVu Sans Mono,monospace" font-size="7" font-weight="400" text-anchor="middle" fill="#172433">/projects/wiki/editor</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.6 KiB |
@@ -0,0 +1,18 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="252pt" height="79pt" viewBox="0 0 252 79" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">Two navigation paths open the same page</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<rect x="0" y="0" width="83" height="26" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="41.5" y="17" font-family="DejaVu Sans Mono,monospace" font-size="8" font-weight="400" text-anchor="middle" fill="#172433">/guide/api</text>
|
||||||
|
<rect x="0" y="35" width="83" height="26" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="41.5" y="52" font-family="DejaVu Sans Mono,monospace" font-size="8" font-weight="400" text-anchor="middle" fill="#172433">/project/ref</text>
|
||||||
|
<rect x="119" y="10" width="133" height="42" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="185.5" y="28" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="10" font-weight="700" text-anchor="middle" fill="#172433">One page</text>
|
||||||
|
<text x="185.5" y="43" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">Shared content / history</text>
|
||||||
|
<line x1="83" y1="13" x2="119" y2="22" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="119" y1="22" x2="115.0837734367601" y2="22.814352199833827" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="119" y1="22" x2="115.92773053823953" y2="19.43852379391608" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="83" y1="48" x2="119" y2="40" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="119" y1="40" x2="115.86140985101306" y2="42.47976851272093" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="119" y1="40" x2="115.10655167141239" y2="39.08290670451785" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<text x="0" y="76" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.4" font-weight="400" text-anchor="start" fill="#526171">Multiple paths, no document copies</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.9 KiB |
@@ -0,0 +1,20 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="252pt" height="79pt" viewBox="0 0 252 79" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">Email and RSS connect to Wiki, tasks and work records</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<rect x="0" y="16" width="72" height="37" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="36" y="31" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="middle" fill="#172433">Mail / RSS</text>
|
||||||
|
<text x="36" y="44" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">capture</text>
|
||||||
|
<rect x="90" y="16" width="72" height="37" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="126" y="31" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="middle" fill="#172433">Wiki + task</text>
|
||||||
|
<text x="126" y="44" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">link</text>
|
||||||
|
<rect x="180" y="16" width="72" height="37" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="216" y="31" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="middle" fill="#172433">Work log</text>
|
||||||
|
<text x="216" y="44" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">report</text>
|
||||||
|
<line x1="72" y1="34" x2="90" y2="34" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="90" y1="34" x2="86.3982115905893" y2="35.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="90" y1="34" x2="86.3982115905893" y2="32.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="162" y1="34" x2="180" y2="34" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="180" y1="34" x2="176.39821159058928" y2="35.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="180" y1="34" x2="176.39821159058928" y2="32.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<text x="0" y="74" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="start" fill="#526171">NeoMutt / pages-cli / Web dashboard</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.2 KiB |
@@ -0,0 +1,19 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="252pt" height="92pt" viewBox="0 0 252 92" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">Campus manages domains independently of application instances</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<rect x="0" y="0" width="252" height="23" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="126" y="15" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8.4" font-weight="700" text-anchor="middle" fill="#172433">Campus / configuration controller</text>
|
||||||
|
<line x1="60" y1="23" x2="60" y2="42" stroke="#526171" stroke-width="0.65" stroke-dasharray="2 2"/>
|
||||||
|
<line x1="60" y1="42" x2="58.26013786355508" y2="38.39821159058929" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="60" y1="42" x2="61.73986213644492" y2="38.39821159058929" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="192" y1="23" x2="192" y2="42" stroke="#526171" stroke-width="0.65" stroke-dasharray="2 2"/>
|
||||||
|
<line x1="192" y1="42" x2="190.2601378635551" y2="38.39821159058929" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="192" y1="42" x2="193.7398621364449" y2="38.39821159058929" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<rect x="0" y="42" width="120" height="49" rx="2" fill="#ffffff" stroke="#244d70" stroke-width="0.6"/>
|
||||||
|
<text x="7" y="55" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8.3" font-weight="700" text-anchor="start" fill="#172433">Instance A</text>
|
||||||
|
<text x="7" y="69" font-family="DejaVu Sans Mono,monospace" font-size="7" font-weight="400" text-anchor="start" fill="#172433">wiki.example.test</text>
|
||||||
|
<text x="7" y="82" font-family="DejaVu Sans Mono,monospace" font-size="7" font-weight="400" text-anchor="start" fill="#172433">lab.example.test</text>
|
||||||
|
<rect x="132" y="42" width="120" height="49" rx="2" fill="#ffffff" stroke="#244d70" stroke-width="0.6"/>
|
||||||
|
<text x="139" y="55" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8.3" font-weight="700" text-anchor="start" fill="#172433">Instance B</text>
|
||||||
|
<text x="139" y="69" font-family="DejaVu Sans Mono,monospace" font-size="7" font-weight="400" text-anchor="start" fill="#172433">team.example.test</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.1 KiB |
@@ -0,0 +1,30 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="252pt" height="92pt" viewBox="0 0 252 92" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">HTML and Markdown editing, conversion and preview</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<rect x="0" y="11" width="76" height="35" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="38.0" y="25" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="9" font-weight="700" text-anchor="middle" fill="#172433">Markdown</text>
|
||||||
|
<text x="38.0" y="38" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">editing</text>
|
||||||
|
<rect x="102" y="11" width="64" height="35" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="134.0" y="25" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="9" font-weight="700" text-anchor="middle" fill="#172433">HTML</text>
|
||||||
|
<text x="134.0" y="38" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">stored content</text>
|
||||||
|
<line x1="76" y1="22" x2="102" y2="22" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="102" y1="22" x2="98.3982115905893" y2="23.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="102" y1="22" x2="98.3982115905893" y2="20.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="102" y1="35" x2="76" y2="35" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="76" y1="35" x2="79.6017884094107" y2="33.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="76" y1="35" x2="79.6017884094107" y2="36.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<text x="87" y="7" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="6.4" font-weight="400" text-anchor="middle" fill="#526171">convert</text>
|
||||||
|
<rect x="192" y="11" width="60" height="35" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="222" y="25" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8.6" font-weight="700" text-anchor="middle" fill="#172433">Viewer</text>
|
||||||
|
<text x="222" y="38" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">Preview</text>
|
||||||
|
<line x1="166" y1="29" x2="192" y2="29" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="192" y1="29" x2="188.39821159058928" y2="30.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="192" y1="29" x2="188.39821159058928" y2="27.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="134" y1="46" x2="134" y2="64" stroke="#b6c2cd" stroke-width="0.65"/>
|
||||||
|
<line x1="134" y1="64" x2="222" y2="64" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="222" y1="64" x2="218.39821159058928" y2="65.73986213644493" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="222" y1="64" x2="218.39821159058928" y2="62.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<text x="0" y="83" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="start" fill="#526171">HTML fragments retained in Markdown</text>
|
||||||
|
<text x="222" y="76" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.7" font-weight="700" text-anchor="middle" fill="#172433">Slides</text>
|
||||||
|
<text x="222" y="89" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">Reveal.js</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.4 KiB |
@@ -0,0 +1,31 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="252pt" height="79pt" viewBox="0 0 252 79" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">Paths resolve to a stable Page, immutable revisions and content hashes</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<rect x="0" y="0" width="66" height="24" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="33" y="15" font-family="DejaVu Sans Mono,monospace" font-size="7" font-weight="400" text-anchor="middle" fill="#172433">/guide/api</text>
|
||||||
|
<rect x="0" y="33" width="66" height="24" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="33" y="48" font-family="DejaVu Sans Mono,monospace" font-size="7" font-weight="400" text-anchor="middle" fill="#172433">/project/ref</text>
|
||||||
|
<rect x="83" y="15" width="49" height="29" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="107.5" y="27" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="middle" fill="#172433">Page</text>
|
||||||
|
<text x="107.5" y="38" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="middle" fill="#526171">UUID</text>
|
||||||
|
<line x1="66" y1="12" x2="83" y2="24" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="83" y1="24" x2="79.05410535900606" y2="23.34432059497393" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="83" y1="24" x2="81.06080387945784" y2="20.501497691000587" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="66" y1="45" x2="83" y2="35" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="83" y1="35" x2="80.77764045479339" y2="38.32582592025336" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="83" y1="35" x2="79.01335021354707" y2="35.32653251013461" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<rect x="147" y="15" width="47" height="29" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="170.5" y="27" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="700" text-anchor="middle" fill="#172433">Revision</text>
|
||||||
|
<text x="170.5" y="38" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="6.2" font-weight="400" text-anchor="middle" fill="#526171">UUID / lang</text>
|
||||||
|
<line x1="132" y1="29" x2="147" y2="29" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="147" y1="29" x2="143.39821159058928" y2="30.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="147" y1="29" x2="143.39821159058928" y2="27.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<rect x="209" y="15" width="43" height="29" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="230.5" y="27" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="6.4" font-weight="700" text-anchor="middle" fill="#172433">Document</text>
|
||||||
|
<text x="230.5" y="38" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="6.6" font-weight="400" text-anchor="middle" fill="#526171">SHA-256</text>
|
||||||
|
<line x1="194" y1="29" x2="209" y2="29" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="209" y1="29" x2="205.39821159058928" y2="30.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="209" y1="29" x2="205.39821159058928" y2="27.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<text x="0" y="74" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#526171">mutable address</text>
|
||||||
|
<text x="83" y="74" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#526171">stable identity / immutable history</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.5 KiB |
@@ -0,0 +1,43 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="535pt" height="144pt" viewBox="0 0 535 144" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">Desktop information density and mobile touch layout: conceptual wireframes</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<rect x="0" y="0" width="350" height="143" rx="2" fill="#ffffff" stroke="#244d70" stroke-width="0.6"/>
|
||||||
|
<rect x="0" y="0" width="350" height="24" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="8" y="16" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="9" font-weight="700" text-anchor="start" fill="#172433">Pages</text>
|
||||||
|
<rect x="54" y="5" width="140" height="14" rx="2" fill="#ffffff" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="61" y="15" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#526171">Search / command</text>
|
||||||
|
<text x="341" y="15" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="end" fill="#172433">Plan Inbox Theme User</text>
|
||||||
|
<rect x="7" y="31" width="70" height="104" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="13" y="44" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="start" fill="#172433">Projects</text>
|
||||||
|
<text x="14" y="61" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="start" fill="#172433">All tasks</text>
|
||||||
|
<text x="14" y="76" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="start" fill="#172433">Wiki</text>
|
||||||
|
<rect x="11" y="76" width="61" height="16" rx="2" fill="#dce8f0" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="14" y="91" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="start" fill="#172433">Exhibition</text>
|
||||||
|
<text x="14" y="106" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="start" fill="#172433">Personal</text>
|
||||||
|
<text x="87" y="43" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.5" font-weight="700" text-anchor="start" fill="#172433">Status / Subject</text>
|
||||||
|
<text x="340" y="43" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.5" font-weight="700" text-anchor="end" fill="#172433">Due / Wiki</text>
|
||||||
|
<text x="88" y="63" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.4" font-weight="400" text-anchor="start" fill="#172433">Review API design</text>
|
||||||
|
<text x="337" y="63" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="end" fill="#172433">11-15</text>
|
||||||
|
<line x1="83" y1="70" x2="342" y2="70" stroke="#b6c2cd" stroke-width="0.65"/>
|
||||||
|
<rect x="83" y="70" width="259" height="20" rx="2" fill="#dce8f0" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="88" y="83" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.4" font-weight="400" text-anchor="start" fill="#172433">Prepare exhibit</text>
|
||||||
|
<text x="337" y="83" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="end" fill="#172433">11-16</text>
|
||||||
|
<line x1="83" y1="90" x2="342" y2="90" stroke="#b6c2cd" stroke-width="0.65"/>
|
||||||
|
<text x="88" y="103" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.4" font-weight="400" text-anchor="start" fill="#172433">Write deployment notes</text>
|
||||||
|
<text x="337" y="103" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="end" fill="#172433">11-17</text>
|
||||||
|
<line x1="83" y1="110" x2="342" y2="110" stroke="#b6c2cd" stroke-width="0.65"/>
|
||||||
|
<text x="88" y="123" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.4" font-weight="400" text-anchor="start" fill="#172433">Update diagrams</text>
|
||||||
|
<text x="337" y="123" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.2" font-weight="400" text-anchor="end" fill="#172433">11-18</text>
|
||||||
|
<line x1="83" y1="130" x2="342" y2="130" stroke="#b6c2cd" stroke-width="0.65"/>
|
||||||
|
<rect x="374" y="0" width="161" height="143" rx="2" fill="#ffffff" stroke="#244d70" stroke-width="0.6"/>
|
||||||
|
<rect x="374" y="0" width="161" height="24" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="383" y="16" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8.5" font-weight="700" text-anchor="start" fill="#172433">Pages / Tasks</text>
|
||||||
|
<rect x="382" y="32" width="145" height="44" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="389" y="46" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="start" fill="#172433">Review API design</text>
|
||||||
|
<text x="389" y="60" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#526171">In progress / Nov 15</text>
|
||||||
|
<text x="389" y="71" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#172433">Edit Date Wiki</text>
|
||||||
|
<rect x="382" y="84" width="145" height="44" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="389" y="98" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="start" fill="#172433">Prepare exhibit</text>
|
||||||
|
<text x="389" y="112" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#526171">To do / Nov 16</text>
|
||||||
|
<text x="389" y="123" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#172433">Edit Date Wiki</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 5.6 KiB |
@@ -0,0 +1,25 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="535pt" height="70pt" viewBox="0 0 535 70" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">Same layout with light, dark and wallpaper-derived colors; illustrative palettes</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<rect x="0" y="0" width="163" height="69" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="8" y="14" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.5" font-weight="700" text-anchor="start" fill="#172433">LIGHT</text>
|
||||||
|
<rect x="8" y="22" width="147" height="15" rx="2" fill="#dce8f0" stroke="#dce8f0" stroke-width="0.6"/>
|
||||||
|
<text x="14" y="32" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#172433">Search / command</text>
|
||||||
|
<line x1="8" y1="45" x2="155" y2="45" stroke="#172433" stroke-width="0.65"/>
|
||||||
|
<line x1="8" y1="54" x2="109" y2="54" stroke="#172433" stroke-width="0.65"/>
|
||||||
|
<text x="8" y="64" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="6.6" font-weight="400" text-anchor="start" fill="#172433">Same controls / layout</text>
|
||||||
|
<rect x="186" y="0" width="163" height="69" rx="2" fill="#26303d" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="194" y="14" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.5" font-weight="700" text-anchor="start" fill="#e3eaf1">DARK</text>
|
||||||
|
<rect x="194" y="22" width="147" height="15" rx="2" fill="#405569" stroke="#405569" stroke-width="0.6"/>
|
||||||
|
<text x="200" y="32" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#e3eaf1">Search / command</text>
|
||||||
|
<line x1="194" y1="45" x2="341" y2="45" stroke="#e3eaf1" stroke-width="0.65"/>
|
||||||
|
<line x1="194" y1="54" x2="295" y2="54" stroke="#e3eaf1" stroke-width="0.65"/>
|
||||||
|
<text x="194" y="64" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="6.6" font-weight="400" text-anchor="start" fill="#e3eaf1">Same controls / layout</text>
|
||||||
|
<rect x="372" y="0" width="163" height="69" rx="2" fill="#f0ebe5" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="380" y="14" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7.5" font-weight="700" text-anchor="start" fill="#42392e">WALLPAPER COLOR</text>
|
||||||
|
<rect x="380" y="22" width="147" height="15" rx="2" fill="#d3c2ac" stroke="#d3c2ac" stroke-width="0.6"/>
|
||||||
|
<text x="386" y="32" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#42392e">Search / command</text>
|
||||||
|
<line x1="380" y1="45" x2="527" y2="45" stroke="#42392e" stroke-width="0.65"/>
|
||||||
|
<line x1="380" y1="54" x2="481" y2="54" stroke="#42392e" stroke-width="0.65"/>
|
||||||
|
<text x="380" y="64" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="6.6" font-weight="400" text-anchor="start" fill="#42392e">Same controls / layout</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.8 KiB |
@@ -0,0 +1,29 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="252pt" height="79pt" viewBox="0 0 252 79" role="img" aria-labelledby="title">
|
||||||
|
<title id="title">Campus and Domain organize Quartier, Street, Spot and Pages</title>
|
||||||
|
<rect width="100%" height="100%" fill="white"/>
|
||||||
|
<text x="0" y="9" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8.5" font-weight="700" text-anchor="start" fill="#172433">Campus</text>
|
||||||
|
<line x1="45" y1="6" x2="60" y2="6" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="60" y1="6" x2="56.39821159058929" y2="7.739862136444921" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="60" y1="6" x2="56.39821159058929" y2="4.260137863555079" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<text x="65" y="9" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8.2" font-weight="700" text-anchor="start" fill="#172433">Domain = FQDN / namespace</text>
|
||||||
|
<rect x="0" y="24" width="72" height="32" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="36.0" y="37" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="middle" fill="#172433">Quartier</text>
|
||||||
|
<text x="36.0" y="49" font-family="DejaVu Sans Mono,monospace" font-size="6.6" font-weight="400" text-anchor="middle" fill="#526171">/lab</text>
|
||||||
|
<rect x="90" y="24" width="72" height="32" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="126.0" y="37" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="middle" fill="#172433">Street</text>
|
||||||
|
<text x="126.0" y="49" font-family="DejaVu Sans Mono,monospace" font-size="6.6" font-weight="400" text-anchor="middle" fill="#526171">/lab/web</text>
|
||||||
|
<rect x="180" y="24" width="72" height="32" rx="2" fill="#f1f5f8" stroke="#b6c2cd" stroke-width="0.6"/>
|
||||||
|
<text x="216.0" y="37" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="middle" fill="#172433">Spot</text>
|
||||||
|
<text x="216.0" y="49" font-family="DejaVu Sans Mono,monospace" font-size="6.6" font-weight="400" text-anchor="middle" fill="#526171">/lab/web/api</text>
|
||||||
|
<line x1="72" y1="40" x2="90" y2="40" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="90" y1="40" x2="86.3982115905893" y2="41.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="90" y1="40" x2="86.3982115905893" y2="38.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="162" y1="40" x2="180" y2="40" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="180" y1="40" x2="176.39821159058928" y2="41.73986213644492" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="180" y1="40" x2="176.39821159058928" y2="38.26013786355508" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="216" y1="56" x2="216" y2="66" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="216" y1="66" x2="214.2601378635551" y2="62.39821159058929" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<line x1="216" y1="66" x2="217.7398621364449" y2="62.39821159058929" stroke="#526171" stroke-width="0.65"/>
|
||||||
|
<text x="216" y="77" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="8" font-weight="700" text-anchor="middle" fill="#172433">Pages</text>
|
||||||
|
<text x="0" y="76" font-family="DejaVu Sans,Noto Sans CJK JP,sans-serif" font-size="7" font-weight="400" text-anchor="start" fill="#526171">path boundaries / map navigation</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 3.3 KiB |