diff --git a/AGENTS.md b/AGENTS.md index 7c917a6..8dd9801 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -886,6 +886,13 @@ calls and kind nodes must carry their own explicit bounds. migrating upgrades still require verified backups. Fixture CA/relay plumbing stays explicit. This verifies seeded native configuration and backup-pairing data, not every product's ordinary content migration, offboarding or full restore. + With `KYQ_TEST_CALENDAR_RESTORE=1` as well, retain two throwaway ceremony custodian shares + only in the test operator, export a candidate Calendar capsule and run its native restore + offline on its own claim. One share must fail; restore the sealed installer credentials + to their recorded paths before startup. Verify key bytes, pre-restore session revocation, + fresh native sign-in and the ordinary event's content/identifiers/edit access. Original data + is moved aside. This is native candidate capsule recovery, not restore of the installer's + pre-upgrade claim copy or offboarding/meeting delivery qualification. - With `KYQ_TEST_MESSAGE_UPGRADE_MANIFEST` naming an independently attested historical KyMessages manifest and its sibling Compose template, `TestKubernetesKyMessage` starts diff --git a/docs/RELEASE-ACCEPTANCE-2026-11-17-MAJOR.md b/docs/RELEASE-ACCEPTANCE-2026-11-17-MAJOR.md index 16e36fa..6900331 100644 --- a/docs/RELEASE-ACCEPTANCE-2026-11-17-MAJOR.md +++ b/docs/RELEASE-ACCEPTANCE-2026-11-17-MAJOR.md @@ -135,7 +135,7 @@ whole-suite release qualification or every product's ordinary content/offboardin | KyRecovery | Native administrative sign-in, everyday identity gate, throwaway public-key ceremony and capsule listing/deposit | Previous-catalog key/pairing retention passed. Restored service with existing capsules/ceremony, administrative revocation and session invalidation remain untested here. Deposit/listing is not product restore. | | kyPulse | Native administrative sign-in, everyday identity gate, monitoring targets healthy and real paired deposit | Previous-catalog config/pairing binding and candidate deposit with prior credentials passed. Restored monitoring state and offboarding/session revocation remain untested. | | KyNotes | Admin backup-status API 200 / ordinary containers 403 with admin-account refusal; everyday backup-status 403 / containers 200 | Native config/account upgrade passed. Real notes migration, offboarding/session revocation and restored notes remain untested. | -| KyCalendar | Admin users API 200 / calendars 403; everyday users API 403 / calendars 200 | Old-image event content/times/IDs/ETag/access and candidate edit passed. Offboarding/restored meetings and recurrence/meeting delivery untested. | +| KyCalendar | Admin users API 200 / calendars 403; everyday users API 403 / calendars 200 | Old-image event preservation/candidate edit and native candidate capsule recovery with restored ordinary event/edit passed. Offboarding, installer resume, recurrence and meeting delivery remain untested. | | KyPost | Native Docker setup, pre-bind-volume layout copy, admin users API 200 / everyday 403, session-ending restart and cold backup | Native config/account upgrade passed in IMAP-proxy mode. Real mail migration/restored mail, offboarding and dedicated-admin ordinary-mail denial remain untested. This fixture disables native mail listeners; it does not qualify the workforce mail stack. | | KyDNS | Native setup, authoritative UDP/TCP DNS, forged-header rejection, unsafe-gateway trust refusal and fail-closed edge behavior | Successful edge/admin sign-in is UNPROVEN on Major because Docker rewrites source addresses. Previous zones/config upgrade, offboarding and restore remain untested. Never broaden trust to force a pass. | | KyMessages | Real encrypted chat, offboarding and history restore; original device decrypts history and removals replay before Synapse starts. Dedicated admin chat sign-in receives KyIdentity access_denied and MAS has no admin account. | Previous0.6.0.1→0.6.1 upgrade with own verified snapshot, original keys/sessions and old/new encrypted events passed; later candidate offboarding/history restore passed. Upstream Matrix-version migration and direct authorization with an otherwise-valid admin token remain unproven. | @@ -242,7 +242,7 @@ earlier failed evidence/source remain intact. V2 did retain the seeded event exa failed because its edit sent an unquoted HTTP If-Match. V3 quotes the original ETag, as the product API tests require, and the complete integration **passed1224.364 s**. Calendar fixture trust is restored after later apply calls with the repeatable CA helper. -It qualifies this seeded event, not Calendar restore/offboarding/recurrence/meeting +That upgrade case alone qualifies the seeded event, not Calendar restore/offboarding/recurrence/meeting transport or other products' content. Notes content needs its actual encryption/key flow; arbitrary opaque bytes are not substituted as a user-note workflow. The product already has native encryption-client and browser-format migration tests, but @@ -261,7 +261,8 @@ old bundled client, complete action-bound KyIdentity confirmation and save a rec copy: notebook creation refuses an unrecoverable key. The local-password browser helper cannot replace this installer-created SSO path. Reuse actual UI content creation and retain the isolated browser key store across the upgrade; do not inject ciphertext or -skip reauthentication/recovery. No Notes browser/runtime case was implemented or run. +skip reauthentication/recovery. No Notes application content case was implemented or run; +the separate isolated TLS prerequisite below does not qualify the application. ## Passed previous-image Messages history upgrade @@ -294,6 +295,39 @@ publication tree `message-history-acceptance` matches344 non-documentation files passed tree byte for byte, including runtime/pins/dependencies; its later report edits do not constitute a fresh test execution. +## Passed native Calendar capsule recovery + +The isolated `20261117-major-calendar-native-restore-v1` campaign **PASSED** at +22:29:48 UTC: fresh upgrade gate7.536 s, affected compile/relay4.533 s, full `make ci` +163.822 s, actual integration1242.651 s and full controller1418.664 s. All seven +previous-image upgrade commands, key/pairing retention and ordinary Calendar event +preservation/edit assertions passed before the new recovery rehearsal. + +`KYQ_TEST_CALENDAR_RESTORE=1` follows KyCalendar's native capsule runbook. Only the +test operator retained two nonconsecutive throwaway custodian shares. The candidate +refused ordinary-user capsule export and pinned the same suite public key for its admin. +It exported a real capsule, verified its transfer digest, refused one-share restoration, +then completed native two-share restore/reset offline. The restored credential map +matched the recorded installer paths; data/recovery/OIDC/directory key hashes matched. +Original data was moved aside. The offline helper was removed before CLI startup. +Old admin/everyday sessions returned401; fresh native sign-in and the restored ordinary +event's content/identifiers/access and a fresh If-Match edit passed. + +The frozen tested patch is +`01eac85d9c8e59b6d3cd931550ef5432ade1986925fceb83d004acba1bce54bb`, retained with +its source in `suite-calendar-native-restore`. This is candidate native capsule recovery, +not restoration of an installer pre-upgrade claim copy, Calendar offboarding, installer +resume after native restore, recurrence or meeting delivery. The separate root +Verification contract documents this opt-in scope. + +The isolated Notes browser TLS prerequisite V12 separately **PASSED**2.244 s at +22:32:01 UTC: a private named CA/signed leaf verified normally, and the wrong hostname +was refused with `SSL_ERROR_BAD_CERT_DOMAIN`. Firefox peaked at157 tasks under the +owner-approved browser-only256-task cap, with no PID-limit events; Go remains128. +No TLS error override or global trust/profile changes were used. Previous failedV1–V11 +remain. This proves fixture transport only; no Notes application enrollment, encrypted +content, retained-client-key upgrade or restore case has been implemented or qualified. + ## HA correction and release gates The original HA fixture used `kind load docker-image` directly on a digest reference. @@ -322,9 +356,9 @@ worktrees or alter pre-existing services. Native-client distribution is separate development archive/signature passed, but Developer ID export remains blocked on a valid direct-distribution profile. This server report certifies no Mac or Android artifact. -DOX pass: root `AGENTS.md` was updated to document the opt-in seven-app/Calendar -(`KYQ_TEST_RELEASE_UPGRADE_MANIFESTS`) and Messages (`KYQ_TEST_MESSAGE_UPGRADE_MANIFEST`) -upgrade-test contracts. +DOX pass: the implementation PRs update root `AGENTS.md` for the opt-in seven-app/Calendar +(`KYQ_TEST_RELEASE_UPGRADE_MANIFESTS`), Messages (`KYQ_TEST_MESSAGE_UPGRADE_MANIFEST`) +and native Calendar capsule recovery (`KYQ_TEST_CALENDAR_RESTORE`) test contracts. `docs/AGENTS.md` and the child indexes remain unchanged because documentation ownership and workflow did not change. This report and the candidate matrix record observed evidence and qualification limits; prior versions are preserved in the timestamped private diff --git a/docs/release-candidate-2026-11-17-major.json b/docs/release-candidate-2026-11-17-major.json index 70cda1f..43dd51d 100644 --- a/docs/release-candidate-2026-11-17-major.json +++ b/docs/release-candidate-2026-11-17-major.json @@ -576,7 +576,7 @@ "kubernetes_secret_payload_count": 0 }, "coverage_audit": { - "checked_at": "2026-11-17T21:09:30.456276+00:00", + "checked_at": "2026-11-17T21:09:30.474136+00:00", "status": "in progress; not release qualified", "products": { "kyidentity": [ @@ -600,8 +600,9 @@ "Native config/account upgrade passed; real note content/offboarding/restore untested" ], "kycalendar": [ - "Reciprocal admin/content endpoints passed", - "Previous-image event text/times/IDs/ETag/access and candidate edit passed; offboarding/restore/recurrence/meeting transport untested" + "Reciprocal native admin/content access, previous-image ordinary event content/times/IDs/ETag and candidate edit passed", + "Candidate native capsule recovery passed: one-share refusal/two-share restore, data/recovery/OIDC/directory key bytes retained, old admin/everyday sessions revoked, fresh native access and restored seeded event edit", + "Offboarding, old installer pre-upgrade claim-copy restore, installer resume after native restore, recurrence and meeting delivery untested" ], "kypost": [ "Admin users endpoint reciprocal authorization passed", @@ -874,5 +875,93 @@ "fresh_combined_integration_run": false, "publication_base": "597ec940141b3d7a14000a0c2d995422cba1efc5", "ancestry_only_rebase": "Old PR206 head tree and merged master base tree identical; feature code tree unchanged by rebase; private ancestry-only-rebase.result.json retains proof" + }, + "calendar_native_restore_extension": { + "status": "PASS: candidate native capsule recovery with retained keys, revoked old sessions and fresh ordinary event access/edit", + "recorded_at": "2026-11-17T22:35:55.331839+00:00", + "worktree": "/home/yoshi/git/KyQuickStart/.claude/worktrees/suite-calendar-native-restore", + "branch": "test/suite-calendar-native-restore", + "base": "50ca7a4d8128950bd4626e3cfdd70c87cb40c5bd", + "patch_sha256": "01eac85d9c8e59b6d3cd931550ef5432ade1986925fceb83d004acba1bce54bb", + "evidence": "20261117-major-calendar-native-restore-v1", + "checks_passed": { + "upgrade-gate": { + "exit_code": 0, + "duration_seconds": 7.536, + "evidence": "/home/yoshi/.local/state/kyquickstart-acceptance/20261117-major-calendar-native-restore-v1/upgrade-gate.result.json" + }, + "affected-compile-relay": { + "exit_code": 0, + "duration_seconds": 4.533, + "evidence": "/home/yoshi/.local/state/kyquickstart-acceptance/20261117-major-calendar-native-restore-v1/affected-compile-relay.result.json" + }, + "ci": { + "exit_code": 0, + "duration_seconds": 163.822, + "evidence": "/home/yoshi/.local/state/kyquickstart-acceptance/20261117-major-calendar-native-restore-v1/ci.result.json" + } + }, + "scope": "Seven actual previous-image configuration/pairing upgrades + ordinary Calendar event; additional candidate native capsule export/two-share offline restore, one-share refusal, key retention, old-session revocation/fresh native access/event edit. NOT Calendar offboarding, restored old pre-upgrade claim copy, meeting delivery, or installer resume after native restore.", + "dox": "Separate isolated harness root Verification documents KYQ_TEST_CALENDAR_RESTORE=1; baseline ownership/child indexes unchanged", + "results": { + "upgrade-gate": { + "exit_code": 0, + "duration_seconds": 7.536, + "evidence": "/home/yoshi/.local/state/kyquickstart-acceptance/20261117-major-calendar-native-restore-v1/upgrade-gate.result.json" + }, + "affected-compile-relay": { + "exit_code": 0, + "duration_seconds": 4.533, + "evidence": "/home/yoshi/.local/state/kyquickstart-acceptance/20261117-major-calendar-native-restore-v1/affected-compile-relay.result.json" + }, + "ci": { + "exit_code": 0, + "duration_seconds": 163.822, + "evidence": "/home/yoshi/.local/state/kyquickstart-acceptance/20261117-major-calendar-native-restore-v1/ci.result.json" + }, + "real-calendar-native-restore": { + "exit_code": 0, + "duration_seconds": 1242.651, + "evidence": "/home/yoshi/.local/state/kyquickstart-acceptance/20261117-major-calendar-native-restore-v1/real-calendar-native-restore.result.json" + }, + "full-qualification": { + "exit_code": 0, + "duration_seconds": 1418.664, + "evidence": "/home/yoshi/.local/state/kyquickstart-acceptance/20261117-major-calendar-native-restore-v1/full-qualification.result.json" + } + }, + "named_assertions_qualified": true, + "whole_suite_qualified": false + }, + "notes_browser_tls_prerequisite": { + "status": "PASS: fixture TLS transport prerequisite only, NOT Notes application acceptance", + "limits": "Go jobs remainTasks128. Browser-onlyTasks256 is owner-approved; same2GiB/noSwap/2CPU/exclusiveheavylock.", + "notes_application_qualification": false, + "previous_failed_run": { + "evidence": "20261117-major-notes-browser-trust-v11", + "exit_code": 1, + "seconds": 2.111, + "peak_tasks": 172, + "pids_limit_events": 0, + "failure": "MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT", + "tls_verification_disabled": false + }, + "last_run": { + "evidence": "20261117-major-notes-browser-trust-v12", + "exit_code": 0, + "seconds": 2.244, + "peak_tasks": 157, + "pids_limit_events": 0, + "positive_https": true, + "wrong_hostname_refused": "SSL_ERROR_BAD_CERT_DOMAIN", + "tls_verification_disabled": false, + "private_ca_trust_only": true + }, + "completed_followup": { + "evidence": "20261117-major-notes-browser-trust-v12", + "status": "PASS: actual isolated browser positiveHTTPS and wrong-host refusal; no Notes application case implemented", + "script_sha256": "1efa42926960b609bcd01e350d825c23ca6d634186afe3713c843e138ab12d33", + "change": "Own namedCA + signed server certificate, only private NSS authority trust, positiveHTTPS and exact wrong-host denial; no TLS override" + } } } diff --git a/test/e2e/calendar_catalog_kube_test.go b/test/e2e/calendar_catalog_kube_test.go index 7be0d42..e0bbf20 100644 --- a/test/e2e/calendar_catalog_kube_test.go +++ b/test/e2e/calendar_catalog_kube_test.go @@ -133,7 +133,13 @@ func checkCatalogCalendar(t *testing.T, ctx context.Context, cs kubernetes.Inter // console but no calendars, the everyday account its calendars but not the console. Test-only // plumbing: testClusterDNS ran and KyCalendar's pod trusts the edge's throwaway certificate. func calendarSignOn(t *testing.T, ctx context.Context, c *kube.Client, certPEM []byte, nodeIP string) *http.Client { - var everyday *http.Client + t.Helper() + _, everyday := calendarSignOnClients(t, ctx, c, certPEM, nodeIP) + return everyday +} + +func calendarSignOnClients(t *testing.T, ctx context.Context, c *kube.Client, certPEM []byte, nodeIP string) (*http.Client, *http.Client) { + var adminClient, everyday *http.Client t.Helper() pool := x509.NewCertPool() if !pool.AppendCertsFromPEM(certPEM) { @@ -219,9 +225,11 @@ func calendarSignOn(t *testing.T, ctx context.Context, c *kube.Client, certPEM [ t.Fatalf("%s: admin/users %d, calendars %d %s", account.username, admin.StatusCode, calendars.StatusCode, b) } t.Logf("%s signed in to KyCalendar through KyIdentity: admin/users %d, calendars %d", account.username, admin.StatusCode, calendars.StatusCode) - if !account.admin { + if account.admin { + adminClient = client + } else { everyday = client } } - return everyday + return adminClient, everyday } diff --git a/test/e2e/calendar_restore_kube_test.go b/test/e2e/calendar_restore_kube_test.go new file mode 100644 index 0000000..a26ea17 --- /dev/null +++ b/test/e2e/calendar_restore_kube_test.go @@ -0,0 +1,228 @@ +//go:build e2e + +package e2e + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "net/url" + "os" + "strings" + "testing" + "time" + + "github.com/Busnes-app/kyquickstart/internal/cli" + "github.com/Busnes-app/kyquickstart/internal/kube" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" +) + +// Only the test operator holds these throwaway custodian shares. The live +// products receive the suite public key, never a recovery private key/share. +type calendarRestoreKit struct { + PublicKey, KeyID string + Shares []string +} + +// restoreNativeCalendar follows KyCalendar's native capsule runbook, not the +// installer's Docker-only restic command. The old live data is moved aside. +func restoreNativeCalendar(t *testing.T, ctx context.Context, cs kubernetes.Interface, c *kube.Client, state, catalogDir string, trust []string, certPEM []byte, nodeIP string, kit calendarRestoreKit, verify func(*http.Client)) { + t.Helper() + if kit.PublicKey == "" || kit.KeyID == "" || len(kit.Shares) != 2 { + t.Fatal("Calendar restore has no two-share suite ceremony kit") + } + // Later unrelated apply calls replace the fixture CA. Restore test trust, + // then use fresh native sign-ins for the real step-up-protected export. + trustTestCA(t, ctx, cs, c, "kycalendar", certPEM) + admin, everyday := calendarSignOnClients(t, ctx, c, certPEM, nodeIP) + origin := "https://" + catalogCalendarURLHost + call := func(client *http.Client, path string, body []byte, want int) (http.Header, []byte) { + t.Helper() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+path, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Origin", origin) + req.Header.Set("Content-Type", "application/json") + u, _ := url.Parse(origin) + for _, cookie := range client.Jar.Cookies(u) { + if cookie.Name == "ky_csrf" { + req.Header.Set("X-CSRF-Token", cookie.Value) + } + } + r, err := client.Do(req) + if err != nil { + t.Fatal("Calendar recovery API", err) + } + defer r.Body.Close() + raw, err := io.ReadAll(io.LimitReader(r.Body, (16<<20)+1)) + if err != nil || len(raw) > 16<<20 || r.StatusCode != want { + t.Fatalf("Calendar recovery %s: status %d, read %v", path, r.StatusCode, err) + } + return r.Header, raw + } + call(everyday, "/api/backup/export-capsule", nil, http.StatusForbidden) + pin, _ := json.Marshal(map[string]any{"public_key": kit.PublicKey, "threshold": 2, "total_shares": 3}) + _, raw := call(admin, "/api/backup/pin-key", pin, http.StatusOK) + var pinned struct { + KeyID string `json:"recovery_key_id"` + } + if json.Unmarshal(raw, &pinned) != nil || pinned.KeyID != kit.KeyID { + t.Fatal("Calendar did not pin the suite ceremony key") + } + ns, appPod, container, err := c.AppPod(ctx, "kycalendar") + if err != nil { + t.Fatal(err) + } + live, err := cs.CoreV1().Pods(ns).Get(ctx, appPod, metav1.GetOptions{}) + if err != nil || len(live.Spec.Containers) != 1 { + t.Fatal("Calendar live pod", err) + } + keyArgs := []string{"sha256sum", "/app/data/encryption.key", "/app/data/recovery.pub", calendarSetupDir + "/client.secret", calendarSetupDir + "/directory.secret"} + beforeKeys, err := c.Exec(ctx, ns, appPod, container, keyArgs) + if err != nil { + t.Fatal("Calendar pre-restore key checkpoint", err) + } + header, capsule := call(admin, "/api/backup/export-capsule", nil, http.StatusOK) + defer clear(capsule) + if header.Get("X-Recovery-Key-ID") != kit.KeyID || len(capsule) == 0 { + t.Fatal("Calendar exported no suite-key capsule") + } + lifecycle := func(op string) { + t.Helper() + var out bytes.Buffer + err := cli.Run(ctx, append([]string{op, "kycalendar", "--state", state}, trust...), cli.Options{Catalog: os.DirFS(catalogDir), ReleaseSet: "e2e", Out: &out}) + t.Logf("Calendar native restore %s: %v\n%s", op, err, out.String()) + if err != nil { + t.Fatal("Calendar lifecycle", op, err) + } + } + lifecycle("stop") + spec := *live.Spec.DeepCopy() + spec.InitContainers = nil + spec.RestartPolicy = corev1.RestartPolicyNever + spec.Containers[0].Command = []string{"/bin/sh", "-c", "sleep 600"} + spec.Containers[0].Args = nil + spec.Containers[0].StartupProbe = nil + spec.Containers[0].LivenessProbe = nil + spec.Containers[0].ReadinessProbe = nil + helper, err := cs.CoreV1().Pods(ns).Create(ctx, &corev1.Pod{ObjectMeta: metav1.ObjectMeta{GenerateName: "calendar-native-restore-", Labels: map[string]string{"test": "calendar-native-restore"}}, Spec: spec}, metav1.CreateOptions{}) + if err != nil { + t.Fatal("create private offline restore pod", err) + } + zero := int64(0) + remove := func() error { + return cs.CoreV1().Pods(ns).Delete(ctx, helper.Name, metav1.DeleteOptions{GracePeriodSeconds: &zero, Preconditions: &metav1.Preconditions{UID: &helper.UID}}) + } + t.Cleanup(func() { _ = remove() }) + deadline := time.Now().Add(90 * time.Second) + for { + p, err := cs.CoreV1().Pods(ns).Get(ctx, helper.Name, metav1.GetOptions{}) + if err != nil { + t.Fatal("offline restore pod", err) + } + if p.Status.Phase == corev1.PodRunning && len(p.Status.ContainerStatuses) == 1 && p.Status.ContainerStatuses[0].Ready { + break + } + if p.Status.Phase == corev1.PodFailed || time.Now().After(deadline) { + t.Fatal("offline restore pod did not become ready") + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-time.After(time.Second): + } + } + exec := func(args ...string) []byte { + t.Helper() + out, err := c.Exec(ctx, ns, helper.Name, "app", args) + if err != nil { + t.Fatal("offline Calendar command", err) + } + return out + } + exec("sh", "-c", "umask 077; test ! -e /app/data/.lifecycle-capsule.kycap; : > /app/data/.lifecycle-capsule.kycap") + for offset := 0; offset < len(capsule); offset += 32 << 10 { + end := min(offset+(32<<10), len(capsule)) + if _, err := c.ExecInput(ctx, ns, helper.Name, "app", []string{"sh", "-c", "cat >> /app/data/.lifecycle-capsule.kycap"}, capsule[offset:end]); err != nil { + t.Fatal("transfer sealed Calendar capsule", err) + } + } + sum := sha256.Sum256(capsule) + got := strings.Fields(string(exec("sha256sum", "/app/data/.lifecycle-capsule.kycap"))) + if len(got) != 2 || got[0] != hex.EncodeToString(sum[:]) { + t.Fatal("Calendar capsule transfer digest mismatch") + } + // A single custodian may not publish a restored database. + if _, err := c.ExecInput(ctx, ns, helper.Name, "app", []string{"/app/kycalendar", "restore", "-capsule", "/app/data/.lifecycle-capsule.kycap", "-to", "/app/data/.lifecycle-refused", "-service", "kycalendar"}, []byte(kit.Shares[0]+"\n")); err == nil { + t.Fatal("one custodian share restored a two-share capsule") + } + exec("sh", "-c", "test ! -f /app/data/.lifecycle-refused/data/kycalendar.db") + input := []byte(strings.Join(kit.Shares, "\n") + "\n") + defer clear(input) + out, err := c.ExecInput(ctx, ns, helper.Name, "app", []string{"sh", "-c", "/app/kycalendar restore -capsule /app/data/.lifecycle-capsule.kycap -to /app/data/.lifecycle-restored -service kycalendar 2>/app/data/.lifecycle-restore.stderr"}, input) + if err != nil || !strings.Contains(string(out), "Sessions, MFA challenges and app passwords revoked") { + t.Fatal("native Calendar capsule restore/reset failed", err) + } + var paths map[string]string + if json.Unmarshal(exec("cat", "/app/data/.lifecycle-restored/installer/credential-paths.json"), &paths) != nil || len(paths) != 2 || paths["installer/client.secret"] != calendarSetupDir+"/client.secret" || paths["installer/directory.secret"] != calendarSetupDir+"/directory.secret" { + t.Fatal("restored Calendar credential paths differ from its managed setup") + } + // Runbook: restore sealed installer credentials to the recorded absolute paths, + // privately, before startup. Preserve the entire original tree instead of merging it. + exec("sh", "-c", `set -eu +mkdir -m 700 /app/data/.lifecycle-before +for entry in /app/data/* /app/data/.[!.]* /app/data/..?*; do + [ -e "$entry" ] || [ -L "$entry" ] || continue + case "$entry" in /app/data/.lifecycle-*) continue ;; esac + mv "$entry" /app/data/.lifecycle-before/ +done +cp -a /app/data/.lifecycle-restored/data/. /app/data/ +mkdir -p -m 700 `+calendarSetupDir+` +chmod 700 /app/data/installer `+calendarSetupDir+` +cp /app/data/.lifecycle-restored/installer/client.secret `+calendarSetupDir+`/client.secret +cp /app/data/.lifecycle-restored/installer/directory.secret `+calendarSetupDir+`/directory.secret +chmod 600 `+calendarSetupDir+`/client.secret `+calendarSetupDir+`/directory.secret`) + if got := exec(keyArgs...); !bytes.Equal(got, beforeKeys) { + t.Fatal("native Calendar restore changed data/recovery/OIDC/directory key bytes") + } + if err := remove(); err != nil { + t.Fatal("remove offline Calendar restore pod", err) + } + deadline = time.Now().Add(30 * time.Second) + for { + _, err := cs.CoreV1().Pods(ns).Get(ctx, helper.Name, metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + break + } + if err != nil || time.Now().After(deadline) { + t.Fatal("offline restore pod did not terminate", err) + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-time.After(time.Second): + } + } + lifecycle("start") + for _, client := range []*http.Client{admin, everyday} { + r, err := client.Get(origin + "/api/calendars") + if err != nil { + t.Fatal("Calendar old-session check", err) + } + r.Body.Close() + if r.StatusCode != http.StatusUnauthorized { + t.Fatalf("Calendar accepted or misclassified a pre-restore session: HTTP%d", r.StatusCode) + } + } + _, restoredEveryday := calendarSignOnClients(t, ctx, c, certPEM, nodeIP) + verify(restoredEveryday) + t.Log("candidate Calendar native capsule restore passed with two custodian shares; one share refused, keys retained, old sessions revoked and fresh everyday event access/edit passed") +} diff --git a/test/e2e/calendar_upgrade_kube_test.go b/test/e2e/calendar_upgrade_kube_test.go index 9706167..6994967 100644 --- a/test/e2e/calendar_upgrade_kube_test.go +++ b/test/e2e/calendar_upgrade_kube_test.go @@ -9,12 +9,13 @@ import ( "io" "net/http" "net/url" + "strings" "testing" ) // seedCalendarUpgrade uses the old product's ordinary API, then checks the same // event through a freshly signed-in candidate session. No attendees or mail are sent. -func seedCalendarUpgrade(t *testing.T, ctx context.Context, old *http.Client) func(*http.Client) { +func seedCalendarUpgrade(t *testing.T, ctx context.Context, old *http.Client) (func(*http.Client), func(*http.Client)) { t.Helper() origin := "https://" + catalogCalendarURLHost send := func(client *http.Client, method, path, body, etag string, want int, out any) { @@ -82,22 +83,52 @@ func seedCalendarUpgrade(t *testing.T, ctx context.Context, old *http.Client) fu if before.CalendarID != cal.ID || before.UID != made.UID || before.ETag != made.ETag || before.Title != "Major migration — café" || before.Location != "Room 7" || before.Description != "Retain this ordinary event.\nSecond line." || before.Start != "2026-11-18T09:00:00Z" || before.End != "2026-11-18T10:00:00Z" || !before.Editable { t.Fatal("old Calendar did not read back the seeded event exactly") } - return func(candidate *http.Client) { + const edited = `{"title":"Edited after candidate upgrade","location":"Room 7","description":"Retain this ordinary event.\nSecond line.","start":"2026-11-18T09:00:00Z","end":"2026-11-18T10:00:00Z","zone":"UTC"}` + var afterUpgrade eventView + verifyUpgrade := func(candidate *http.Client) { t.Helper() if after := read(candidate); after != before { t.Fatal("candidate Calendar changed existing event content, identity, ETag or access") } - const edited = `{"title":"Edited after candidate upgrade","location":"Room 7","description":"Retain this ordinary event.\nSecond line.","start":"2026-11-18T09:00:00Z","end":"2026-11-18T10:00:00Z","zone":"UTC"}` var changed struct{ ETag string } send(candidate, "PUT", "/api/events/"+cal.ID+"/"+made.UID, edited, made.ETag, http.StatusOK, &changed) after := read(candidate) if changed.ETag == "" || changed.ETag == made.ETag || after.ETag != changed.ETag || after.Title != "Edited after candidate upgrade" { t.Fatal("candidate Calendar could not edit preserved event with its old ETag") } + afterUpgrade = after after.Title, after.ETag = before.Title, before.ETag if after != before { t.Fatal("candidate Calendar edit changed unrelated event content or access") } t.Log("real previous-image Calendar event retained text/times/IDs/ETag and accepted a candidate If-Match edit") } + verifyRestore := func(restored *http.Client) { + t.Helper() + got := read(restored) + if afterUpgrade.ETag == "" || got.ETag == "" { + t.Fatal("no upgraded/restored Calendar ETag") + } + etag := got.ETag + // Native restore intentionally rotates the sync epoch; content/identity + // must survive even if an epoch-derived ETag changes. + got.ETag = afterUpgrade.ETag + if got != afterUpgrade { + t.Fatal("native restore changed the everyday event, identifiers or edit access") + } + var changed struct{ ETag string } + body := strings.Replace(edited, "Edited after candidate upgrade", "Edited after native capsule restore", 1) + send(restored, "PUT", "/api/events/"+cal.ID+"/"+made.UID, body, etag, http.StatusOK, &changed) + got = read(restored) + if got.Title != "Edited after native capsule restore" || changed.ETag == "" || changed.ETag == etag || got.ETag != changed.ETag { + t.Fatal("restored event did not accept an If-Match edit") + } + got.Title, got.ETag = afterUpgrade.Title, afterUpgrade.ETag + if got != afterUpgrade { + t.Fatal("restored Calendar edit changed unrelated event fields") + } + t.Log("native Calendar restore retained everyday event content/IDs/access and accepted a fresh If-Match edit") + } + return verifyUpgrade, verifyRestore + } diff --git a/test/e2e/npm_joins_kube_test.go b/test/e2e/npm_joins_kube_test.go index 1da064d..f195d87 100644 --- a/test/e2e/npm_joins_kube_test.go +++ b/test/e2e/npm_joins_kube_test.go @@ -51,6 +51,9 @@ func testKubernetesEdgeJoins(t *testing.T, proxy string) { cs := kubernetes.NewForConfigOrDie(cfg) catalogDir := filepath.Join(work, "catalog") previous := os.Getenv("KYQ_TEST_RELEASE_UPGRADE_MANIFESTS") + if os.Getenv("KYQ_TEST_CALENDAR_RESTORE") == "1" && previous == "" { + t.Fatal("Calendar restore case requires the attested previous release manifests") + } candidates := map[string][]byte{} fromPrevious := func(app string) { t.Helper() @@ -92,6 +95,7 @@ func testKubernetesEdgeJoins(t *testing.T, proxy string) { plan := filepath.Join(state, "stack.yaml") os.WriteFile(plan, []byte("version: 1\ntargets:\n - name: k8s\n kubeconfig: "+kc+"\n storage_class: standard\napps:\n - name: "+proxy+"\n target: k8s\n - name: hello\n target: k8s\n"), 0o600) var outputs, trust []string + var restoreCalendar func() apply := func(want string) string { t.Helper() var out bytes.Buffer @@ -271,12 +275,17 @@ func testKubernetesEdgeJoins(t *testing.T, proxy string) { // OIDC clients, SCIM and receipts. Also seed a real Recovery ceremony, // Pulse pairing and deposit, then preserve them across actual upgrades. watched := []string{"hello", "kycalendar", "kydrive", "kyidentity", "kynotes", "kypost", "kyrecovery"} - recoveryPairing := catalogSignOnWithBackup(t, ctx, cs, kc, certPEM, nodeIP, true, watched) + var restoreKit calendarRestoreKit + var custody []*calendarRestoreKit + if os.Getenv("KYQ_TEST_CALENDAR_RESTORE") == "1" { + custody = []*calendarRestoreKit{&restoreKit} + } + recoveryPairing := catalogSignOnWithBackup(t, ctx, cs, kc, certPEM, nodeIP, true, watched, custody...) // Later apply calls may replace this test-only mount. Repeating the ensure // must not append duplicate volumes, mounts or environment values. trustTestCA(t, ctx, cs, connected, "kycalendar", certPEM) trustTestCA(t, ctx, cs, connected, "kycalendar", certPEM) - verifyCalendar := seedCalendarUpgrade(t, ctx, calendarSignOn(t, ctx, connected, certPEM, nodeIP)) + verifyCalendar, verifyRestoredCalendar := seedCalendarUpgrade(t, ctx, calendarSignOn(t, ctx, connected, certPEM, nodeIP)) fingerprints := func() map[string][32]byte { t.Helper() out := map[string][32]byte{} @@ -391,7 +400,13 @@ func testKubernetesEdgeJoins(t *testing.T, proxy string) { t.Logf("preserved %d Kubernetes Secret payloads, Docker client/session keys, Identity JWKS and Recovery pairing; candidate Pulse deposited with its prior pairing", len(before)) driveSignOn(t, ctx, kc, certPEM, nodeIP, driveSecrets[1]) notesSignOn(t, ctx, connected, certPEM, nodeIP) - verifyCalendar(calendarSignOn(t, ctx, connected, certPEM, nodeIP)) + calendarEveryday := calendarSignOn(t, ctx, connected, certPEM, nodeIP) + verifyCalendar(calendarEveryday) + if os.Getenv("KYQ_TEST_CALENDAR_RESTORE") == "1" { + restoreCalendar = func() { + restoreNativeCalendar(t, ctx, cs, connected, state, catalogDir, trust, certPEM, nodeIP, restoreKit, verifyRestoredCalendar) + } + } postSignOn(t, ctx, connected, certPEM, nodeIP) } @@ -460,6 +475,11 @@ func testKubernetesEdgeJoins(t *testing.T, proxy string) { t.Errorf("rerun: kydns.edge = %q, %v", status(out, "kydns.edge"), err) } + // Finish all unrelated apply/rerun graphs before the destructive native + // recovery rehearsal. Its scope is restored product access, not installer resume. + if restoreCalendar != nil { + restoreCalendar() + } var edgeSecrets []string if npm != nil { edgeSecrets = []string{npm.password, npm.token, npm.stored()} diff --git a/test/e2e/recovery_kube_test.go b/test/e2e/recovery_kube_test.go index 0212ad9..46084b6 100644 --- a/test/e2e/recovery_kube_test.go +++ b/test/e2e/recovery_kube_test.go @@ -171,7 +171,7 @@ func catalogSignOn(t *testing.T, ctx context.Context, cs kubernetes.Interface, k catalogSignOnWithBackup(t, ctx, cs, kubeconfig, certPEM, nodeIP, true, pulseWatched) } -func catalogSignOnWithBackup(t *testing.T, ctx context.Context, cs kubernetes.Interface, kubeconfig string, certPEM []byte, nodeIP string, backup bool, watched []string) [32]byte { +func catalogSignOnWithBackup(t *testing.T, ctx context.Context, cs kubernetes.Interface, kubeconfig string, certPEM []byte, nodeIP string, backup bool, watched []string, custody ...*calendarRestoreKit) [32]byte { var checkpoint [32]byte t.Helper() c, err := kube.Connect(kubeconfig, "") @@ -289,7 +289,7 @@ func catalogSignOnWithBackup(t *testing.T, ctx context.Context, cs kubernetes.In if app.client == "kypulse" { pulseTargetsHealthy(t, ctx, send, app.origin, watched) if backup { - pulseBacksUpByHand(t, ctx, c, jar, send) + pulseBacksUpByHand(t, ctx, c, jar, send, custody...) } if !backup { u, _ := url.Parse(app.origin) @@ -338,7 +338,7 @@ func catalogSignOnWithBackup(t *testing.T, ctx context.Context, cs kubernetes.In // mints a code with the handover's command, and pairs kyPulse on its backup API with the // handover's URL. kyPulse accepts the private address only because the catalog set // KYPULSE_BACKUP_ALLOW_PRIVATE_RECOVERY; its deposit then reaches KyRecovery, which lists it. -func pulseBacksUpByHand(t *testing.T, ctx context.Context, c *kube.Client, jar http.CookieJar, send func(method, endpoint string, body []byte, csrf string) (*http.Response, []byte)) { +func pulseBacksUpByHand(t *testing.T, ctx context.Context, c *kube.Client, jar http.CookieJar, send func(method, endpoint string, body []byte, csrf string) (*http.Response, []byte), custody ...*calendarRestoreKit) { t.Helper() recovery, pulse := "https://"+catalogRecoveryURLHost, "https://"+catalogPulseURLHost key, err := recoverykey.Generate() @@ -346,6 +346,13 @@ func pulseBacksUpByHand(t *testing.T, ctx context.Context, c *kube.Client, jar h t.Fatal(err) } pub := key.Public() + if len(custody) != 0 { + shares, err := recoverykey.Split(key, 2, 3) + if err != nil { + t.Fatal(err) + } + *custody[0] = calendarRestoreKit{PublicKey: base64.StdEncoding.EncodeToString(pub.Bytes()), KeyID: pub.ID(), Shares: []string{shares[0].String(), shares[2].String()}} + } body, _ := json.Marshal(map[string]any{"public_key": base64.StdEncoding.EncodeToString(pub.Bytes()), "threshold": 2, "total_shares": 3}) r, b := send("POST", recovery+"/api/recovery-key", body, "") var imported struct {