oficina / home Public

feat/existing-team-adoption

Squashed from feat/existing-team-adoption into main.
codex agent, operated by paul@keymail.dev d36a41375161a7d0ce8377271935f702df50ae76 parent d82341c
19 files changed, +962 −13
  • implementation/existing-team-adoption.md +177 −0
  • implementation/team-provisioning-amendment.md +5 −0
  • internal/home/directory_runtime.go +3 −0
  • internal/home/directorydata/canonical.go +16 −0
  • internal/home/existing_adoption_test.go +162 −0
  • internal/home/operator_confirm.go +21 −2
  • internal/home/operator_http_test.go +7 −0
  • internal/home/templates/operator_confirm.html +2 −0
  • internal/home/templates/operator_confirm_id.html +2 −0
  • internal/operator/directory.go +14 −0
  • internal/operator/existing.go +14 −0
  • internal/operator/existing_migration_test.go +71 −0
  • internal/operator/existing_test.go +389 −0
  • internal/operator/http_migrations/credential/migrations/0002_existing_team.sql +2 −0
  • internal/operator/http_migrations/directory/migrations/0002_existing_team.sql +2 −0
  • internal/operator/http_verbs.go +29 −6
  • internal/operator/owner.go +9 −0
  • internal/operator/plan.go +18 −4
  • internal/operator/verification.go +19 −1

CI passed — run details

diff --git a/implementation/existing-team-adoption.md b/implementation/existing-team-adoption.md
new file mode 100644
index 0000000..ea44407
--- /dev/null
+++ b/implementation/existing-team-adoption.md
@@ -0,0 +1,177 @@
+# Existing canonical app adoption
+
+Status: Home capability design approved by independent GPT-6 Astra,
+2026-11-02, after rollback, observation and scope revisions. Production
+activation remains gated on the reviewed observation runner and confirmations.
+Base: d82341c. Implements agent-access task 5 and Home discussion 103.
+
+The six existing canonical instances need directory membership and routing
+without creating replacement instances, changing their keys, or converting
+their existing item permissions to TeamMode. Agent adapters already support
+this combination: Home controls delegated team admission; each app resolves
+the Home subject and enforces its current local resource permissions. A new
+directory membership never grants access to existing content by itself.
+
+## Scope and authority
+
+Extend the signed operator plan with optional `existing_team` (the actual
+team SQID, not the dashboard label). It is valid only for create-team or
+add-apps plans and only for the six compiled canonical apps. Both roles show
+an explicit existing-app adoption description. The directory requires label
+`oficina`, shows the exact canonical hosts, and binds seeding and every
+subsequent operation to the plan's SQID. The credential plan binds owner-seed
+and the signed provisioning record to that same SQID. Existing-only owner
+lookup, typed owner confirmation, two-role fresh authentication, signed
+stream ordering, expiration and exact retries remain required.
+
+Add an `existing_team` column to each role's operator_plans using new
+additive migrations. Store only the bounded opaque SQID; no signed plan or
+address. The field defaults empty for old plans. Ordinary plan behavior is
+unchanged except that `oficina` is reserved: ordinary create-team plans and
+native seeding refuse that label. Ordinary add-apps also refuses that label;
+only canonical adoption can add apps there. An ordinary retire-apps window
+may disable a directory binding, but cannot retire an env-manifest consumer.
+Adoption's SQID must decode to exactly one
+positive signed-64-bit team ID and re-encode identically.
+
+Rollback is forward-compatible only after adoption: a pre-adoption binary
+rejects canonical live rows and can make the whole chooser fail. Keep an
+adoption-capable build as the rollback target. Before any adoption writes,
+an older build is permitted only after every adoption window/pending plan
+expires. After canonical bindings exist, do not downgrade, restore an old
+snapshot, or delete rows to force a downgrade. Disabling delegated access
+is the immediate incident response; a separate reviewed recovery is needed
+if no adoption-capable binary is usable. App local access and data remain
+available independently of the new connection service.
+
+The canonical binding table is compiled and closed: docs, sheets, slides,
+memoria, calendar and calls each use consumer ID equal to app slug and
+origin `https://<app>.oficina.works`. Their only label is `oficina`.
+Directory read policy admits these exact stored tuples, alongside ordinary
+label.app destinations. Merely broadening hostname validation is not the
+write path: directory.provision-consumer refuses canonical origins unless
+ExecuteHTTP supplies an open adoption window matching the exact tuple and
+SQID. Native provision never supplies that authorization. Ordinary HTTP
+plans cannot write canonical tuples; adoption plans cannot write new-team
+tuples. Existing unique origin/consumer constraints prevent another team
+claiming an adopted instance. Provenance fence and owner membership remain.
+
+Credential register-consumer under an adoption window verifies the
+directory signature, exact issuer/directory/app/consumer/origin and pinned
+team, then requires that exact ID/origin pair in the immutable env manifest.
+It returns the existing union manifest digest without inserting, replacing
+or retiring a registration. Partial matches, table consumers, missing env
+entries and ordinary windows all refuse. Sign-in registrations and keys
+remain unchanged. Ordinary registration continues rejecting env collisions.
+
+## Activation and existing access
+
+Provisioning still creates pending directory/roster bindings and a signed
+record, with the existing operation ledger and bounded verification attempt.
+Canonical activation uses explicit policy
+`oficina/existing-app-activation/v1` under an adoption window; ordinary
+activation keeps `oficina/team-activation/v1`. Policy/route mismatch refuses,
+including native activation. Both paths retain all attempt, owner, epoch,
+record, generation, build, artifact, manifest and configuration digest checks.
+
+The adoption observation attests the canonical host's exact build, unchanged
+existing consumer registration, unchanged storage and identity keys, and
+agent configuration bound to the actual team. It does not attest a fresh
+isolated database or TeamMode conversion. No TEAM_* settings are enabled,
+no content is copied, no existing memberships are inferred, and no existing
+local user access is removed. The UI explicitly says that connecting an app
+preserves its existing content permissions. This narrows the activation
+claim and is a deliberate amendment to team-provisioning-amendment.md §2.6,
+§5 and its new-instance-only threat model, not a fake TeamMode probe.
+
+This implementation adds Home's capability and reviewable operator tooling;
+Alta's ordinary instance-creation recipe must not be used for adoption.
+Production activation still needs actual signed plans, Home's fresh browser
+confirmation, and the historical never-provisioned attestation before the
+initial generation. Existing deployment authorization does not stand in for
+these product-level confirmations. No production mutation is done by tests.
+
+Typed owner confirmation applies to create-team only. An add-apps adoption
+plan has no owner field; both fresh confirmations instead identify the
+existing SQID, exact app hosts and preservation of local permissions.
+
+### Observation recipe and activation gate
+
+The activation evidence is the operator's signed observation; neither Home
+nor the platform attests that arbitrary digest fields describe real checks.
+The adoption runner must obtain two supported CARLOS snapshots, before any
+configuration write and after the process adopts the intended configuration.
+Each snapshot records account/app/instance ID, canonical alias and its
+target, named/default environment identity, persistent storage identity,
+Home issuer/consumer ID, and the complete effective configuration. Secrets
+are held only in memory; the saved evidence contains a random-key HMAC-SHA256
+commitment to each existing secret, so later comparison detects changed
+identity/data keys without printing or persisting their values. The HMAC
+key is kept with the run's encrypted operator journal, never in the report.
+The before snapshot is captured once, sealed before durable storage, and
+never rebaselined on retry. After must preserve every old setting except the
+explicitly enumerated AGENT_ISSUER and AGENT_TEAM additions. No TEAM_*
+setting may be active before or after; no instance creation or storage swap.
+
+Compute environment_binding as base64url SHA256 of a canonical JSON array:
+context `oficina/existing-app-observation/v1`, exact account/app/instance,
+environment and storage identities, canonical alias target, sorted before
+configuration entries with secret HMACs, sorted after entries with secret
+HMACs, actual team SQID, connection issuer, reviewed artifact SHA256, and
+observed version. Require the canonical HTTPS /api/version body and
+X-Carlos-Version to equal that reviewed version, without redirects, and
+/healthz success. Fetch the existing credential manifest digest through the
+verified adoption registration result. The signed activation retains these
+digests and the current bounded verification attempt.
+
+The runner additionally checks that a real Home member lacking local app
+permission remains refused, and that revoking directory membership refuses
+an existing delegated connection without removing normal local access.
+Synthetic proof belongs in integration tests; actual-user acceptance follows
+setup. Until the reviewed snapshot/observation runner exists and its negative
+checks pass, production activation is blocked even if Home capability is
+deployed. This document does not authorize hand-constructing observation
+digests or bypassing a missing snapshot facility.
+
+Adoption and Alta share exactly one operator signer, installation, registry
+and device on both roles. No native command enrolls a competing stream.
+Directory initialize must be sequence 1, before any adoption. Its actual
+four-table guard checks roster_generation, roster_consumers, roster_tokens
+and roster_operator_receipts; the preflight also checks teams, memberships,
+team_instances and both operator streams. Use the shared team-keygen output
+only after its own review and CI pass. Existing consumer aliases are checked
+against their exact env manifest; no second signer or regenerated keyset is
+introduced for the adoption tool.
+
+This supersedes team-provisioning-amendment.md §4's label.app-only rendering
+for adoption plans, §2.6/§5's new-instance activation policy, and §8's claim
+that a confirmed provisioner cannot affect existing canonical hosts. An
+adoption window explicitly allows binding those six pre-existing hosts to
+one confirmed team, changing directory discovery and delegated admission.
+It grants no local content permission and cannot change credential env
+registrations, existing storage or keys. The operator signer can falsely
+attest observations; that trust is explicit and bounded by confirmation.
+
+## Required evidence
+
+- Signed plan roundtrip/persistence, invalid kind/label/app/SQID, changed
+ signature and scope, expiry; actual confirmation rendering on both roles.
+- Full initialize, owner seed, team seed, canonical provision, existing
+ registration verification, verify and activate flow with fresh fixtures.
+- Ordinary/native provision refusal, other label/team/app/consumer/origin,
+ new-team origin in adoption mode, registration table/env partial matches,
+ wrong signature, activation policy substitution and window mismatch.
+- Exact replay retains one team/record; no registry duplication; existing
+ registration and existing local-content authority preserved.
+- Directory/agent discovery exposes only live routes for current members;
+ membership removal revokes discovery. Privacy gates cover plan fields and
+ no new address/content storage. Existing migrations/gates remain intact.
+- Upgrade old pending/open plans, restart and expire new adoption plans;
+ demonstrate old-reader incompatibility after activation and verify the
+ forward-compatible rollback build. Observer rejects changed storage,
+ identity keys, agent team, TeamMode and version body/header mismatch.
+- Independent source/evidence review, meaningful adverse mutations, full
+ required CI, deployed isolated canary and exact canonical version checks.
+
+No claim of four-client live acceptance follows from these gates. That is a
+subsequent authenticated test after actual team setup and connection rollout.
diff --git a/implementation/team-provisioning-amendment.md b/implementation/team-provisioning-amendment.md
index 0d6c263..12aa4bb 100644
--- a/implementation/team-provisioning-amendment.md
+++ b/implementation/team-provisioning-amendment.md
@@ -1,5 +1,10 @@
# 🤖 Amendment: the operator endpoint (teams without the maintenance worker)
+Existing canonical instances: `existing-team-adoption.md` extends §4's
+confirmation rendering, §2.6/§5's activation policy and §8's threat model
+for explicitly confirmed adoption plans. It preserves existing registrations
+and local content authority; ordinary new-team provisioning stays separate.
+
**Status:** APPROVED (design), 2026-10-27. Drafted by Claude Opus 5.5 for
Paul. **Reviewed by Claude Fable 5.1 (claude-fable-5-1), 2026-10-27,
discussion 92, APPROVED (design, round 3)** at `93f8209`, after round 1
diff --git a/internal/home/directory_runtime.go b/internal/home/directory_runtime.go
index e171714..ddffc69 100644
--- a/internal/home/directory_runtime.go
+++ b/internal/home/directory_runtime.go
@@ -25,6 +25,9 @@ func directoryApps() []directoryApp {
}
func directoryRouteAllowed(route directorydata.Route) bool {
+ if route.Label == "oficina" {
+ return directorydata.CanonicalBinding(route.Label, route.App, route.ConsumerID, route.Origin)
+ }
for _, app := range directoryApps() {
if app.slug == route.App && app.integrated {
return route.Origin == "https://"+route.Label+"."+app.slug+".oficina.works"
diff --git a/internal/home/directorydata/canonical.go b/internal/home/directorydata/canonical.go
new file mode 100644
index 0000000..47fdad9
--- /dev/null
+++ b/internal/home/directorydata/canonical.go
@@ -0,0 +1,16 @@
+package directorydata
+
+// CanonicalOrigin is a closed registry of the existing suite instances. It
+// does not authorize a write: only a confirmed operator adoption may bind one.
+func CanonicalOrigin(app string) string {
+ switch app {
+ case "docs", "sheets", "slides", "memoria", "calendar", "calls":
+ return "https://" + app + ".oficina.works"
+ }
+ return ""
+}
+
+// CanonicalBinding pins all parts of an existing instance's directory route.
+func CanonicalBinding(label, app, consumer, origin string) bool {
+ return label == "oficina" && consumer == app && CanonicalOrigin(app) != "" && origin == CanonicalOrigin(app)
+}
diff --git a/internal/home/existing_adoption_test.go b/internal/home/existing_adoption_test.go
new file mode 100644
index 0000000..eae732e
--- /dev/null
+++ b/internal/home/existing_adoption_test.go
@@ -0,0 +1,162 @@
+package home
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/go-json-experiment/json"
+
+ "amadan.net/oficina/home/internal/home/directorydata"
+ "amadan.net/oficina/home/internal/home/sealtest"
+ "amadan.net/oficina/home/internal/operator"
+)
+
+// Exercise both real HTTP routers and their fresh browser confirmations, not
+// just the operator methods. Synthetic fixtures never touch production data.
+func TestExistingAdoptionHTTPPreservesCredentialAndLocalBoundary(t *testing.T) {
+ f := newOperatorFixtureConsumers(t, map[string]string{"docs": "https://docs.oficina.works"})
+ signInFully(t, f.credential, sealtest.CanaryAddress)
+ f.openWindows(t, "initialize", nil)
+ if r, _ := f.run(t, "directory", "directory.initialize", func(b operator.InputBase) any {
+ return operator.InitializeInput{InputBase: b, Generation: generationToken(), Baseline: "operator-attests-never-provisioned"}
+ }); r.Code != 200 {
+ t.Fatal("initialize", r.Code)
+ }
+ f.expireWindows(t)
+ var owner string
+ if e := f.credential.db.Writer().QueryRow("SELECT person_ref FROM people WHERE blind_index=?", blindIndex(f.credential.secrets.Pepper, sealtest.CanaryAddress)).Scan(&owner); e != nil {
+ t.Fatal(e)
+ }
+ for _, role := range []string{"directory", "credential"} {
+ raw := f.plan(t, role, "create-team", []string{"docs"}, func(p *operator.Plan) {
+ p.ExistingTeam = "Uk"
+ if role == "directory" {
+ p.Label = "oficina"
+ }
+ })
+ if r := f.post(role, operatorPlanPath, raw, nil); r.Code != 200 {
+ t.Fatal("plan", role, r.Code)
+ }
+ }
+ cred := f.paulCredential(t)
+ dir := f.paulDirectory(t, cred)
+ for role, session := range map[string]*http.Cookie{"directory": dir, "credential": cred} {
+ page := exchangeRequest(f.app(role), "GET", roleOrigin(role)+operatorConfirm, "", nil, session)
+ for _, want := range []string{"Connect existing apps to a team", "docs.oficina.works", "Uk", "content permissions"} {
+ if !strings.Contains(page.Body.String(), want) {
+ t.Fatalf("%s confirmation omitted %s", role, want)
+ }
+ }
+ if strings.Contains(page.Body.String(), "oficina.docs.oficina.works") {
+ t.Fatal("confirmation displayed a replacement instance")
+ }
+ if role == "credential" && (strings.Contains(page.Body.String(), operatorName) || strings.Contains(page.Body.String(), sealtest.CanaryAddress)) {
+ t.Fatal("credential page rendered account text")
+ }
+ address := ""
+ if role == "credential" {
+ address = sealtest.CanaryAddress
+ }
+ if r := f.confirm(t, role, session, address); r.Code != 200 {
+ t.Fatal("confirmation", role, r.Code)
+ }
+ }
+ r, seed := f.run(t, "credential", "credential.owner-seed", func(b operator.InputBase) any {
+ return operator.OwnerInput{InputBase: b, Directory: directoryOrigin, TeamID: 1, TeamSQID: "Uk", Address: sealtest.CanaryAddress, ExistingOnly: true}
+ })
+ if r.Code != 200 {
+ t.Fatal("owner seed", r.Code)
+ }
+ if r, _ = f.run(t, "directory", "directory.seed-team", func(b operator.InputBase) any {
+ return operator.SeedInput{InputBase: b, Generation: generationToken(), TeamID: 1, TeamSQID: "Uk", Label: "oficina", Name: operatorName, Receipt: seed.Receipt}
+ }); r.Code != 200 {
+ t.Fatal("team seed", r.Code)
+ }
+ r, provision := f.run(t, "directory", "directory.provision-consumer", func(b operator.InputBase) any {
+ return operator.ProvisionInput{InputBase: b, Generation: generationToken(), TeamSQID: "Uk", App: "docs", Consumer: "docs", Audience: "https://docs.oficina.works"}
+ })
+ if r.Code != 200 {
+ t.Fatal("provision", r.Code)
+ }
+ request := f.operation(t, "credential", "credential.register-consumer", func(b operator.InputBase) any { return operator.RegisterInput{InputBase: b, Record: provision.Record} })
+ first := f.post("credential", operatorPath, request, nil)
+ again := f.post("credential", operatorPath, request, nil)
+ if first.Code != 200 || again.Code != 200 || first.Body.String() != again.Body.String() {
+ t.Fatal("registration exact replay", first.Code, again.Code)
+ }
+ var n int
+ if e := f.credential.db.Writer().QueryRow("SELECT count(*) FROM consumers").Scan(&n); e != nil || n != 0 {
+ t.Fatal("registration duplicated", e, n)
+ }
+ if got, ok := f.credential.consumers()["docs"]; !ok || got != "https://docs.oficina.works" {
+ t.Fatal("existing sign-in changed", got, ok)
+ }
+ var registered operator.Result
+ if err := json.Unmarshal(first.Body.Bytes(), &registered); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().Unix()
+ digest := sha256.Sum256(provision.Record)
+ v := operator.VerificationInput{Consumer: "docs", TeamSQID: "Uk", App: "docs", Audience: "https://docs.oficina.works", Generation: generationToken(), RecordSequence: 1, RecordDigest: base64.RawURLEncoding.EncodeToString(digest[:]), Epoch: provision.Epoch, Owner: owner, Issued: now, Expires: now + 600}
+ r, attempt := f.run(t, "directory", "directory.verify-consumer", func(b operator.InputBase) any { v.InputBase = b; return v })
+ if r.Code != 200 {
+ t.Fatal("verify", r.Code)
+ }
+ ev := operator.ActivationEvidence{Version: 1, Policy: "oficina/existing-app-activation/v1", Attempt: attempt.Attempt, Consumer: v.Consumer, TeamSQID: v.TeamSQID, App: v.App, Audience: v.Audience, Generation: v.Generation, RecordSequence: 1, RecordDigest: v.RecordDigest, Epoch: v.Epoch, Owner: owner, AppVersion: strings.Repeat("a", 40), ArtifactDigest: fixtureToken(80), EnvironmentBinding: fixtureToken(81), ManifestDigest: registered.Manifest, AliasHost: "docs.oficina.works", Started: now, Completed: now}
+ if r, _ = f.run(t, "directory", "directory.activate-consumer", func(b operator.InputBase) any { return operator.ActivationInput{InputBase: b, Evidence: ev} }); r.Code != 200 {
+ t.Fatal("activation", r.Code)
+ }
+ store, e := directorydata.New(f.directory.db.Writer(), f.directory.secrets.Sealer, directorydata.Config{Apps: operatorApps(), ValidateRoute: directoryRouteAllowed})
+ if e != nil {
+ t.Fatal(e)
+ }
+ if choices, e := store.AgentChoices(context.Background(), owner); e != nil || len(choices) != 1 || choices[0].ConsumerID != "docs" {
+ t.Fatal("live route", choices, e)
+ }
+ // Home has not granted the unrelated operator team membership merely
+ // because they approved the setup. Local item authority is still app-side.
+ if choices, e := store.AgentChoices(context.Background(), f.paul); e != nil || len(choices) != 0 {
+ t.Fatal("operator gained standing", e)
+ }
+ for _, path := range []string{f.credential.dbPath, f.directoryPath} {
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ b, e := os.ReadFile(path + suffix)
+ if e != nil && !os.IsNotExist(e) {
+ t.Fatal(e)
+ }
+ for _, secret := range []string{sealtest.CanaryAddress, operatorName, string(seed.Receipt), provision.Bearer} {
+ if secret != "" && bytes.Contains(b, []byte(secret)) {
+ t.Fatal("adoption retained private plaintext")
+ }
+ }
+ }
+ }
+ for _, secret := range []string{sealtest.CanaryAddress, operatorName, provision.Bearer} {
+ if strings.Contains(f.logs.String(), secret) {
+ t.Fatal("adoption logged private input")
+ }
+ }
+}
+
+func TestCanonicalDirectoryPolicyIsExact(t *testing.T) {
+ for _, app := range operatorApps() {
+ r := directorydata.Route{TeamID: 1, TeamSQID: "Uk", Label: "oficina", App: app, ConsumerID: app, Origin: "https://" + app + ".oficina.works"}
+ if !directoryRouteAllowed(r) {
+ t.Fatal("canonical tuple refused", app)
+ }
+ for _, edit := range []func(*directorydata.Route){func(r *directorydata.Route) { r.Label = "other" }, func(r *directorydata.Route) { r.ConsumerID = "other" }, func(r *directorydata.Route) { r.Origin = "https://oficina." + app + ".oficina.works" }, func(r *directorydata.Route) { r.Origin += ".evil.test" }} {
+ bad := r
+ edit(&bad)
+ if directoryRouteAllowed(bad) {
+ t.Fatal("canonical substitution admitted", bad)
+ }
+ }
+ }
+}
diff --git a/internal/home/operator_confirm.go b/internal/home/operator_confirm.go
index ae0b90c..e090a1f 100644
--- a/internal/home/operator_confirm.go
+++ b/internal/home/operator_confirm.go
@@ -9,6 +9,7 @@ import (
"strings"
"time"
+ "amadan.net/oficina/home/internal/home/directorydata"
"amadan.net/oficina/home/internal/operator"
"amadan.net/rastrillo/rastrillo/assertion"
"amadan.net/rastrillo/rastrillo/sessions"
@@ -57,13 +58,22 @@ func directoryFresh(s sessions.Session, now time.Time) bool {
type directoryPlanView struct {
ID, Prefix, Kind, Label, Name, Expires string
+ ExistingTeam string
Hosts []string
}
func (a *App) directoryView(v operator.PlanView) directoryPlanView {
out := directoryPlanView{ID: v.ID, Prefix: v.Prefix(), Kind: operatorKinds[v.Kind], Label: v.Label, Name: v.DisplayName, Expires: operatorTime(v.Expires)}
+ out.ExistingTeam = v.ExistingTeam
+ if v.ExistingTeam != "" {
+ out.Kind = "Connect existing apps to a team"
+ }
for _, app := range v.Apps {
- out.Hosts = append(out.Hosts, v.Label+"."+app+".oficina.works")
+ if v.ExistingTeam != "" {
+ out.Hosts = append(out.Hosts, strings.TrimPrefix(directorydata.CanonicalOrigin(app), "https://"))
+ } else {
+ out.Hosts = append(out.Hosts, v.Label+"."+app+".oficina.works")
+ }
}
return out
}
@@ -207,16 +217,25 @@ func (a *App) credentialOperatorSession(w http.ResponseWriter, r *http.Request)
type credentialPlanView struct {
ID, Prefix, Kind, Owner, Expires string
+ ExistingTeam string
Apps []string
}
func credentialView(v operator.PlanView) credentialPlanView {
out := credentialPlanView{ID: v.ID, Prefix: v.Prefix(), Kind: operatorKinds[v.Kind], Expires: operatorTime(v.Expires)}
+ out.ExistingTeam = v.ExistingTeam
+ if v.ExistingTeam != "" {
+ out.Kind = "Connect existing apps to a team"
+ }
if len(v.OwnerIndex) >= 8 {
out.Owner = v.OwnerIndex[:8]
}
for _, app := range v.Apps {
- out.Apps = append(out.Apps, appName(app))
+ name := appName(app)
+ if v.ExistingTeam != "" {
+ name += " (" + strings.TrimPrefix(directorydata.CanonicalOrigin(app), "https://") + ")"
+ }
+ out.Apps = append(out.Apps, name)
}
return out
}
diff --git a/internal/home/operator_http_test.go b/internal/home/operator_http_test.go
index 07b8c05..b8b3016 100644
--- a/internal/home/operator_http_test.go
+++ b/internal/home/operator_http_test.go
@@ -80,6 +80,10 @@ var credentialActions = []string{"credential.owner-seed", "credential.register-c
var directoryActions = []string{"directory.inspect", "directory.initialize", "directory.seed-team", "directory.provision-consumer", "directory.verify-consumer", "directory.activate-consumer", "directory.disable-consumer"}
func newOperatorFixture(t *testing.T) *operatorFixture {
+ return newOperatorFixtureConsumers(t, nil)
+}
+
+func newOperatorFixtureConsumers(t *testing.T, consumers map[string]string) *operatorFixture {
t.Helper()
f := &operatorFixture{paulAddress: operatorPaul, opByte: 40, logs: new(bytes.Buffer)}
logger := slog.New(slog.NewTextHandler(f.logs, nil))
@@ -115,6 +119,9 @@ func newOperatorFixture(t *testing.T) *operatorFixture {
key, _ := family.Generate()
kid := hexID(key)
ccfg := Runtime{role: "credential", origins: Origins{Origin, directoryOrigin}, secrets: secrets, signer: key, keyID: kid, keys: map[string][]byte{kid: key.SignPub()}, consumers: map[string]string{"directory": directoryOrigin, "team_docs": "https://blue.docs.oficina.works", "preview": "https://preview.example.test"}, resolveSigner: f.resolve}
+ for id, origin := range consumers {
+ ccfg.consumers[id] = origin
+ }
t.Setenv("HOME_OPERATOR_HTTP", operatorHTTPJSON(t, "credential", Origin, f.alta, f.paul, prefilterSum, credentialActions, rawURLPub(f.provisioning)))
t.Setenv("HOME_OPERATOR_MATERIAL", `{"version":1,"role":"credential","mac_key":"`+base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))+`","owner_seed_key":"`+encodedKeypair(t, f.ownerSeed)+`"}`)
if err = loadOperatorHTTP(&ccfg); err != nil || ccfg.operator == nil {
diff --git a/internal/home/templates/operator_confirm.html b/internal/home/templates/operator_confirm.html
index d469c9b..0e12dbe 100644
--- a/internal/home/templates/operator_confirm.html
+++ b/internal/home/templates/operator_confirm.html
@@ -10,11 +10,13 @@
<dl>
<dt>Plan</dt><dd><code>{{.Prefix}}</code></dd>
<dt>Kind</dt><dd>{{.Kind}}</dd>
+ {{if .ExistingTeam}}<dt>Team ID</dt><dd><code>{{.ExistingTeam}}</code></dd>{{end}}
{{if .Label}}<dt>Label</dt><dd><code>{{.Label}}</code></dd>{{end}}
{{if .Name}}<dt>Name</dt><dd>{{.Name}}</dd>{{end}}
{{if .Hosts}}<dt>Apps</dt><dd><ul>{{range .Hosts}}<li><code>{{.}}</code></li>{{end}}</ul></dd>{{end}}
<dt>Expires</dt><dd>{{.Expires}}</dd>
</dl>
+{{if .ExistingTeam}}<p>Connect these existing apps while keeping their data, sign-in settings and content permissions. Team membership alone does not give access to existing content.</p>{{end}}
<form method="post" action="/operator/confirm" rst-form>
<input type="hidden" name="plan" value="{{.ID}}">
<div rst-form-foot>
diff --git a/internal/home/templates/operator_confirm_id.html b/internal/home/templates/operator_confirm_id.html
index f4918bc..080002a 100644
--- a/internal/home/templates/operator_confirm_id.html
+++ b/internal/home/templates/operator_confirm_id.html
@@ -11,10 +11,12 @@
<dl>
<dt>Plan</dt><dd><code>{{.Prefix}}</code></dd>
<dt>Kind</dt><dd>{{.Kind}}</dd>
+ {{if .ExistingTeam}}<dt>Team ID</dt><dd><code>{{.ExistingTeam}}</code></dd>{{end}}
<dt>Apps</dt><dd>{{range $i, $a := .Apps}}{{if $i}}, {{end}}{{$a}}{{end}}</dd>
{{if .Owner}}<dt>Owner</dt><dd><code>{{.Owner}}</code></dd>{{end}}
<dt>Expires</dt><dd>{{.Expires}}</dd>
</dl>
+{{if .ExistingTeam}}<p>Verify the existing sign-in registrations for these apps. Their data and content permissions stay as they are.</p>{{end}}
<form method="post" action="/operator/confirm" rst-form>
<input type="hidden" name="plan" value="{{.ID}}">
{{if .Owner}}<div rst-field>
diff --git a/internal/operator/directory.go b/internal/operator/directory.go
index 2bc5edb..2d26534 100644
--- a/internal/operator/directory.go
+++ b/internal/operator/directory.go
@@ -211,10 +211,17 @@ func (d *Directory) seed(ctx context.Context, c *sql.Conn, r Request) ([]byte, e
// memberships.added_at. The native command's selected-release schema has no
// such column, so its path writes the original three columns.
func (d *Directory) seedTeam(ctx context.Context, c *sql.Conn, r Request, addedAt bool) ([]byte, error) {
+ return d.seedTeamForWindow(ctx, c, r, addedAt, "")
+}
+
+func (d *Directory) seedTeamForWindow(ctx context.Context, c *sql.Conn, r Request, addedAt bool, existingTeam string) ([]byte, error) {
var in SeedInput
if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || !validTeam(in.TeamID, in.TeamSQID) {
return nil, ErrRefused
}
+ if (in.Label == "oficina") != (existingTeam != "") || (existingTeam != "" && in.TeamSQID != existingTeam) {
+ return nil, ErrRefused
+ }
if e := generation(ctx, c, in.Generation); e != nil {
return nil, e
}
@@ -282,6 +289,10 @@ func (d *Directory) seedTeam(ctx context.Context, c *sql.Conn, r Request, addedA
return encode(result)
}
func (d *Directory) provision(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
+ return d.provisionForWindow(ctx, c, r, "")
+}
+
+func (d *Directory) provisionForWindow(ctx context.Context, c *sql.Conn, r Request, existingTeam string) ([]byte, error) {
var in ProvisionInput
if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial || in.Sequence != 0 || !d.apps[in.App] || !atom(in.Consumer, 64) || !Origin(in.Audience) {
return nil, ErrRefused
@@ -300,6 +311,9 @@ func (d *Directory) provision(ctx context.Context, c *sql.Conn, r Request) ([]by
if !validTeam(route.TeamID, route.TeamSQID) || !d.policy.ValidateRoute(route) || epoch <= 0 {
return nil, ErrRefused
}
+ if !routeScope(existingTeam, route.Label, in.TeamSQID, in.App, in.Consumer, in.Audience) {
+ return nil, ErrRefused
+ }
var owner string
if e := c.QueryRowContext(ctx, "SELECT person_ref FROM memberships WHERE team_id=? AND role='owner' LIMIT 1", route.TeamID).Scan(&owner); e != nil || !PersonRef(owner) {
return nil, ErrRefused
diff --git a/internal/operator/existing.go b/internal/operator/existing.go
new file mode 100644
index 0000000..17b9abb
--- /dev/null
+++ b/internal/operator/existing.go
@@ -0,0 +1,14 @@
+package operator
+
+import "amadan.net/oficina/home/internal/home/directorydata"
+
+// routeScope separates existing-instance adoption from ordinary provisioning.
+// existingTeam comes only from Home's confirmed plan, never operation input.
+func routeScope(existingTeam, label, team, app, consumer, origin string) bool {
+ if existingTeam == "" {
+ return label != "oficina" && origin != directorydata.CanonicalOrigin(app)
+ }
+ return validTeamSQID(existingTeam) && team == existingTeam && directorydata.CanonicalBinding(label, app, consumer, origin)
+}
+
+const existingActivationPolicy = "oficina/existing-app-activation/v1"
diff --git a/internal/operator/existing_migration_test.go b/internal/operator/existing_migration_test.go
new file mode 100644
index 0000000..f313d80
--- /dev/null
+++ b/internal/operator/existing_migration_test.go
@@ -0,0 +1,71 @@
+package operator
+
+import (
+ "bytes"
+ "context"
+ "path/filepath"
+ "testing"
+ "testing/fstest"
+ "time"
+
+ sharedseal "amadan.net/oficina/home/handoff/seal"
+ rdb "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+func TestExistingPlanMigrationPreservesOldPendingAndOpen(t *testing.T) {
+ for _, role := range []string{"credential", "directory"} {
+ t.Run(role, func(t *testing.T) {
+ ctx := context.Background()
+ db, err := rdb.Open(filepath.Join(t.TempDir(), "old.db"), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ old, err := httpMigrations.ReadFile("http_migrations/" + role + "/migrations/0001_operator_http.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fs := fstest.MapFS{"migrations/0001_operator_http.sql": &fstest.MapFile{Data: old}}
+ if _, err = migrate.Apply(ctx, db, migrate.MustFromFS(fs, "oficina_"+role+"_operator_http")); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Unix(2000000000, 0)
+ for i, state := range []string{"pending", "open"} {
+ var window any
+ if state == "open" {
+ window = now.Unix() + 600
+ }
+ if role == "credential" {
+ _, err = db.Writer().Exec("INSERT INTO operator_plans(plan_id,state,kind,apps,expires_at,window_expires_at) VALUES(?,?,'add-apps','docs',?,?)", token(byte(i+20)), state, now.Unix()+600, window)
+ } else {
+ _, err = db.Writer().Exec("INSERT INTO operator_plans(plan_id,state,kind,label,apps,expires_at,window_expires_at) VALUES(?,?,'add-apps','alpha','docs',?,?)", token(byte(i+20)), state, now.Unix()+600, window)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err = migrate.Apply(ctx, db, httpSchema(role)); err != nil {
+ t.Fatal("upgrade", err)
+ }
+ sealer, _ := sharedseal.New(bytes.Repeat([]byte{6}, 32), "oficina/operator")
+ store, _ := NewPlanStore(db.Writer(), role, sealer)
+ pending, err := store.Pending(ctx, now)
+ if err != nil || pending.ExistingTeam != "" || pending.Kind != "add-apps" {
+ t.Fatal("old plan changed", err)
+ }
+ conn, err := db.Writer().Conn(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ opened, _, err := window(ctx, conn, role, now.Unix())
+ conn.Close()
+ if err != nil || opened.ExistingTeam != "" || opened.State != "open" {
+ t.Fatal("old window changed", err)
+ }
+ if err = store.Sweep(ctx, now.Add(600*time.Second)); err != nil || countRows(t, db.Writer(), "operator_plans") != 0 {
+ t.Fatal("expiry", err)
+ }
+ })
+ }
+}
diff --git a/internal/operator/existing_test.go b/internal/operator/existing_test.go
new file mode 100644
index 0000000..e38f059
--- /dev/null
+++ b/internal/operator/existing_test.go
@@ -0,0 +1,389 @@
+package operator
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/internal/home/directorydata"
+ "amadan.net/oficina/home/roster"
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "github.com/go-json-experiment/json"
+)
+
+func adoptionRoute(r directorydata.Route) bool {
+ if r.Label == "oficina" {
+ return directorydata.CanonicalBinding(r.Label, r.App, r.ConsumerID, r.Origin)
+ }
+ return r.Origin == "https://"+r.Label+"."+r.App+".oficina.works"
+}
+
+func adoptionDirectory(t *testing.T) *httpDirectory {
+ t.Helper()
+ f := newHTTPDirectory(t)
+ f.directory.policy.ValidateRoute = adoptionRoute
+ f.openPlan(t, func(p *Plan) { p.Kind, p.Apps, p.Label, p.DisplayName = "initialize", nil, "", "" })
+ if _, e := f.run(t, "directory.initialize", func(b InputBase) any {
+ return InitializeInput{b, nil, token(10), "operator-attests-never-provisioned"}
+ }); e != nil {
+ t.Fatal(e)
+ }
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, func(p *Plan) { p.Label, p.ExistingTeam = "oficina", "Uk" })
+ return f
+}
+
+func adoptionPending(t *testing.T) (*httpDirectory, VerificationInput) {
+ t.Helper()
+ f := adoptionDirectory(t)
+ if _, e := f.seedHTTP(t, 1, "oficina", "PRIVATE-TEAM-NAME-CANARY"); e != nil {
+ t.Fatal(e)
+ }
+ raw := f.input(t, "directory.provision-consumer", func(b InputBase) any {
+ return ProvisionInput{b, token(10), "Uk", "docs", "docs", "https://docs.oficina.works", 0}
+ })
+ out, e := f.directory.ExecuteHTTP(context.Background(), raw)
+ if e != nil {
+ t.Fatal(e)
+ }
+ again, e := f.directory.ExecuteHTTP(context.Background(), raw)
+ if e != nil || !bytes.Equal(out, again) || countRows(t, f.db, "roster_consumers") != 1 {
+ t.Fatal("provision replay", e)
+ }
+ var result Result
+ if json.Unmarshal(out, &result) != nil {
+ t.Fatal("result")
+ }
+ f.bearer = result.Bearer
+ var digest []byte
+ if e = f.db.QueryRow("SELECT record_digest FROM directory_operator_consumer_records").Scan(&digest); e != nil {
+ t.Fatal(e)
+ }
+ return f, VerificationInput{Consumer: "docs", TeamSQID: "Uk", App: "docs", Audience: "https://docs.oficina.works", Generation: token(10), RecordSequence: 1, RecordDigest: base64.RawURLEncoding.EncodeToString(digest), Epoch: 2, Owner: "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", Issued: f.now.Unix(), Expires: f.now.Unix() + 600}
+}
+
+func TestExistingPlanScopePersistenceAndExpiry(t *testing.T) {
+ f := newHTTPDirectory(t)
+ p, raw := f.signPlan(t, func(p *Plan) { p.Label, p.ExistingTeam = "oficina", "Uk" })
+ verified, e := f.engine.verifier.VerifyPlan(raw, httpApps, *f.now)
+ if e != nil || verified.ExistingTeam != "Uk" {
+ t.Fatal(e)
+ }
+ if e = f.plans.Submit(context.Background(), p, "", *f.now); e != nil {
+ t.Fatal(e)
+ }
+ // A new reader, as after restart, must see the stored scope.
+ reopened, _ := NewPlanStore(f.db, "directory", f.engine.sealer)
+ v, e := reopened.Pending(context.Background(), *f.now)
+ if e != nil || v.ExistingTeam != "Uk" {
+ t.Fatal("scope not durable", e)
+ }
+ if _, e = reopened.Open(context.Background(), p.PlanID, *f.now, func(v PlanView) bool { return v.ExistingTeam == "Uk" }); e != nil {
+ t.Fatal(e)
+ }
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ if e = reopened.Sweep(context.Background(), *f.now); e != nil || countRows(t, f.db, "operator_plans") != 0 {
+ t.Fatal("scope survived expiry", e)
+ }
+ for name, edit := range map[string]func(*Plan){
+ "label": func(p *Plan) { p.Label = "other" }, "retire": func(p *Plan) { p.Kind = "retire-apps"; p.DisplayName = "" },
+ "initialize": func(p *Plan) { p.Kind = "initialize"; p.Label = ""; p.Apps = nil; p.DisplayName = "" },
+ "invalid-sqid": func(p *Plan) { p.ExistingTeam = "oficina" }, "zero-sqid": func(p *Plan) { p.ExistingTeam = "bM" },
+ "ordinary-create-reserved": func(p *Plan) { p.ExistingTeam = "" },
+ "ordinary-add-reserved": func(p *Plan) { p.ExistingTeam = ""; p.Kind = "add-apps"; p.DisplayName = "" },
+ "unknown-app": func(p *Plan) { p.Apps = []string{"unknown"} },
+ } {
+ t.Run(name, func(t *testing.T) {
+ q := p
+ edit(&q)
+ if _, e := SignPlan(f.key, q, append(httpApps, "unknown")); e != ErrRefused {
+ t.Fatal("invalid adoption scope admitted", e)
+ }
+ })
+ }
+}
+
+func TestExistingReservedLabelAndNativeWritesRefused(t *testing.T) {
+ f := newDirectoryFixture(t)
+ f.initialize(t)
+ if _, e := f.seed(t, 1, "oficina"); e != ErrRefused {
+ t.Fatal("native seed claimed reserved label", e)
+ }
+ h := adoptionDirectory(t)
+ if _, e := h.seedHTTP(t, 2, "oficina", "PRIVATE-TEAM-NAME-CANARY"); e != ErrRefused {
+ t.Fatal("different valid seed team", e)
+ }
+ if _, e := h.seedHTTP(t, 1, "oficina", "PRIVATE-TEAM-NAME-CANARY"); e != nil {
+ t.Fatal(e)
+ }
+ for name, edit := range map[string]func(*ProvisionInput){
+ "team": func(p *ProvisionInput) { p.TeamSQID = "gb" }, "consumer": func(p *ProvisionInput) { p.Consumer = "other" },
+ "new-origin": func(p *ProvisionInput) { p.Audience = "https://oficina.docs.oficina.works" },
+ "other-app-origin": func(p *ProvisionInput) { p.Audience = "https://sheets.oficina.works" },
+ } {
+ t.Run(name, func(t *testing.T) {
+ _, e := h.run(t, "directory.provision-consumer", func(b InputBase) any {
+ p := ProvisionInput{b, token(10), "Uk", "docs", "docs", "https://docs.oficina.works", 0}
+ edit(&p)
+ return p
+ })
+ if e != ErrRefused {
+ t.Fatal(e)
+ }
+ })
+ }
+ raw := h.input(t, "directory.provision-consumer", func(b InputBase) any {
+ return ProvisionInput{b, token(10), "Uk", "docs", "docs", "https://docs.oficina.works", 0}
+ })
+ if _, e := h.directory.Execute(context.Background(), raw); e != ErrRefused {
+ t.Fatal("native canonical provision", e)
+ }
+}
+
+func TestExistingActivationDiscoveryAndRevocation(t *testing.T) {
+ f, in := adoptionPending(t)
+ store, e := directorydata.New(f.db, f.engine.sealer, directorydata.Config{Apps: httpApps, ValidateRoute: adoptionRoute})
+ if e != nil {
+ t.Fatal(e)
+ }
+ if choices, e := store.AgentChoices(context.Background(), in.Owner); e != nil || len(choices) != 0 {
+ t.Fatal("pending visible", e)
+ }
+ wrong := in
+ wrong.TeamSQID = "gb"
+ if _, e = f.run(t, "directory.verify-consumer", func(b InputBase) any { wrong.InputBase = b; return wrong }); e != ErrRefused {
+ t.Fatal("wrong verify team", e)
+ }
+ raw := f.input(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in })
+ if _, e = f.directory.Execute(context.Background(), raw); e != ErrRefused {
+ t.Fatal("native canonical verification", e)
+ }
+ out, e := f.directory.ExecuteHTTP(context.Background(), raw)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var window Result
+ if json.Unmarshal(out, &window) != nil {
+ t.Fatal("verify result")
+ }
+ ev := activation(in, window.Attempt)
+ ev.AliasHost = "docs.oficina.works"
+ if _, e = f.run(t, "directory.activate-consumer", func(b InputBase) any { return ActivationInput{b, ev} }); e != ErrRefused {
+ t.Fatal("new-instance policy on existing app", e)
+ }
+ ev.Policy = existingActivationPolicy
+ for name, edit := range map[string]func(*ActivationEvidence){"team": func(e *ActivationEvidence) { e.TeamSQID = "gb" }, "origin": func(e *ActivationEvidence) { e.Audience = "https://oficina.docs.oficina.works" }, "manifest": func(e *ActivationEvidence) { e.ManifestDigest = "" }} {
+ t.Run(name, func(t *testing.T) {
+ p := ev
+ edit(&p)
+ if _, e := f.run(t, "directory.activate-consumer", func(b InputBase) any { return ActivationInput{b, p} }); e != ErrRefused {
+ t.Fatal(e)
+ }
+ })
+ }
+ raw = f.input(t, "directory.activate-consumer", func(b InputBase) any { return ActivationInput{b, ev} })
+ if _, e = f.directory.Execute(context.Background(), raw); e != ErrRefused {
+ t.Fatal("native adoption activation", e)
+ }
+ out, e = f.directory.ExecuteHTTP(context.Background(), raw)
+ if e != nil {
+ t.Fatal(e)
+ }
+ again, e := f.directory.ExecuteHTTP(context.Background(), raw)
+ if e != nil || !bytes.Equal(out, again) {
+ t.Fatal("activation replay", e)
+ }
+ choices, e := store.AgentChoices(context.Background(), in.Owner)
+ if e != nil || len(choices) != 1 || choices[0].Origin != in.Audience {
+ t.Fatal("live canonical discovery", e, choices)
+ }
+ // The old reader cannot consume these rows. Only an adoption-capable
+ // build is a valid post-activation rollback target.
+ old, _ := directorydata.New(f.db, f.engine.sealer, directorydata.Config{Apps: httpApps, ValidateRoute: func(r directorydata.Route) bool { return r.Origin == "https://"+r.Label+"."+r.App+".oficina.works" }})
+ if _, e = old.AgentChoices(context.Background(), in.Owner); e != directorydata.ErrUnavailable {
+ t.Fatal("old reader compatibility unexpectedly changed", e)
+ }
+ compatible, _ := directorydata.New(f.db, f.engine.sealer, directorydata.Config{Apps: httpApps, ValidateRoute: adoptionRoute})
+ if choices, e = compatible.AgentChoices(context.Background(), in.Owner); e != nil || len(choices) != 1 {
+ t.Fatal("compatible rollback reader", e)
+ }
+ if _, e = f.db.Exec("DELETE FROM memberships WHERE person_ref=?", in.Owner); e != nil {
+ t.Fatal(e)
+ }
+ if choices, e = store.AgentChoices(context.Background(), in.Owner); e != nil || len(choices) != 0 {
+ t.Fatal("removed member retained discovery", e)
+ }
+}
+
+func openCredentialAdoption(t *testing.T, f *httpCredential) {
+ openCredentialAdoptionPlan(t, f, "create-team", "Uk", "docs")
+}
+
+func openCredentialAdoptionPlan(t *testing.T, f *httpCredential, kind, team string, apps ...string) {
+ t.Helper()
+ p := Plan{Version: 1, Purpose: "operator-plan", Role: "credential", Origin: f.auth.Origin, Installation: token(1), Registry: token(2), Device: token(3), PlanID: token(f.attempt + 100), Kind: kind, Apps: apps, ExistingTeam: team, Issued: f.now.Unix(), Expires: f.now.Unix() + 600}
+ index := ""
+ if kind == "create-team" {
+ p.Owner = ownerCanary
+ index = credentialIndex(f.pepper, ownerCanary)
+ }
+ raw, e := SignPlan(f.key, p, httpApps)
+ if e != nil {
+ t.Fatal(e)
+ }
+ p, e = f.http.c.engine.verifier.VerifyPlan(raw, httpApps, *f.now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = f.plans.Submit(context.Background(), p, index, *f.now); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = f.plans.Open(context.Background(), p.PlanID, *f.now, func(v PlanView) bool { return v.ExistingTeam == team && (kind != "add-apps" || v.OwnerIndex == "") }); e != nil {
+ t.Fatal(e)
+ }
+}
+
+func TestExistingAddAppsKeepsTeamAndRegistrations(t *testing.T) {
+ f, _ := adoptionPending(t)
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, func(p *Plan) {
+ p.Kind, p.Label, p.DisplayName, p.ExistingTeam, p.Apps = "add-apps", "oficina", "", "Uk", []string{"sheets"}
+ })
+ out, e := f.run(t, "directory.provision-consumer", func(b InputBase) any {
+ return ProvisionInput{b, token(10), "Uk", "sheets", "sheets", "https://sheets.oficina.works", 0}
+ })
+ if e != nil {
+ t.Fatal("add canonical app", e)
+ }
+ if countRows(t, f.db, "teams") != 1 || countRows(t, f.db, "memberships") != 1 || countRows(t, f.db, "team_instances") != 2 {
+ t.Fatal("add apps replaced the team")
+ }
+ var result Result
+ if json.Unmarshal(out, &result) != nil {
+ t.Fatal("provision result")
+ }
+ c := newHTTPCredential(t)
+ c.http.env["sheets"] = "https://sheets.oficina.works"
+ openCredentialAdoption(t, c)
+ if _, e = c.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil {
+ t.Fatal(e)
+ }
+ *c.now = c.now.Add(WindowLifetime * time.Second)
+ openCredentialAdoptionPlan(t, c, "add-apps", "Uk", "sheets")
+ // Use the actual directory record and signer. Both fixtures share the
+ // canonical issuer/directory; this tests derivative verification too.
+ c.http.provisioning = []roster.Key{{ID: keyID(f.directory.signer.SignPub()), Public: base64.RawURLEncoding.EncodeToString(f.directory.signer.SignPub())}}
+ out, e = c.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, result.Record} })
+ if e != nil {
+ t.Fatal("existing sheets registration", e)
+ }
+ var registered Result
+ if json.Unmarshal(out, &registered) != nil {
+ t.Fatal("register result")
+ }
+ want, _ := ManifestDigest(c.http.env)
+ if registered.Manifest != want || countRows(t, c.db, "consumers") != 0 {
+ t.Fatal("add-apps modified registry")
+ }
+}
+
+func TestExistingConfirmedTeamScopeIsIndependentOfStoredTeam(t *testing.T) {
+ t.Run("seed", func(t *testing.T) {
+ f := adoptionDirectory(t)
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, func(p *Plan) { p.Label, p.ExistingTeam = "oficina", "gb" })
+ if _, e := f.seedHTTP(t, 1, "oficina", "PRIVATE-TEAM-NAME-CANARY"); e != ErrRefused {
+ t.Fatal("valid next team escaped confirmed scope", e)
+ }
+ })
+ t.Run("provision", func(t *testing.T) {
+ f, _ := adoptionPending(t)
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, func(p *Plan) {
+ p.Kind, p.Label, p.DisplayName, p.ExistingTeam, p.Apps = "add-apps", "oficina", "", "gb", []string{"sheets"}
+ })
+ if _, e := f.run(t, "directory.provision-consumer", func(b InputBase) any {
+ return ProvisionInput{b, token(10), "Uk", "sheets", "sheets", "https://sheets.oficina.works", 0}
+ }); e != ErrRefused {
+ t.Fatal("valid stored team escaped confirmed scope", e)
+ }
+ })
+ t.Run("verify", func(t *testing.T) {
+ f, in := adoptionPending(t)
+ *f.now = f.now.Add(WindowLifetime * time.Second)
+ f.openPlan(t, func(p *Plan) { p.Kind, p.Label, p.DisplayName, p.ExistingTeam = "add-apps", "oficina", "", "gb" })
+ in.Issued = f.now.Unix()
+ in.Expires = in.Issued + 600
+ if _, e := f.run(t, "directory.verify-consumer", func(b InputBase) any { in.InputBase = b; return in }); e != ErrRefused {
+ t.Fatal("valid pending binding escaped confirmed scope", e)
+ }
+ })
+}
+
+func TestExistingRegistrationPreservesManifestAndOwnerScope(t *testing.T) {
+ f := newHTTPCredential(t)
+ openCredentialAdoption(t, f)
+ if _, e := f.run(t, "credential.owner-seed", func(b InputBase) any { return OwnerInput{b, "https://oficina.works", 2, "gb", ownerCanary, true} }); e != ErrRefused {
+ t.Fatal("different owner-seed team", e)
+ }
+ if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil {
+ t.Fatal(e)
+ }
+ record := f.record(t, f.dirKey, "docs", "docs", "https://docs.oficina.works")
+ out, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, record} })
+ if e != nil {
+ t.Fatal(e)
+ }
+ var result Result
+ if json.Unmarshal(out, &result) != nil {
+ t.Fatal("result")
+ }
+ want, _ := ManifestDigest(f.http.env)
+ if result.Manifest != want || countRows(t, f.db, "consumers") != 0 || f.http.env["docs"] != "https://docs.oficina.works" {
+ t.Fatal("existing registration changed")
+ }
+}
+
+func TestExistingRegistrationRejectsSubstitutions(t *testing.T) {
+ for _, name := range []string{"missing", "wrong-origin", "wrong-id", "table-clash", "wrong-key", "new-origin", "other-team", "ordinary-window"} {
+ t.Run(name, func(t *testing.T) {
+ f := newHTTPCredential(t)
+ if name == "ordinary-window" {
+ f.openPlan(t, "create-team", "docs")
+ } else {
+ openCredentialAdoption(t, f)
+ }
+ if _, e := f.run(t, "credential.owner-seed", ownerSeedInput(ownerCanary, true)); e != nil {
+ t.Fatal(e)
+ }
+ key := f.dirKey
+ consumer, origin := "docs", "https://docs.oficina.works"
+ switch name {
+ case "missing":
+ delete(f.http.env, "docs")
+ case "wrong-origin":
+ f.http.env["docs"] = "https://other.docs.oficina.works"
+ case "wrong-id":
+ consumer = "other"
+ case "table-clash":
+ if _, e := f.db.Exec("INSERT INTO consumers VALUES('docs','https://other.docs.oficina.works','docs','active','2026-11-02',?)", token(85)); e != nil {
+ t.Fatal(e)
+ }
+ case "wrong-key":
+ key, _ = family.Generate()
+ case "new-origin":
+ origin = "https://oficina.docs.oficina.works"
+ case "other-team":
+ if _, e := f.db.Exec("UPDATE operator_plans SET existing_team='gb'"); e != nil {
+ t.Fatal(e)
+ }
+ }
+ record := f.record(t, key, consumer, "docs", origin)
+ if _, e := f.run(t, "credential.register-consumer", func(b InputBase) any { return RegisterInput{b, record} }); e != ErrRefused {
+ t.Fatal("substitution admitted", e)
+ }
+ })
+ }
+}
diff --git a/internal/operator/http_migrations/credential/migrations/0002_existing_team.sql b/internal/operator/http_migrations/credential/migrations/0002_existing_team.sql
new file mode 100644
index 0000000..05a6656
--- /dev/null
+++ b/internal/operator/http_migrations/credential/migrations/0002_existing_team.sql
@@ -0,0 +1,2 @@
+ALTER TABLE operator_plans ADD COLUMN existing_team TEXT NOT NULL DEFAULT ''
+ CHECK(existing_team='' OR (kind IN ('create-team','add-apps') AND length(existing_team) BETWEEN 1 AND 64 AND existing_team NOT GLOB '*[^a-zA-Z0-9]*'));
diff --git a/internal/operator/http_migrations/directory/migrations/0002_existing_team.sql b/internal/operator/http_migrations/directory/migrations/0002_existing_team.sql
new file mode 100644
index 0000000..7b686bd
--- /dev/null
+++ b/internal/operator/http_migrations/directory/migrations/0002_existing_team.sql
@@ -0,0 +1,2 @@
+ALTER TABLE operator_plans ADD COLUMN existing_team TEXT NOT NULL DEFAULT ''
+ CHECK(existing_team='' OR (kind IN ('create-team','add-apps') AND label='oficina' AND length(existing_team) BETWEEN 1 AND 64 AND existing_team NOT GLOB '*[^a-zA-Z0-9]*'));
diff --git a/internal/operator/http_verbs.go b/internal/operator/http_verbs.go
index dc1aa44..2a0fe41 100644
--- a/internal/operator/http_verbs.go
+++ b/internal/operator/http_verbs.go
@@ -12,6 +12,7 @@ import (
"slices"
"time"
+ "amadan.net/oficina/home/internal/home/directorydata"
"amadan.net/oficina/home/roster"
"github.com/go-json-experiment/json"
"github.com/go-json-experiment/json/jsontext"
@@ -89,7 +90,7 @@ func (d *Directory) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error)
if !bytes.Equal(name, []byte(in.Name)) {
return nil, ErrRefused
}
- out, e := d.seedTeam(ctx, c, r, true)
+ out, e := d.seedTeamForWindow(ctx, c, r, true, w.ExistingTeam)
if e != nil {
return nil, e
}
@@ -109,25 +110,25 @@ func (d *Directory) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, error)
if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil {
return nil, e
}
- return d.provision(ctx, c, r)
+ return d.provisionForWindow(ctx, c, r, w.ExistingTeam)
case "directory.verify-consumer":
var in VerificationInput
- if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) {
+ if DecodeInput(r, &in) != nil || !contains(w.Apps, in.App) || !routeScope(w.ExistingTeam, w.Label, in.TeamSQID, in.App, in.Consumer, in.Audience) {
return nil, ErrRefused
}
if _, e := fence(ctx, c, in.TeamSQID, w.Label); e != nil {
return nil, e
}
- return d.verifyConsumer(ctx, c, r)
+ return d.verifyConsumerForWindow(ctx, c, r, w.ExistingTeam)
case "directory.activate-consumer":
var in ActivationInput
- if DecodeInput(r, &in) != nil || !contains(w.Apps, in.Evidence.App) {
+ if DecodeInput(r, &in) != nil || !contains(w.Apps, in.Evidence.App) || !routeScope(w.ExistingTeam, w.Label, in.Evidence.TeamSQID, in.Evidence.App, in.Evidence.Consumer, in.Evidence.Audience) {
return nil, ErrRefused
}
if _, e := fence(ctx, c, in.Evidence.TeamSQID, w.Label); e != nil {
return nil, e
}
- return d.activate(ctx, c, r)
+ return d.activateForWindow(ctx, c, r, w.ExistingTeam)
case "directory.disable-consumer":
return d.disable(ctx, c, r, w)
}
@@ -259,6 +260,9 @@ func (h *CredentialHTTP) ExecuteHTTP(ctx context.Context, raw []byte) ([]byte, e
if DecodeInput(r, &in) != nil || !in.ExistingOnly || !ownerAddress(in.Address) || !hmac.Equal([]byte(h.ownerIndex(in.Address)), []byte(w.OwnerIndex)) {
return nil, ErrRefused
}
+ if w.ExistingTeam != "" && in.TeamSQID != w.ExistingTeam {
+ return nil, ErrRefused
+ }
return c.ownerSeed(ctx, conn, r)
case "credential.register-consumer":
return h.register(ctx, conn, r, w)
@@ -309,6 +313,25 @@ func (h *CredentialHTTP) register(ctx context.Context, c *sql.Conn, r Request, w
if !h.apps[b.App] || !contains(w.Apps, b.App) || !atom(b.Consumer, 64) || !Origin(b.Audience) || !h.admit(b.Consumer, b.Audience) {
return nil, ErrRefused
}
+ if w.ExistingTeam != "" {
+ if b.Team != w.ExistingTeam || !directorydata.CanonicalBinding("oficina", b.App, b.Consumer, b.Audience) || h.env[b.Consumer] != b.Audience {
+ return nil, ErrRefused
+ }
+ for id, origin := range h.env {
+ if id != b.Consumer && origin == b.Audience {
+ return nil, ErrRefused
+ }
+ }
+ var clash int
+ if c.QueryRowContext(ctx, "SELECT count(*) FROM consumers WHERE consumer_id=? OR origin=?", b.Consumer, b.Audience).Scan(&clash) != nil {
+ return nil, ErrUnavailable
+ }
+ if clash != 0 {
+ return nil, ErrRefused
+ }
+ // Verify the existing registration; never duplicate it in the table.
+ return h.manifestResult(ctx, c, r)
+ }
for id, origin := range h.env {
if id == b.Consumer || origin == b.Audience {
return nil, ErrRefused
diff --git a/internal/operator/owner.go b/internal/operator/owner.go
index 533acc4..19faf6c 100644
--- a/internal/operator/owner.go
+++ b/internal/operator/owner.go
@@ -2,6 +2,7 @@ package operator
import (
"encoding/base64"
+ "math"
"strings"
"time"
@@ -27,6 +28,14 @@ func validTeam(id int64, s string) bool {
expected, e := TeamSQID(id)
return e == nil && s == expected
}
+
+func validTeamSQID(s string) bool {
+ if teamCodecError != nil || len(s) == 0 || len(s) > 64 {
+ return false
+ }
+ ids := teamCodec.Decode(s)
+ return len(ids) == 1 && ids[0] > 0 && ids[0] <= math.MaxInt64 && validTeam(int64(ids[0]), s)
+}
func PersonRef(s string) bool {
if len(s) != 29 || !strings.HasPrefix(s, "pr_") {
return false
diff --git a/internal/operator/plan.go b/internal/operator/plan.go
index 921300b..6cdd75f 100644
--- a/internal/operator/plan.go
+++ b/internal/operator/plan.go
@@ -68,6 +68,7 @@ type Plan struct {
Label string `json:"label,omitzero"`
DisplayName string `json:"display_name,omitzero"`
Owner string `json:"owner,omitzero"`
+ ExistingTeam string `json:"existing_team,omitzero"`
Issued int64 `json:"issued_at"`
Expires int64 `json:"expires_at"`
}
@@ -109,6 +110,18 @@ func (p Plan) valid(apps map[string]bool) bool {
if p.Version != 1 || p.Purpose != "operator-plan" || !planKind(p.Role, p.Kind) || !Origin(p.Origin) || !CanonicalToken(p.Installation) || !CanonicalToken(p.Registry) || !CanonicalToken(p.Device) || !CanonicalToken(p.PlanID) || p.Issued <= 0 || p.Expires <= p.Issued || p.Expires-p.Issued > PlanLifetime {
return false
}
+ if p.ExistingTeam != "" {
+ if !validTeamSQID(p.ExistingTeam) || (p.Kind != "create-team" && p.Kind != "add-apps") || (p.Role == "directory" && p.Label != "oficina") {
+ return false
+ }
+ for _, app := range p.Apps {
+ if directorydata.CanonicalOrigin(app) == "" {
+ return false
+ }
+ }
+ } else if p.Role == "directory" && p.Label == "oficina" && (p.Kind == "create-team" || p.Kind == "add-apps") {
+ return false
+ }
if p.Kind == "initialize" {
return len(p.Apps) == 0 && p.Label == "" && p.DisplayName == "" && p.Owner == ""
}
@@ -180,6 +193,7 @@ func (v *Verifier) VerifyPlan(raw []byte, apps []string, now time.Time) (Plan, e
// the owner's address. DisplayName is opened only on the directory.
type PlanView struct {
ID, State, Kind, Label, DisplayName, OwnerIndex string
+ ExistingTeam string
Apps []string
Expires, WindowExpires int64
}
@@ -290,7 +304,7 @@ func (s *PlanStore) Submit(ctx context.Context, p Plan, ownerIndex string, now t
if ownerIndex != "" {
index = ownerIndex
}
- if _, e := c.ExecContext(ctx, "INSERT INTO operator_plans(plan_id,state,kind,apps,owner_index,expires_at) VALUES(?,'pending',?,?,?,?)", p.PlanID, p.Kind, strings.Join(apps, ","), index, p.Expires); e != nil {
+ if _, e := c.ExecContext(ctx, "INSERT INTO operator_plans(plan_id,state,kind,apps,owner_index,expires_at,existing_team) VALUES(?,'pending',?,?,?,?,?)", p.PlanID, p.Kind, strings.Join(apps, ","), index, p.Expires, p.ExistingTeam); e != nil {
return ErrUnavailable
}
return nil
@@ -306,7 +320,7 @@ func (s *PlanStore) Submit(ctx context.Context, p Plan, ownerIndex string, now t
}
name = sealed
}
- if _, e := c.ExecContext(ctx, "INSERT INTO operator_plans(plan_id,state,kind,label,apps,sealed_name,expires_at) VALUES(?,'pending',?,?,?,?,?)", p.PlanID, p.Kind, label, strings.Join(apps, ","), name, p.Expires); e != nil {
+ if _, e := c.ExecContext(ctx, "INSERT INTO operator_plans(plan_id,state,kind,label,apps,sealed_name,expires_at,existing_team) VALUES(?,'pending',?,?,?,?,?,?)", p.PlanID, p.Kind, label, strings.Join(apps, ","), name, p.Expires, p.ExistingTeam); e != nil {
return ErrUnavailable
}
return nil
@@ -321,9 +335,9 @@ func scanPlan(ctx context.Context, q execer, role, where string, args ...any) (P
var sealed []byte
var e error
if role == "credential" {
- e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,apps,owner_index,expires_at,window_expires_at FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &apps, &index, &v.Expires, &window)
+ e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,apps,owner_index,expires_at,window_expires_at,existing_team FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &apps, &index, &v.Expires, &window, &v.ExistingTeam)
} else {
- e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,label,apps,sealed_name,expires_at,window_expires_at FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &label, &apps, &sealed, &v.Expires, &window)
+ e = q.QueryRowContext(ctx, "SELECT plan_id,state,kind,label,apps,sealed_name,expires_at,window_expires_at,existing_team FROM operator_plans WHERE "+where, args...).Scan(&v.ID, &v.State, &v.Kind, &label, &apps, &sealed, &v.Expires, &window, &v.ExistingTeam)
}
if errors.Is(e, sql.ErrNoRows) {
return PlanView{}, nil, ErrRefused
diff --git a/internal/operator/verification.go b/internal/operator/verification.go
index 154c4ac..5ff403d 100644
--- a/internal/operator/verification.go
+++ b/internal/operator/verification.go
@@ -114,6 +114,10 @@ func (d *Directory) pending(ctx context.Context, c *sql.Conn, consumer, team, ap
return b, nil
}
func (d *Directory) verifyConsumer(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
+ return d.verifyConsumerForWindow(ctx, c, r, "")
+}
+
+func (d *Directory) verifyConsumerForWindow(ctx context.Context, c *sql.Conn, r Request, existingTeam string) ([]byte, error) {
var in VerificationInput
if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial {
return nil, ErrRefused
@@ -126,6 +130,9 @@ func (d *Directory) verifyConsumer(ctx context.Context, c *sql.Conn, r Request)
if e != nil {
return nil, e
}
+ if !routeScope(existingTeam, binding.label, in.TeamSQID, in.App, in.Consumer, in.Audience) {
+ return nil, ErrRefused
+ }
var old, oldConsumer string
var issued, expires int64
e = c.QueryRowContext(ctx, "SELECT a.operation_id,a.consumer_id,a.issued_at,a.expires_at FROM verification_active v JOIN verification_attempts a ON a.operation_id=v.operation_id WHERE v.consumer_id=?", in.Consumer).Scan(&old, &oldConsumer, &issued, &expires)
@@ -171,20 +178,31 @@ var observedVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`)
func version(s string) bool { return observedVersion.MatchString(s) }
func (d *Directory) activate(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
+ return d.activateForWindow(ctx, c, r, "")
+}
+
+func (d *Directory) activateForWindow(ctx context.Context, c *sql.Conn, r Request, existingTeam string) ([]byte, error) {
var in ActivationInput
if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial {
return nil, ErrRefused
}
p := in.Evidence
+ policy := "oficina/team-activation/v1"
+ if existingTeam != "" {
+ policy = existingActivationPolicy
+ }
now := d.engine.now().Unix()
u, e := url.Parse(p.Audience)
- if e != nil || p.Version != 1 || p.Policy != "oficina/team-activation/v1" || !CanonicalToken(p.Attempt) || !version(p.AppVersion) || !CanonicalToken(p.ArtifactDigest) || !CanonicalToken(p.EnvironmentBinding) || !CanonicalToken(p.ManifestDigest) || p.AliasHost != u.Host || p.Started <= 0 || p.Completed < p.Started || p.Completed > now || now-p.Completed >= 300 {
+ if e != nil || p.Version != 1 || p.Policy != policy || !CanonicalToken(p.Attempt) || !version(p.AppVersion) || !CanonicalToken(p.ArtifactDigest) || !CanonicalToken(p.EnvironmentBinding) || !CanonicalToken(p.ManifestDigest) || p.AliasHost != u.Host || p.Started <= 0 || p.Completed < p.Started || p.Completed > now || now-p.Completed >= 300 {
return nil, ErrRefused
}
binding, e := d.pending(ctx, c, p.Consumer, p.TeamSQID, p.App, p.Audience, p.Generation, p.RecordSequence, p.RecordDigest, p.Owner, p.Epoch)
if e != nil {
return nil, e
}
+ if !routeScope(existingTeam, binding.label, p.TeamSQID, p.App, p.Consumer, p.Audience) {
+ return nil, ErrRefused
+ }
var consumer, app, origin, gen, owner string
var teamID, sequence, epoch, issued, expires int64
var recordDigest []byte