Implement Knowledge City platform, organizer and DAV integration

Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
This commit is contained in:
Anya Tokugawa committed 2026-09-27 14:44:43 +09:00
1 parent 288e6e94ac
commit c1175d389f
699 files changed
+110197 -4117

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
package middleware
import (
"context"
"log"
"net/http"
"strings"
"time"
)
type davDiagnosticKey struct{}
type davDiagnostic struct{ outcome, target string }
// UUID collections cannot be classified as VEVENT/VTODO from the URL alone.
func SetDAVTaskTarget(r *http.Request, resource bool) {
if d, ok := r.Context().Value(davDiagnosticKey{}).(*davDiagnostic); ok {
d.target = "task_collection"
if resource {
d.target = "task_resource"
}
}
}
// SetDAVAuthOutcome accepts only fixed diagnostic categories, never identities
// or error strings. The value is server-side only, not a response header.
func SetDAVAuthOutcome(r *http.Request, outcome string) {
switch outcome {
case "basic_accepted", "basic_rejected", "session_accepted", "anonymous", "missing", "invalid_authorization", "multiple_authorization":
default:
return
}
if d, ok := r.Context().Value(davDiagnosticKey{}).(*davDiagnostic); ok {
d.outcome = outcome
}
}
func davLogTarget(path string) string {
const root = "/_/api/v1/caldav"
p := strings.TrimSuffix(path, "/")
switch p {
case "/.well-known/caldav":
return "well_known"
case root:
return "home"
case root + "/tasks":
return "task_home"
case root + "/tasks/default":
return "task_collection"
}
if strings.HasPrefix(path, root+"/tasks/default/") {
return "task_resource"
}
if strings.HasPrefix(path, root+"/") {
if strings.Contains(strings.TrimPrefix(p, root+"/"), "/") {
return "calendar_resource"
}
return "calendar_collection"
}
return ""
}
func davAuthScheme(r *http.Request) string {
values := r.Header.Values("Authorization")
if len(values) > 1 {
return "multiple"
}
if len(values) == 0 || values[0] == "" {
return "none"
}
if _, _, ok := r.BasicAuth(); ok {
return "basic"
}
if strings.HasPrefix(strings.ToLower(values[0]), "basic ") {
return "malformed_basic"
}
if strings.HasPrefix(strings.ToLower(values[0]), "bearer ") {
return "bearer"
}
return "other"
}
type davLogWriter struct {
http.ResponseWriter
status int
}
func (w *davLogWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
func (w *davLogWriter) WriteHeader(status int) {
if w.status != 0 {
return
}
if status >= 200 || status == 101 {
w.status = status
}
w.ResponseWriter.WriteHeader(status)
}
func (w *davLogWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(b)
}
// DAV logs replace raw-path access logs: no usernames, credential IDs, resource
// names, query strings, cookies, Authorization values or calendar bodies.
func logDAVRequest(w http.ResponseWriter, r *http.Request, next http.Handler, target string, start time.Time) {
d := &davDiagnostic{outcome: "not_checked"}
r = r.WithContext(context.WithValue(r.Context(), davDiagnosticKey{}, d))
rec := &davLogWriter{ResponseWriter: w}
next.ServeHTTP(rec, r)
if d.target != "" {
target = d.target
}
status := rec.status
if status == 0 {
status = http.StatusOK
}
method := r.Method
switch method {
case "OPTIONS", "PROPFIND", "REPORT", "GET", "HEAD", "PUT", "DELETE", "POST", "MKCALENDAR", "PROPPATCH":
default:
method = "other"
}
log.Printf("caldav request method=%s target=%s status=%d auth=%s outcome=%s challenge=%t compatibility=%t request_id=%q duration=%s",
method, target, status, davAuthScheme(r), d.outcome,
rec.Header().Get("WWW-Authenticate") != "",
rec.Header().Get("X-PagesWiki-CalDAV-Profile") == "limited-compatibility",
rec.Header().Get("X-Request-ID"), time.Since(start))
}
@@ -0,0 +1,105 @@
package middleware
import (
"bytes"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDAVLogging(t *testing.T) {
var output bytes.Buffer
previous := log.Writer()
log.SetOutput(&output)
t.Cleanup(func() { log.SetOutput(previous) })
for _, tc := range []struct {
name, auth, outcome string
status int
}{
{"challenge", "", "missing", 401},
{"accepted", "basic", "basic_accepted", 204},
{"rejected", "basic", "basic_rejected", 401},
{"malformed", "malformed_basic", "invalid_authorization", 401},
{"bearer", "bearer", "session_accepted", 207},
{"multiple", "multiple", "multiple_authorization", 401},
} {
t.Run(tc.name, func(t *testing.T) {
output.Reset()
r := httptest.NewRequest("OPTIONS", "https://example.test/_/api/v1/caldav/private-calendar/private-event.ics?token=private-query", strings.NewReader("private-body"))
switch tc.auth {
case "basic", "multiple":
r.SetBasicAuth("private-username", "private-password")
if tc.auth == "multiple" {
r.Header.Add("Authorization", "Bearer private-token")
}
case "malformed_basic":
r.Header.Set("Authorization", "Basic private-malformed")
case "bearer":
r.Header.Set("Authorization", "Bearer private-token")
}
r.Header.Set("Cookie", "private-cookie")
r.Header.Set("User-Agent", "private-user-agent")
w := httptest.NewRecorder()
Logging(RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
SetDAVAuthOutcome(r, tc.outcome)
SetDAVAuthOutcome(r, "private-injected-outcome") // Not allowlisted.
if tc.status == 401 {
w.Header().Set("WWW-Authenticate", `Basic realm="test"`)
}
if tc.status == 204 {
w.Header().Set("X-PagesWiki-CalDAV-Profile", "limited-compatibility")
}
w.WriteHeader(tc.status)
}))).ServeHTTP(w, r)
line := output.String()
auth := tc.auth
if auth == "" {
auth = "none"
}
for _, wanted := range []string{"caldav request", "target=calendar_resource", "auth=" + auth, "outcome=" + tc.outcome, w.Header().Get("X-Request-ID")} {
if !strings.Contains(line, wanted) {
t.Fatalf("missing %q in %q", wanted, line)
}
}
if strings.Contains(line, "private-") || strings.Contains(line, "/_/api/") || (r.Header.Get("Authorization") != "" && strings.Contains(line, r.Header.Get("Authorization"))) {
t.Fatalf("sensitive metadata in log: %q", line)
}
if w.Code != tc.status {
t.Fatalf("status changed: %d", w.Code)
}
})
}
}
func TestDAVLogTarget(t *testing.T) {
for path, want := range map[string]string{
"/_/api/v1/caldav": "home", "/_/api/v1/caldav/": "home",
"/_/api/v1/caldav/tasks/": "task_home", "/_/api/v1/caldav/tasks/default": "task_collection",
"/_/api/v1/caldav/tasks/default/private.ics": "task_resource",
"/_/api/v1/caldav/private/": "calendar_collection",
"/.well-known/caldav": "well_known",
"/_/api/v1/caldav-credentials": "", "/health": "",
} {
if got := davLogTarget(path); got != want {
t.Errorf("%s: %q != %q", path, got, want)
}
}
}
func TestDAVLogWriterStatus(t *testing.T) {
w := &davLogWriter{ResponseWriter: httptest.NewRecorder()}
w.WriteHeader(103)
if w.status != 0 {
t.Fatal("informational status recorded as final")
}
w.Write([]byte("synthetic"))
w.WriteHeader(500)
if w.status != 200 {
t.Fatal("implicit response or duplicate header changed status", w.status)
}
if w.Unwrap() == nil {
t.Fatal("response controller cannot unwrap")
}
}
+4
View File
@@ -17,6 +17,10 @@ func Logging(
) {
start := time.Now()
if target := davLogTarget(r.URL.Path); target != "" {
logDAVRequest(w, r, next, target, start)
return
}
next.ServeHTTP(w, r)
+7
View File
@@ -16,6 +16,13 @@ func NormalizePath(
) {
p := r.URL.Path
// Hosted adapter assets use directory-relative module and worker URLs.
// DAV collections also require the slash: removing it conflicts with
// ServeMux's collection redirect and causes an infinite redirect loop.
if strings.HasPrefix(p, "/_/adaptor/") || strings.HasPrefix(p, "/_/api/v1/caldav/") {
next.ServeHTTP(w, r)
return
}
if p != "/" {
@@ -0,0 +1,26 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestNormalizePathDAVCollections(t *testing.T) {
for _, path := range []string{"/_/api/v1/caldav/", "/_/api/v1/caldav/tasks/", "/_/api/v1/caldav/tasks/default/", "/_/api/v1/caldav/calendar-id/"} {
mux := http.NewServeMux()
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(401) })
for _, method := range []string{"GET", "OPTIONS", "PROPFIND", "REPORT"} {
w := httptest.NewRecorder()
NormalizePath(mux).ServeHTTP(w, httptest.NewRequest(method, path, nil))
if w.Code != 401 || w.Header().Get("Location") != "" {
t.Fatalf("%s %s: %d %v", method, path, w.Code, w.Header())
}
}
}
w := httptest.NewRecorder()
NormalizePath(http.NotFoundHandler()).ServeHTTP(w, httptest.NewRequest("GET", "/wiki/path/", nil))
if w.Code != 301 || w.Header().Get("Location") != "/wiki/path" {
t.Fatal("Wiki canonicalization changed", w.Code, w.Header())
}
}