oficina / equipo Public

Merge branch 'oficina-id-signin' into main

Add Sign in with Oficina ID beside email sign-in (off by default)

Pinned Home keys from config; audience-bound, single-use assertions;
explicit linking after a fresh local gesture and fresh Home auth;
unlink with reauthentication; local-first sign-out. Migration 0082.
Reviewed by Fable over two rounds.
claude agent, operated by paul@keymail.dev 71ffc5ef72ea40d9d6a5ada8d40001c8282ef1f3 parent 47b6eb6parent acd8042
56 files changed, +2,795 −63
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +24 −0
  • go.mod +9 −3
  • go.sum +6 −0
  • internal/equipo/app.go +18 −4
  • internal/equipo/auth.go +10 −2
  • internal/equipo/chat_page.go +2 −2
  • internal/equipo/config.go +11 −0
  • internal/equipo/connection_handlers.go +2 −2
  • internal/equipo/conversation/handlers.go +2 −2
  • internal/equipo/conversation/live.go +3 −3
  • internal/equipo/conversation/preference_handlers.go +2 −2
  • internal/equipo/copy.go +18 −0
  • internal/equipo/handlers.go +5 −3
  • internal/equipo/identity/identity.go +19 −0
  • internal/equipo/invite_handlers.go +1 −1
  • internal/equipo/kernel/types.go +5 −4
  • internal/equipo/library/handlers.go +2 −2
  • internal/equipo/migrations.go +4 −1
  • internal/equipo/migrations/0082_oficina_id.sql +8 −0
  • internal/equipo/migrations/schema.sql +8 −0
  • internal/equipo/models.go +3 −0
  • internal/equipo/oficina_id.go +51 −0
  • internal/equipo/oficinaid/http.go +328 −0
  • internal/equipo/oficinaid/http_test.go +27 −0
  • internal/equipo/oficinaid/link.go +224 −0
  • internal/equipo/oficinaid/lookup_test.go +67 −0
  • internal/equipo/oficinaid/main_test.go +9 −0
  • internal/equipo/oficinaid/migrations.go +13 −0
  • internal/equipo/oficinaid/migrations/0001_lifecycle.sql +18 −0
  • internal/equipo/oficinaid/reauth.go +33 −0
  • internal/equipo/oficinaid/review_test.go +175 −0
  • internal/equipo/oficinaid/signout.go +63 −0
  • internal/equipo/oficinaid/store.go +262 −0
  • internal/equipo/oficinaid/store_test.go +418 −0
  • internal/equipo/onboarding.go +2 −2
  • internal/equipo/personapi/auth.go +6 −2
  • internal/equipo/planning/handlers.go +2 −2
  • internal/equipo/question_handlers.go +2 −2
  • internal/equipo/render.go +6 −3
  • internal/equipo/runner_handlers.go +5 −5
  • internal/equipo/settings_hub.go +4 −0
  • internal/equipo/setup/project_form.go +2 −2
  • internal/equipo/setup/session_handlers.go +14 −8
  • internal/equipo/task_handlers.go +4 −4
  • internal/equipo/templates/id_body.html +21 −0
  • internal/equipo/templates/id_public.html +3 −0
  • internal/equipo/templates/oficina_id.html +11 −0
  • internal/equipo/templates/signin_page.html +1 −1
  • internal/equipotest/execution_schema_test.go +6 −0
  • internal/idtest/deletion_test.go +83 −0
  • internal/idtest/guards_test.go +165 −0
  • internal/idtest/id_browser_test.go +151 −0
  • internal/idtest/id_test.go +443 −0
  • internal/idtest/main_test.go +9 −0
  • internal/plan3test/plan3_upgrade_test.go +4 −0

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 27313757..71f9ea30 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 19596 - Web handlers and runtime copy, including project Copy settings and task flags.
+size internal/equipo 19713 - Web handlers and runtime copy, including Oficina ID route wiring and reviewed strings. Identity storage and HTTP flow live in internal/equipo/oficinaid.
size internal/wire 6097 - Protocol 21 Copy dispatch, result, task flags and downgrade fields share Encode.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 813a64c7..e6248f14 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -4704,6 +4704,30 @@ All eight entries have individual `COPY REVIEW REQUIRED` markers. The API guide
## Plan 3 copy inventory (for Paul's review)
+Oficina ID consumer: COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13).
+
+| Key | Copy | Surface | Review |
+| --- | --- | --- | --- |
+| `id.door` | Sign in with Oficina ID | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.title` | Oficina ID | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.unlinked` | No Equipo account is linked to this Oficina ID. | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.help` | Sign in by email, then link your Oficina ID in Settings. | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.link` | Link Oficina ID | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.reauth` | Sign in by email again before linking or unlinking your Oficina ID. | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.confirm` | Link this Oficina ID to your Equipo account? | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.confirm_button` | Confirm link | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.unlink` | Unlink Oficina ID | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.unlink_confirm` | Unlink your Oficina ID? You can still sign in by email. Your work will stay in Equipo. | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.linked_at` | Linked on %s | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.not_linked` | You have not linked an Oficina ID. | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.failed` | This sign-in could not be completed. Try again or sign in by email. | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.email` | Sign in by email | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.signed_out` | You are signed out of Equipo. | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `id.home_signout` | Sign out of Oficina ID too | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+| `copyIDConfig` | Oficina ID configuration is incomplete or invalid. | Oficina ID | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13) |
+
+
+
Activity subjects: COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13). Names come from the person’s task records or runner catalog. Long quoted subjects shorten only on screen; the tooltip and accessible label keep the full text.
| Key | Copy | Surface | Review |
diff --git a/go.mod b/go.mod
index 14ce7283..1701c213 100644
--- a/go.mod
+++ b/go.mod
@@ -15,7 +15,13 @@ require (
require github.com/coder/websocket v1.8.15
-require golang.org/x/crypto v0.53.0
+require (
+ amadan.net/oficina/home/connect v0.0.0-20261114000742-e9829fda431e
+ amadan.net/oficina/home/handoff v0.0.0-20261114000742-e9829fda431e
+ golang.org/x/crypto v0.53.0
+)
+
+require amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d // indirect
require (
amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
@@ -25,12 +31,12 @@ require (
github.com/google/uuid v1.6.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
- github.com/keymaildev/signin v0.1.1 // indirect
+ github.com/keymaildev/signin v0.1.1
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/yuin/goldmark v1.8.6
- golang.org/x/mod v0.37.0 // indirect
+ golang.org/x/mod v0.37.0
golang.org/x/sync v0.21.0 // indirect
golang.org/x/text v0.39.0 // indirect
golang.org/x/tools v0.47.0 // indirect
diff --git a/go.sum b/go.sum
index a31e9b8f..6d2e0789 100644
--- a/go.sum
+++ b/go.sum
@@ -1,3 +1,9 @@
+amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw=
+amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/home/connect v0.0.0-20261114000742-e9829fda431e h1:7Yl4BgKcmocF1ZlnkaGXoBoxBH9oCBxnl+0nTJXAKaY=
+amadan.net/oficina/home/connect v0.0.0-20261114000742-e9829fda431e/go.mod h1:7tsJ//7X4o5QkD068WoUGVDxj/e3ygZ2adF+PHhvBxE=
+amadan.net/oficina/home/handoff v0.0.0-20261114000742-e9829fda431e h1:ce4x6+UxI/uKeGZrLfaPm6FyDAgqcSinl+8HBUw9dsI=
+amadan.net/oficina/home/handoff v0.0.0-20261114000742-e9829fda431e/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/rastrillo/rastrillo v0.30.1 h1:MleTrteqqnGGeCZBqQSzZAhAfqQ3B0tZahZ+0wXhzXc=
amadan.net/rastrillo/rastrillo v0.30.1/go.mod h1:K7Clrt14+25ruVupgRjlIhH2GQp/OdL9VoD8xPmkt0w=
amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index e7b6b272..15774256 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -3,6 +3,7 @@ package equipo
import (
"amadan.net/oficina/equipo/internal/equipo/chat"
"amadan.net/oficina/equipo/internal/equipo/notifications"
+ "amadan.net/oficina/equipo/internal/equipo/oficinaid"
"context"
"encoding/json"
"errors"
@@ -30,6 +31,7 @@ import (
)
type application struct {
+ home *oficinaid.HTTP
installAssets *release.InstallAssets
executionEnabled bool
chi.Router
@@ -203,6 +205,13 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
return nil, err
}
a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin}
+ if cfg.Home != nil {
+ storeID, e := oficinaid.New(d.Writer(), cfg.Origin, cfg.Home)
+ if e != nil {
+ return nil, e
+ }
+ a.home = &oficinaid.HTTP{Store: storeID, Auth: authentication, Render: a.renderID}
+ }
// The live hub served the old always-on pages; the conversation now
// follows the person event stream (chat-stream.js), so it stays off.
a.Use(a.live.Middleware)
@@ -210,14 +219,14 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
store.personOrigin = cfg.Origin
store.personKey = cfg.InstanceKey
store.personCookie = func(r *http.Request) (personapi.PersonPrincipal, error) {
- id, ok := authentication.SessionFrom(r)
+ id, ok := a.sessionFrom(r)
if !ok {
return personapi.PersonPrincipal{}, personapi.ErrUnauthenticated
}
return personapi.PersonPrincipal{Address: id.Address, SessionEpoch: id.At.Unix()}, nil
}
person := store.personAPIRouter()
- a.Use(personapi.Dispatcher(cfg.Origin, runner, person, func(w http.ResponseWriter) { runnerFailure(w, ErrForbidden) }))
+ a.Use(personapi.Dispatcher(cfg.Origin, runner, person, func(w http.ResponseWriter) { runnerFailure(w, ErrForbidden) }, a.home != nil))
a.Mount("/api/v1", person)
a.Handle("/releases/*", a.installAssets)
a.Get("/install.sh", a.installScript)
@@ -230,13 +239,18 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(wire.RunnerProtocol{Protocol: wire.ProtocolCurrent})
})
- a.Get("/signin", a.store.sessionHandler(a.auth).Signin)
+ a.Get("/signin", a.signin)
a.Post("/auth/begin", a.auth.Begin)
a.Get("/auth/callback", a.rememberSignIn(a.auth.Callback))
a.Get("/auth/verify", a.rememberSignIn(a.auth.Verify))
a.Post("/auth/verify", a.rememberSignIn(a.auth.Verify))
a.Post("/auth/forget", a.auth.Forget)
- a.Post("/signout", a.auth.Signout)
+ if a.home != nil {
+ a.home.Routes(a)
+ a.Post("/signout", a.home.Signout)
+ } else {
+ a.Post("/signout", a.auth.Signout)
+ }
ih := a.invitationHandler()
a.Get("/invites/{id}", ih.Page)
a.Post("/invites/{id}/accept", ih.Accept)
diff --git a/internal/equipo/auth.go b/internal/equipo/auth.go
index 603a7ada..b78395cd 100644
--- a/internal/equipo/auth.go
+++ b/internal/equipo/auth.go
@@ -43,10 +43,18 @@ func (a *application) requireMember(next http.Handler) http.Handler {
if a == nil || a.auth == nil || a.store == nil {
return http.HandlerFunc(privateUnavailable)
}
- return a.store.sessionHandler(a.auth).RequireMember(next)
+ h := a.store.sessionHandler(a.auth)
+ if a.home != nil {
+ h.Authenticate = a.home.Authenticate
+ }
+ return h.RequireMember(next)
}
func (a *application) rememberSignIn(next http.HandlerFunc) http.HandlerFunc {
- return a.store.sessionHandler(a.auth).RememberSignIn(next)
+ handler := a.store.sessionHandler(a.auth).RememberSignIn(next)
+ if a.home != nil {
+ return a.home.LocalReauth(handler)
+ }
+ return handler
}
func privateUnavailable(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index 4985260b..0667d7cd 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -13,9 +13,9 @@ import (
"github.com/go-chi/chi/v5"
"amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/equipo/personapi"
"amadan.net/oficina/equipo/internal/wire"
- "amadan.net/rastrillo/rastrillo/auth"
)
// chatView is the conversation page, rendered from the same snapshot a
@@ -224,7 +224,7 @@ type chatEnded struct{ ID, Key string }
// sessionContext carries the browser session as the principal the chat
// store re-checks inside each transaction.
func sessionContext(r *http.Request) (context.Context, string, bool) {
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
return r.Context(), "", false
}
diff --git a/internal/equipo/config.go b/internal/equipo/config.go
index cf7e344f..2febd9db 100644
--- a/internal/equipo/config.go
+++ b/internal/equipo/config.go
@@ -1,6 +1,7 @@
package equipo
import (
+ "amadan.net/oficina/home/connect"
"errors"
"net"
"net/url"
@@ -10,6 +11,7 @@ import (
)
type Config struct {
+ Home *connect.DecodedCredentials
RunnerReleaseDir string
ExecutionEnabled bool
ExecutionMarkerPath string
@@ -38,6 +40,15 @@ func LoadConfig(getenv func(string) string) (Config, error) {
AllowLoggedMail: getenv("EQUIPO_ALLOW_LOGGED_MAIL") == "1",
DatabaseName: strings.TrimSpace(getenv("EQUIPO_DATABASE")),
}
+ raw := connect.Credentials{Issuer: getenv("EQUIPO_HOME_ISSUER"), ConsumerID: getenv("EQUIPO_HOME_CONSUMER_ID"), KeysBase64: getenv("EQUIPO_HOME_KEYS_BASE64"), DEKBase64: getenv("EQUIPO_HOME_DEK_BASE64")}
+ if raw.Issuer != "" || raw.ConsumerID != "" || raw.KeysBase64 != "" || raw.DEKBase64 != "" {
+ var err error
+ cfg.Home, err = connect.DecodeCredentials(&raw, cfg.Origin)
+ if err != nil {
+ //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go.
+ return Config{}, errors.New(copyIDConfig)
+ }
+ }
if cfg.DatabaseName == "" {
cfg.DatabaseName = "equipo.db"
}
diff --git a/internal/equipo/connection_handlers.go b/internal/equipo/connection_handlers.go
index 65a23e84..1df808a6 100644
--- a/internal/equipo/connection_handlers.go
+++ b/internal/equipo/connection_handlers.go
@@ -4,7 +4,7 @@ import (
"net/http"
"strconv"
- "amadan.net/rastrillo/rastrillo/auth"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"github.com/go-chi/chi/v5"
)
@@ -14,7 +14,7 @@ func (a *application) connectionForm(w http.ResponseWriter, r *http.Request) (Ac
a.failure(w, r, ErrInvalid)
return Actor{}, 0, false
}
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return Actor{}, 0, false
diff --git a/internal/equipo/conversation/handlers.go b/internal/equipo/conversation/handlers.go
index 7a171f85..d3cfcd19 100644
--- a/internal/equipo/conversation/handlers.go
+++ b/internal/equipo/conversation/handlers.go
@@ -5,8 +5,8 @@ import (
"net/url"
"strconv"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/equipo/planning"
- "amadan.net/rastrillo/rastrillo/auth"
"amadan.net/rastrillo/rastrillo/live"
"github.com/go-chi/chi/v5"
)
@@ -31,7 +31,7 @@ func (h *Handler) Routes(r chi.Router) {
}
func (h *Handler) actor(w http.ResponseWriter, r *http.Request) (Actor, bool) {
w.Header().Set("Cache-Control", "no-store")
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
h.Failure(w, r, h.App.Forbidden)
}
diff --git a/internal/equipo/conversation/live.go b/internal/equipo/conversation/live.go
index 4ed28fba..5efd4de8 100644
--- a/internal/equipo/conversation/live.go
+++ b/internal/equipo/conversation/live.go
@@ -12,7 +12,7 @@ import (
"strings"
"time"
- "amadan.net/rastrillo/rastrillo/auth"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"gorm.io/gorm"
)
@@ -21,7 +21,7 @@ func PersonalTopic(team, person string) string {
return fmt.Sprintf("personal/%x", sha256.Sum256(raw))
}
func (h *PreferenceHandler) Allow(r *http.Request, key string) bool {
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
return false
}
@@ -72,7 +72,7 @@ func ConversationTopic(team, person, resource string) string {
return fmt.Sprintf("conversation/%s_%x", resource, sum[:16])
}
func (s *Application) AllowConversation(r *http.Request, key string) bool {
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
return false
}
diff --git a/internal/equipo/conversation/preference_handlers.go b/internal/equipo/conversation/preference_handlers.go
index a85b5a29..b765c128 100644
--- a/internal/equipo/conversation/preference_handlers.go
+++ b/internal/equipo/conversation/preference_handlers.go
@@ -4,7 +4,7 @@ import (
"net/http"
"strconv"
- "amadan.net/rastrillo/rastrillo/auth"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"github.com/go-chi/chi/v5"
)
@@ -23,7 +23,7 @@ func (h *PreferenceHandler) Routes(r chi.Router) {
}
func (h *PreferenceHandler) actor(w http.ResponseWriter, r *http.Request) (Actor, bool) {
w.Header().Set("Cache-Control", "no-store")
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
h.Failure(w, r, h.App.Forbidden)
return Actor{}, false
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 31222b2d..a423cb0a 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -12,6 +12,7 @@ import (
// App-owned runtime strings belong here, including boot diagnostics.
// Existing copy accepted for now by Paul, 2026-11-04; new entries stay marked pending.
const (
+ copyIDConfig = "Oficina ID configuration is incomplete or invalid." // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
CopyCalibrationFunding = "calibration funding is too low; rerun with JobInput=%d JobOutput=%d ProjectInputHeadroom=%d ProjectOutputHeadroom=%d TeamInputHeadroom=%d TeamOutputHeadroom=%d: %w" // COPY ACCEPTED FOR NOW (Paul, 2026-11-05; iterate in context)
copyObserverFailure = "The live update could not be sent. The change was saved."
copyDecisionOwnerAssigned = "Reassign this person's project decisions before removing them."
@@ -58,6 +59,23 @@ const BootLog = "Equipo could not start."
// COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules).
var pageCopy = map[string]string{
+ "id.door": "Sign in with Oficina ID", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.title": "Oficina ID", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.unlinked": "No Equipo account is linked to this Oficina ID.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.help": "Sign in by email, then link your Oficina ID in Settings.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.link": "Link Oficina ID", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.reauth": "Sign in by email again before linking or unlinking your Oficina ID.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.confirm": "Link this Oficina ID to your Equipo account?", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.confirm_button": "Confirm link", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.unlink": "Unlink Oficina ID", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.unlink_confirm": "Unlink your Oficina ID? You can still sign in by email. Your work will stay in Equipo.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.linked_at": "Linked on %s", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.not_linked": "You have not linked an Oficina ID.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.failed": "This sign-in could not be completed. Try again or sign in by email.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.email": "Sign in by email", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.signed_out": "You are signed out of Equipo.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+ "id.home_signout": "Sign out of Oficina ID too", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
+
"work.reason.copy_budget": "Copy cannot review all these strings within this task’s token allowance. Continue without Copy or ask the coordinator.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
"work.reason.copy_budget_unknown": "Copy’s token use is unknown. Check the last attempt before continuing.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
"copy.continue": "Continue without Copy", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go
index dad0f270..0709e011 100644
--- a/internal/equipo/handlers.go
+++ b/internal/equipo/handlers.go
@@ -1,6 +1,7 @@
package equipo
import (
+ "amadan.net/oficina/equipo/internal/equipo/oficinaid"
"crypto/rand"
"errors"
"net/http"
@@ -9,12 +10,12 @@ import (
"strings"
"amadan.net/oficina/equipo/internal/equipo/conversation"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/equipo/library"
"amadan.net/oficina/equipo/internal/equipo/personapi"
"amadan.net/oficina/equipo/internal/equipo/planning"
"amadan.net/oficina/equipo/internal/equipo/setup"
"amadan.net/oficina/equipo/internal/equipo/team"
- "amadan.net/rastrillo/rastrillo/auth"
"amadan.net/rastrillo/rastrillo/live"
"github.com/go-chi/chi/v5"
)
@@ -26,6 +27,7 @@ type budgetForm struct {
Fields []budgetField
}
type pageData struct {
+ ID oficinaid.View
Repositories []string
PersonDevices []personapi.Device
PersonDevice personapi.Device
@@ -97,7 +99,7 @@ type pageData struct {
}
func (a *application) page(r *http.Request, key string) (pageData, error) {
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
return pageData{}, ErrForbidden
}
@@ -182,7 +184,7 @@ func (a *application) failure(w http.ResponseWriter, r *http.Request, err error)
back = "/work"
}
}
- id, _ := auth.From(r)
+ id, _ := identity.From(r)
renderStatus(w, status, "form_error", pageData{Nav: Navigation(), Key: navKey, Address: id.Address, Title: key, ErrorKey: key, Back: back, TeamName: copyBrand})
}
func (a *application) index(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/equipo/identity/identity.go b/internal/equipo/identity/identity.go
new file mode 100644
index 00000000..9a1fc05f
--- /dev/null
+++ b/internal/equipo/identity/identity.go
@@ -0,0 +1,19 @@
+package identity
+
+import (
+ "amadan.net/rastrillo/rastrillo/auth"
+ "context"
+ "net/http"
+)
+
+type key struct{}
+
+func With(r *http.Request, id auth.Identity) *http.Request {
+ return r.WithContext(context.WithValue(r.Context(), key{}, id))
+}
+func From(r *http.Request) (auth.Identity, bool) {
+ if id, ok := r.Context().Value(key{}).(auth.Identity); ok {
+ return id, true
+ }
+ return auth.From(r)
+}
diff --git a/internal/equipo/invite_handlers.go b/internal/equipo/invite_handlers.go
index 76b409a4..ac40fc85 100644
--- a/internal/equipo/invite_handlers.go
+++ b/internal/equipo/invite_handlers.go
@@ -10,7 +10,7 @@ import (
func (a *application) invitationHandler() *setup.Handler {
return &setup.Handler{Key: a.store.invitationKey, Now: a.store.runnerClock.Now, Store: a.store, Invalid: ErrInvalid, Forbidden: ErrForbidden, Expired: ErrInvitationExpired, Failure: a.failure,
Actor: func(r *http.Request) (Actor, error) {
- id, ok := a.auth.SessionFrom(r)
+ id, ok := a.sessionFrom(r)
if !ok || id.At.IsZero() {
return Actor{}, ErrForbidden
}
diff --git a/internal/equipo/kernel/types.go b/internal/equipo/kernel/types.go
index b20d715e..440196eb 100644
--- a/internal/equipo/kernel/types.go
+++ b/internal/equipo/kernel/types.go
@@ -37,10 +37,11 @@ const (
)
type Member struct {
- Address string `gorm:"primaryKey"`
- Role Role
- Revision int64
- Active bool
+ IdentityKey string `gorm:"not null;default:'';uniqueIndex:members_identity_key" json:"-"`
+ Address string `gorm:"primaryKey"`
+ Role Role
+ Revision int64
+ Active bool
// SessionEpoch is the earliest permitted session creation time in Unix seconds.
SessionEpoch int64
}
diff --git a/internal/equipo/library/handlers.go b/internal/equipo/library/handlers.go
index cd93b849..167324aa 100644
--- a/internal/equipo/library/handlers.go
+++ b/internal/equipo/library/handlers.go
@@ -9,9 +9,9 @@ import (
"strconv"
"strings"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/equipo/kernel"
"amadan.net/oficina/equipo/internal/equipo/planning"
- "amadan.net/rastrillo/rastrillo/auth"
"github.com/go-chi/chi/v5"
)
@@ -296,7 +296,7 @@ func (h *Handler) Routes(r chi.Router) {
func SessionActor(forbidden error) func(*http.Request) (kernel.Actor, error) {
return func(r *http.Request) (kernel.Actor, error) {
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
return kernel.Actor{}, forbidden
}
diff --git a/internal/equipo/migrations.go b/internal/equipo/migrations.go
index 8af0aee2..6dc86e1f 100644
--- a/internal/equipo/migrations.go
+++ b/internal/equipo/migrations.go
@@ -1,6 +1,9 @@
package equipo
import (
+ "amadan.net/oficina/equipo/internal/equipo/oficinaid"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/handoff"
"embed"
"amadan.net/rastrillo/rastrillo/auth"
@@ -15,4 +18,4 @@ var migrationFS embed.FS
// Schema contains only app tables, so migration check can compare Models.
var Schema = migrate.MustFromFS(migrationFS, "equipo")
-var BootSchema = migrate.Merge(sessions.Schema, auth.Schema, pow.Schema, Schema)
+var BootSchema = migrate.Merge(sessions.Schema, auth.Schema, pow.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace), Schema, oficinaid.LifecycleSchema)
diff --git a/internal/equipo/migrations/0082_oficina_id.sql b/internal/equipo/migrations/0082_oficina_id.sql
new file mode 100644
index 00000000..cee08c72
--- /dev/null
+++ b/internal/equipo/migrations/0082_oficina_id.sql
@@ -0,0 +1,8 @@
+ALTER TABLE members ADD COLUMN identity_key text NOT NULL DEFAULT "";
+UPDATE members SET identity_key=lower(hex(randomblob(16)));
+CREATE UNIQUE INDEX members_identity_key ON members(identity_key);
+CREATE TRIGGER equipo_member_identity AFTER INSERT ON members WHEN NEW.identity_key='' BEGIN
+ UPDATE members SET identity_key=lower(hex(randomblob(16))) WHERE address=NEW.address;
+END;
+CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL DEFAULT 0);
+CREATE TABLE equipo_id_reauth (id_hash TEXT PRIMARY KEY, account_id INTEGER NOT NULL, session_hash TEXT NOT NULL, started INTEGER NOT NULL, expires INTEGER NOT NULL, purpose TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0);
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 30afc5cc..f97d2145 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -678,3 +678,11 @@ CREATE TABLE chat_handoff_turns (handoff_id text, turn_id text PRIMARY KEY);
CREATE INDEX chat_handoff_turn_handoff ON chat_handoff_turns(handoff_id);
CREATE TABLE chat_handoff_tasks (handoff_id text, task_id text, created numeric, PRIMARY KEY (handoff_id, task_id));
CREATE INDEX chat_handoff_task ON chat_handoff_tasks(task_id);
+ALTER TABLE members ADD COLUMN identity_key text NOT NULL DEFAULT "";
+UPDATE members SET identity_key=lower(hex(randomblob(16)));
+CREATE UNIQUE INDEX members_identity_key ON members(identity_key);
+CREATE TRIGGER equipo_member_identity AFTER INSERT ON members WHEN NEW.identity_key='' BEGIN
+ UPDATE members SET identity_key=lower(hex(randomblob(16))) WHERE address=NEW.address;
+END;
+CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL DEFAULT 0);
+CREATE TABLE equipo_id_reauth (id_hash TEXT PRIMARY KEY, account_id INTEGER NOT NULL, session_hash TEXT NOT NULL, started INTEGER NOT NULL, expires INTEGER NOT NULL, purpose TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0);
diff --git a/internal/equipo/models.go b/internal/equipo/models.go
index bf59cb94..2089e253 100644
--- a/internal/equipo/models.go
+++ b/internal/equipo/models.go
@@ -4,6 +4,7 @@ import (
"amadan.net/oficina/equipo/internal/equipo/chat"
"amadan.net/oficina/equipo/internal/equipo/library"
"amadan.net/oficina/equipo/internal/equipo/notifications"
+ "amadan.net/oficina/equipo/internal/equipo/oficinaid"
"time"
"amadan.net/oficina/equipo/internal/equipo/conversation"
@@ -53,3 +54,5 @@ type DecisionOwner = kernel.DecisionOwner
type projectRequest = setup.ProjectRequest
type Specialist = library.Specialist
+
+func init() { Models = append(Models, oficinaid.Models...) }
diff --git a/internal/equipo/oficina_id.go b/internal/equipo/oficina_id.go
new file mode 100644
index 00000000..d142fb8b
--- /dev/null
+++ b/internal/equipo/oficina_id.go
@@ -0,0 +1,51 @@
+package equipo
+
+import (
+ "net/http"
+ "net/url"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/identity"
+ "amadan.net/oficina/equipo/internal/equipo/oficinaid"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/auth"
+)
+
+func (a *application) sessionFrom(r *http.Request) (auth.Identity, bool) {
+ if a.home != nil {
+ return a.home.Session(r)
+ }
+ return a.auth.SessionFrom(r)
+}
+func (a *application) signin(w http.ResponseWriter, r *http.Request) {
+ if a.home == nil {
+ a.store.sessionHandler(a.auth).Signin(w, r)
+ return
+ }
+ state := a.auth.SigninState(r)
+ a.auth.PrepareSigninResponse(w, state)
+ target := "/"
+ if p := r.URL.Query().Get("return_to"); handoff.SafePath(p) && !strings.HasPrefix(p, "/account/home/") {
+ target = p
+ }
+ render(w, "signin_page", map[string]any{"State": state, "Brand": map[string]string{"Name": copyBrand}, "HomeDoor": "/auth/home?return_to=" + url.QueryEscape(target)})
+}
+func (a *application) renderID(w http.ResponseWriter, r *http.Request, view oficinaid.View, status int) {
+ w.Header().Set("Cache-Control", "no-store")
+ if view.State == "settings" || view.State == "confirm" || view.State == "unlink" {
+ id, ok := a.sessionFrom(r)
+ if !ok {
+ ErrorPage(w, r, 403, "")
+ return
+ }
+ data, e := a.settingsPage(identity.With(r, id), "oficina-id", false)
+ if e != nil {
+ ErrorPage(w, r, 503, "")
+ return
+ }
+ data.ID = view
+ renderStatus(w, status, "oficina_id", data)
+ return
+ }
+ renderStatus(w, status, "id_public", map[string]any{"ID": view, "Brand": map[string]string{"Name": copyBrand}})
+}
diff --git a/internal/equipo/oficinaid/http.go b/internal/equipo/oficinaid/http.go
new file mode 100644
index 00000000..a09d029d
--- /dev/null
+++ b/internal/equipo/oficinaid/http.go
@@ -0,0 +1,328 @@
+package oficinaid
+
+import (
+ "amadan.net/rastrillo/rastrillo/carlos"
+ "amadan.net/rastrillo/rastrillo/clientip"
+ "encoding/base64"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/identity"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/auth"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "github.com/go-chi/chi/v5"
+ "github.com/keymaildev/signin"
+)
+
+const pendingCookie = "__Host-equipo-id-pending"
+const inboxCookie = "__Host-equipo-id-inbox"
+const initCookie = "__Host-equipo-id-init"
+const proofCookie = "__Host-equipo-id-proof"
+const reauthCookie = "__Host-equipo-id-reauth"
+const logoutCookie = "__Host-equipo-id-logout"
+const settingsPath = "/conversation/settings/oficina-id"
+
+type View struct {
+ State string
+ Subject string
+ LinkedAt time.Time
+ HomeSignout string
+}
+type HTTP struct {
+ startOnce sync.Once
+ startLimiter *signin.MemoryLimiter
+ Store *Store
+ Auth *auth.Auth
+ Render func(http.ResponseWriter, *http.Request, View, int)
+}
+
+func cookie(r *http.Request, name string) string {
+ value := ""
+ n := 0
+ for _, c := range r.Cookies() {
+ if c.Name == name {
+ n++
+ value = c.Value
+ }
+ }
+ if n != 1 || len(value) != 43 {
+ return ""
+ }
+ b, e := base64.RawURLEncoding.Strict().DecodeString(value)
+ if e != nil || len(b) != 32 || base64.RawURLEncoding.EncodeToString(b) != value {
+ return ""
+ }
+ return value
+}
+func set(w http.ResponseWriter, name, value string, seconds int) {
+ http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: "/", MaxAge: seconds, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
+}
+func (h *HTTP) token(r *http.Request) string { return cookie(r, h.Auth.SessionCookie()) }
+func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, e error) {
+ state := "failed"
+ status := http.StatusBadRequest
+ if errors.Is(e, ErrUnlinked) {
+ state = "unlinked"
+ status = http.StatusForbidden
+ }
+ h.Render(w, r, View{State: state}, status)
+}
+func (h *HTTP) guard(next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
+ if r.Host != strings.TrimPrefix(h.Store.Origin, "https://") {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ for _, name := range []string{h.Auth.SessionCookie(), pendingCookie, inboxCookie, initCookie, proofCookie, reauthCookie} {
+ n := 0
+ for _, c := range r.Cookies() {
+ if c.Name == name {
+ n++
+ }
+ }
+ if n > 1 {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ }
+ if r.Method == http.MethodPost && r.URL.Path != "/auth/assertion" {
+ v := r.Header.Values("Origin")
+ if len(v) != 1 || v[0] != h.Store.Origin {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ }
+ next(w, r)
+ }
+}
+func (h *HTTP) Routes(r chi.Router) {
+ r.Get("/auth/home", h.guard(h.Start))
+ r.Handle("/auth/assertion", h.guard(h.Callback))
+ r.Get("/auth/finish", h.guard(h.Finish))
+ r.Get(settingsPath, h.guard(h.Settings))
+ r.Post("/account/home/reauth", h.guard(h.BeginReauth))
+ r.Get("/account/home/reauth-complete", h.guard(h.CompleteReauth))
+ r.Get("/account/home/confirm", h.guard(h.Confirmation))
+ r.Post("/account/home/confirm", h.guard(h.Confirm))
+ r.Get("/account/home/unlink", h.guard(h.UnlinkPage))
+ r.Post("/account/home/unlink", h.guard(h.Unlink))
+ r.Get("/signed-out", h.guard(h.SignedOut))
+}
+func (h *HTTP) Start(w http.ResponseWriter, r *http.Request) {
+ q, e := url.ParseQuery(r.URL.RawQuery)
+ if e != nil || len(q) > 1 || len(q["return_to"]) > 1 {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ path := "/"
+ if len(q) > 0 {
+ if len(q["return_to"]) != 1 {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ path = q.Get("return_to")
+ }
+ init := cookie(r, initCookie)
+ start := h.Store.Exchange.Start
+ if init != "" {
+ path = "/account/home/confirm"
+ start = h.Store.Exchange.StartFresh
+ } else if strings.HasPrefix(path, "/account/home/") {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ if !handoff.SafePath(path) {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ h.startOnce.Do(func() { h.startLimiter = signin.NewMemoryLimiter(10 * time.Minute) })
+ hops := 0
+ if carlos.Running() {
+ hops = clientip.DefaultHops
+ }
+ allowed, err := h.startLimiter.Allow(r.Context(), clientip.From(r, hops), time.Now(), 20)
+ if err != nil || !allowed {
+ w.Header().Set("Retry-After", "600")
+ h.Render(w, r, View{State: "failed"}, http.StatusTooManyRequests)
+ return
+ }
+ secret, nonce, e := start(r.Context(), path, cookie(r, pendingCookie), time.Now())
+ if e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ if init != "" {
+ if e = h.Store.Bind(r.Context(), init, h.token(r), nonce, time.Now()); e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ }
+ set(w, pendingCookie, secret, 600)
+ q = url.Values{"consumer": {h.Store.Config.ConsumerID}, "nonce": {nonce}}
+ if init != "" {
+ q.Set("max_age", "300")
+ }
+ http.Redirect(w, r, h.Store.Config.Issuer+"/authorize?"+q.Encode(), http.StatusSeeOther)
+}
+func (h *HTTP) Callback(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ w.Header().Set("Allow", http.MethodPost)
+ h.Render(w, r, View{State: "failed"}, http.StatusMethodNotAllowed)
+ return
+ }
+ origins := r.Header.Values("Origin")
+ media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if len(origins) != 1 || origins[0] != h.Store.Config.Issuer || r.URL.RawQuery != "" || e != nil || media != "application/x-www-form-urlencoded" {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ b, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024))
+ if e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ form, e := url.ParseQuery(string(b))
+ if e != nil || len(form) != 1 || len(form["assertion"]) != 1 {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ handle, e := h.Store.Exchange.ReceivePending(r.Context(), form.Get("assertion"), time.Now())
+ if e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ set(w, inboxCookie, handle, 120)
+ http.Redirect(w, r, "/auth/finish", http.StatusSeeOther)
+}
+func (h *HTTP) Finish(w http.ResponseWriter, r *http.Request) {
+ if r.URL.RawQuery != "" {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ init := cookie(r, initCookie)
+ result, path, e := h.Store.Finish(r.Context(), cookie(r, pendingCookie), cookie(r, inboxCookie), h.token(r), init, time.Now())
+ set(w, pendingCookie, "", -1)
+ set(w, inboxCookie, "", -1)
+ set(w, initCookie, "", -1)
+ if e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ if init != "" {
+ set(w, proofCookie, result, 300)
+ } else {
+ set(w, h.Auth.SessionCookie(), result, 30*24*3600)
+ }
+ http.Redirect(w, r, path, http.StatusSeeOther)
+}
+func (h *HTTP) Settings(w http.ResponseWriter, r *http.Request) {
+ linked, e := h.Store.Linked(r.Context(), h.token(r), time.Now())
+ if e != nil {
+ http.Redirect(w, r, "/signin?return_to="+url.QueryEscape(settingsPath), http.StatusSeeOther)
+ return
+ }
+ h.Render(w, r, View{State: "settings", Subject: linked.Subject, LinkedAt: linked.At}, 200)
+}
+func (h *HTTP) BeginReauth(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, 1024)
+ if r.ParseForm() != nil {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ secret, e := h.Store.BeginReauth(r.Context(), h.token(r), r.PostForm.Get("purpose"), time.Now())
+ if e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ set(w, reauthCookie, secret, 300)
+ set(w, initCookie, "", -1)
+ set(w, proofCookie, "", -1)
+ http.Redirect(w, r, "/signin?force=1&return_to=%2Faccount%2Fhome%2Freauth-complete", http.StatusSeeOther)
+}
+func (h *HTTP) CompleteReauth(w http.ResponseWriter, r *http.Request) {
+ next, purpose, e := h.Store.CompleteReauth(r.Context(), cookie(r, reauthCookie), h.token(r), time.Now())
+ if e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ if purpose == "link" {
+ set(w, reauthCookie, "", -1)
+ set(w, initCookie, next, 300)
+ http.Redirect(w, r, "/auth/home", http.StatusSeeOther)
+ } else {
+ http.Redirect(w, r, "/account/home/unlink", http.StatusSeeOther)
+ }
+}
+func (h *HTTP) Confirmation(w http.ResponseWriter, r *http.Request) {
+ if e := h.Store.Pending(r.Context(), cookie(r, proofCookie), h.token(r), time.Now()); e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ h.Render(w, r, View{State: "confirm"}, 200)
+}
+func (h *HTTP) Confirm(w http.ResponseWriter, r *http.Request) {
+ if e := h.Store.Confirm(r.Context(), cookie(r, proofCookie), h.token(r), time.Now()); e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ set(w, proofCookie, "", -1)
+ http.Redirect(w, r, settingsPath, http.StatusSeeOther)
+}
+func (h *HTTP) UnlinkPage(w http.ResponseWriter, r *http.Request) {
+ if _, e := h.Store.Session(r.Context(), h.token(r), time.Now()); e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ h.Render(w, r, View{State: "unlink"}, 200)
+}
+func (h *HTTP) Unlink(w http.ResponseWriter, r *http.Request) {
+ if e := h.Store.Unlink(r.Context(), cookie(r, reauthCookie), h.token(r), time.Now()); e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ set(w, reauthCookie, "", -1)
+ http.Redirect(w, r, settingsPath, http.StatusSeeOther)
+}
+func (h *HTTP) Session(r *http.Request) (auth.Identity, bool) {
+ raw, ok := h.Auth.SessionFrom(r)
+ if !ok {
+ return auth.Identity{}, false
+ }
+ if string(raw.Method) != Method {
+ return raw, true
+ }
+ sess, e := h.Store.Session(r.Context(), h.token(r), time.Now())
+ if e != nil {
+ return auth.Identity{}, false
+ }
+ return auth.Identity{Address: sess.Subject, Method: signin.Method(sess.Method), AuthTime: sess.AuthTime, At: sess.At}, true
+}
+func (h *HTTP) Authenticate(next http.Handler) http.Handler {
+ return h.Auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw, ok := auth.From(r)
+ if !ok {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ if string(raw.Method) != Method {
+ next.ServeHTTP(w, r)
+ return
+ }
+ sess, e := h.Store.Session(r.Context(), h.token(r), time.Now())
+ if e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ id := auth.Identity{Address: sess.Subject, Method: signin.Method(sess.Method), AuthTime: sess.AuthTime, At: sess.At}
+ next.ServeHTTP(w, identity.With(sessions.WithSession(r, sess), id))
+ }))
+}
diff --git a/internal/equipo/oficinaid/http_test.go b/internal/equipo/oficinaid/http_test.go
new file mode 100644
index 00000000..6274868b
--- /dev/null
+++ b/internal/equipo/oficinaid/http_test.go
@@ -0,0 +1,27 @@
+package oficinaid
+
+import (
+ "amadan.net/rastrillo/rastrillo/auth"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+func TestIDDuplicateSessionCannotBypassResolution(t *testing.T) {
+ s, k := fixture(t)
+ _, token := establish(t, s, k, time.Now().Truncate(time.Second))
+ authentication, e := auth.New(auth.Config{DB: s.DB, Origin: s.Origin, InstanceKey: "test-identity-cookie-key", ProofOff: true})
+ if e != nil {
+ t.Fatal(e)
+ }
+ h := &HTTP{Store: s, Auth: authentication, Render: func(w http.ResponseWriter, _ *http.Request, _ View, status int) { w.WriteHeader(status) }}
+ r := httptest.NewRequest("GET", s.Origin+"/work", nil)
+ r.AddCookie(&http.Cookie{Name: authentication.SessionCookie(), Value: token})
+ r.AddCookie(&http.Cookie{Name: authentication.SessionCookie(), Value: token})
+ out := httptest.NewRecorder()
+ h.Authenticate(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })).ServeHTTP(out, r)
+ if out.Code < 400 {
+ t.Fatal("Home subject escaped identity resolution", out.Code)
+ }
+}
diff --git a/internal/equipo/oficinaid/link.go b/internal/equipo/oficinaid/link.go
new file mode 100644
index 00000000..be2b8179
--- /dev/null
+++ b/internal/equipo/oficinaid/link.go
@@ -0,0 +1,224 @@
+package oficinaid
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "time"
+
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+func (s *Store) BeginReauth(ctx context.Context, token, purpose string, now time.Time) (string, error) {
+ if purpose != "link" && purpose != "unlink" {
+ return "", ErrRefused
+ }
+ tx, e := s.begin(ctx, now)
+ if e != nil {
+ return "", e
+ }
+ defer tx.Rollback()
+ sess, e := s.session(ctx, tx, token, now)
+ if e != nil {
+ return "", e
+ }
+ id, e := s.account(ctx, tx, sess.Subject)
+ if e != nil {
+ return "", e
+ }
+ if _, e = tx.ExecContext(ctx, "DELETE FROM equipo_id_reauth WHERE expires<=?", now.Unix()); e != nil {
+ return "", e
+ }
+ var n int
+ if e = tx.QueryRowContext(ctx, "SELECT count(*) FROM equipo_id_reauth").Scan(&n); e != nil || n >= 10000 {
+ return "", ErrRefused
+ }
+ secret, hash, e := sessions.NewToken()
+ if e != nil {
+ return "", e
+ }
+ _, e = tx.ExecContext(ctx, "INSERT INTO equipo_id_reauth(id_hash,account_id,session_hash,started,expires,purpose) VALUES(?,?,?,?,?,?)", hash, id, sessions.HashToken(token), now.Unix(), now.Unix()+300, purpose)
+ if e != nil {
+ return "", e
+ }
+ if e = tx.Commit(); e != nil {
+ return "", e
+ }
+ return secret, nil
+}
+func (s *Store) CompleteReauth(ctx context.Context, secret, token string, now time.Time) (string, string, error) {
+ tx, e := s.begin(ctx, now)
+ if e != nil {
+ return "", "", e
+ }
+ defer tx.Rollback()
+ high, e := s.clock(ctx, tx, now)
+ if e != nil {
+ return "", "", e
+ }
+ var id, started, expires, ready int64
+ var old, purpose string
+ e = tx.QueryRowContext(ctx, "SELECT account_id,session_hash,started,expires,purpose,ready FROM equipo_id_reauth WHERE id_hash=?", sessions.HashToken(secret)).Scan(&id, &old, &started, &expires, &purpose, &ready)
+ if e != nil || ready != 0 || expires <= high || old == sessions.HashToken(token) {
+ return "", "", ErrRefused
+ }
+ local, e := s.local(ctx, tx, token, now)
+ if e != nil || local.PersonID != id || local.AuthTime.Unix() < started {
+ return "", "", ErrRefused
+ }
+ // The original session must still exist; revocation invalidates the request.
+ var originalExpiry, originalCreated string
+ if e = tx.QueryRowContext(ctx, "SELECT expires_at,created_at FROM sessions WHERE token_hash=?", old).Scan(&originalExpiry, &originalCreated); e != nil {
+ return "", "", ErrRefused
+ }
+ expiry, e := time.Parse(time.RFC3339, originalExpiry)
+ if e != nil || !expiry.After(now) {
+ return "", "", ErrRefused
+ }
+ created, e := time.Parse(time.RFC3339, originalCreated)
+ if e != nil {
+ return "", "", ErrRefused
+ }
+ address, e := s.lookup(ctx, tx, id)
+ if e != nil {
+ return "", "", e
+ }
+ var epoch int64
+ if e = tx.QueryRowContext(ctx, "SELECT session_epoch FROM members WHERE address=?", address).Scan(&epoch); e != nil || created.Unix() < epoch {
+ return "", "", ErrRefused
+ }
+ if _, e = tx.ExecContext(ctx, "DELETE FROM sessions WHERE token_hash=?", old); e != nil {
+ return "", "", e
+ }
+ var next string
+ if purpose == "link" {
+ next, e = s.Links.StartFreshOn(ctx, tx, local, "/account/home/confirm", now)
+ if e == nil {
+ _, e = tx.ExecContext(ctx, "DELETE FROM equipo_id_reauth WHERE id_hash=?", sessions.HashToken(secret))
+ }
+ } else {
+ next = secret
+ _, e = tx.ExecContext(ctx, "UPDATE equipo_id_reauth SET session_hash=?,ready=1 WHERE id_hash=?", sessions.HashToken(token), sessions.HashToken(secret))
+ }
+ if e != nil {
+ return "", "", e
+ }
+ if e = tx.Commit(); e != nil {
+ return "", "", e
+ }
+ return next, purpose, nil
+}
+func (s *Store) Bind(ctx context.Context, init, token, nonce string, now time.Time) error {
+ tx, e := s.begin(ctx, now)
+ if e != nil {
+ return e
+ }
+ local, e := s.local(ctx, tx, token, now)
+ tx.Rollback()
+ if e != nil {
+ return e
+ }
+ return s.Links.BindNonce(ctx, init, local, nonce, now)
+}
+func (s *Store) Confirm(ctx context.Context, proof, token string, now time.Time) error {
+ tx, e := s.begin(ctx, now)
+ if e != nil {
+ return e
+ }
+ defer tx.Rollback()
+ local, e := s.local(ctx, tx, token, now)
+ if e != nil {
+ return e
+ }
+ _, e = s.Links.ConfirmOn(ctx, tx, proof, local, now)
+ if errors.Is(e, linkstore.ErrRefused) {
+ if commitErr := tx.Commit(); commitErr != nil {
+ return commitErr
+ }
+ return e
+ }
+ if e != nil {
+ return e
+ }
+ if _, e = tx.ExecContext(ctx, "UPDATE equipo_id_accounts SET linked_at=? WHERE id=?", now.Unix(), local.PersonID); e != nil {
+ return e
+ }
+ if e = s.audit(ctx, tx, local.PersonID, "oficina_id.link", now); e != nil {
+ return e
+ }
+ return tx.Commit()
+}
+func (s *Store) Unlink(ctx context.Context, proof, token string, now time.Time) error {
+ tx, e := s.begin(ctx, now)
+ if e != nil {
+ return e
+ }
+ defer tx.Rollback()
+ local, e := s.local(ctx, tx, token, now)
+ if e != nil {
+ return e
+ }
+ high, e := s.clock(ctx, tx, now)
+ if e != nil {
+ return e
+ }
+ var one int
+ if e = tx.QueryRowContext(ctx, "SELECT 1 FROM equipo_id_reauth WHERE id_hash=? AND account_id=? AND session_hash=? AND purpose='unlink' AND ready=1 AND expires>?", sessions.HashToken(proof), local.PersonID, sessions.HashToken(token), high).Scan(&one); e != nil {
+ return ErrRefused
+ }
+ if _, e = tx.ExecContext(ctx, "DELETE FROM sessions WHERE method=? AND subject IN (SELECT subject FROM home_identity_links WHERE issuer=? AND person_id=?)", Method, s.Config.Issuer, local.PersonID); e != nil {
+ return e
+ }
+ if _, e = tx.ExecContext(ctx, "DELETE FROM home_identity_links WHERE issuer=? AND person_id=?", s.Config.Issuer, local.PersonID); e != nil {
+ return e
+ }
+ if _, e = tx.ExecContext(ctx, "DELETE FROM equipo_id_reauth WHERE account_id=?", local.PersonID); e != nil {
+ return e
+ }
+ for _, table := range []string{"home_link_flows", "oficina_handoff_pending", "oficina_handoff_inbox"} {
+ if _, e = tx.ExecContext(ctx, "DELETE FROM "+table); e != nil {
+ return e
+ }
+ }
+ if _, e = tx.ExecContext(ctx, "UPDATE equipo_id_accounts SET linked_at=0 WHERE id=?", local.PersonID); e != nil {
+ return e
+ }
+ if e = s.audit(ctx, tx, local.PersonID, "oficina_id.unlink", now); e != nil {
+ return e
+ }
+ return tx.Commit()
+}
+
+type Linked struct {
+ Subject string
+ At time.Time
+}
+
+func (s *Store) Linked(ctx context.Context, token string, now time.Time) (Linked, error) {
+ sess, e := s.Session(ctx, token, now)
+ if e != nil {
+ return Linked{}, e
+ }
+ var out Linked
+ var at int64
+ e = s.DB.QueryRowContext(ctx, "SELECT l.subject,a.linked_at FROM home_identity_links l JOIN equipo_id_accounts a ON a.id=l.person_id WHERE l.issuer=? AND a.binding=?", s.Config.Issuer, s.binding(sess.Subject)).Scan(&out.Subject, &at)
+ if errors.Is(e, sql.ErrNoRows) {
+ return out, nil
+ }
+ out.At = time.Unix(at, 0)
+ return out, e
+}
+func (s *Store) Pending(ctx context.Context, proof, token string, now time.Time) error {
+ tx, e := s.begin(ctx, now)
+ if e != nil {
+ return e
+ }
+ local, e := s.local(ctx, tx, token, now)
+ tx.Rollback()
+ if e != nil {
+ return e
+ }
+ _, e = s.Links.Pending(ctx, proof, local, now)
+ return e
+}
diff --git a/internal/equipo/oficinaid/lookup_test.go b/internal/equipo/oficinaid/lookup_test.go
new file mode 100644
index 00000000..708a7ae2
--- /dev/null
+++ b/internal/equipo/oficinaid/lookup_test.go
@@ -0,0 +1,67 @@
+package oficinaid
+
+import (
+ "amadan.net/rastrillo/rastrillo/auth"
+ "context"
+ "database/sql"
+ "database/sql/driver"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+// This driver fails the first identity lookup and succeeds on an unsafe retry.
+type transientDriver struct{}
+type transientConn struct{ queries int }
+type transientRows struct{ done bool }
+
+func (transientDriver) Open(string) (driver.Conn, error) { return &transientConn{}, nil }
+func (*transientConn) Prepare(string) (driver.Stmt, error) {
+ return nil, errors.New("unexpected prepare")
+}
+func (*transientConn) Close() error { return nil }
+func (*transientConn) Begin() (driver.Tx, error) { return nil, errors.New("unexpected transaction") }
+func (c *transientConn) QueryContext(context.Context, string, []driver.NamedValue) (driver.Rows, error) {
+ c.queries++
+ if c.queries == 1 {
+ return nil, errors.New("temporary lookup failure")
+ }
+ return &transientRows{}, nil
+}
+func (*transientRows) Columns() []string {
+ return []string{"subject", "method", "auth_time", "created_at", "expires_at"}
+}
+func (*transientRows) Close() error { return nil }
+func (r *transientRows) Next(out []driver.Value) error {
+ if r.done {
+ return io.EOF
+ }
+ r.done = true
+ now := time.Now().UTC()
+ copy(out, []driver.Value{"pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", Method, now.Format(time.RFC3339), now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)})
+ return nil
+}
+func init() { sql.Register("oficina_id_transient_lookup", transientDriver{}) }
+func TestIDLookupFailureCannotRetryIntoLocalPath(t *testing.T) {
+ d, e := sql.Open("oficina_id_transient_lookup", "")
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer d.Close()
+ d.SetMaxOpenConns(1)
+ authentication, e := auth.New(auth.Config{DB: d, Origin: "https://equipo.example", InstanceKey: "test-identity-cookie-key", ProofOff: true})
+ if e != nil {
+ t.Fatal(e)
+ }
+ h := &HTTP{Store: &Store{DB: d}, Auth: authentication, Render: func(w http.ResponseWriter, _ *http.Request, _ View, status int) { w.WriteHeader(status) }}
+ req := httptest.NewRequest("GET", "https://equipo.example/work", nil)
+ req.AddCookie(&http.Cookie{Name: authentication.SessionCookie(), Value: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"})
+ next := false
+ h.Authenticate(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { next = true })).ServeHTTP(httptest.NewRecorder(), req)
+ if next {
+ t.Fatal("failed identity lookup retried into unresolved Home subject")
+ }
+}
diff --git a/internal/equipo/oficinaid/main_test.go b/internal/equipo/oficinaid/main_test.go
new file mode 100644
index 00000000..7298471e
--- /dev/null
+++ b/internal/equipo/oficinaid/main_test.go
@@ -0,0 +1,9 @@
+package oficinaid
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/equipo/oficinaid/migrations.go b/internal/equipo/oficinaid/migrations.go
new file mode 100644
index 00000000..c3fb0767
--- /dev/null
+++ b/internal/equipo/oficinaid/migrations.go
@@ -0,0 +1,13 @@
+package oficinaid
+
+import (
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "embed"
+)
+
+// These triggers need the app tables, sessions and shared identity stores.
+// Install them last in BootSchema; app-only schema users have no sessions.
+//
+//go:embed migrations/*.sql
+var migrations embed.FS
+var LifecycleSchema = migrate.MustFromFS(migrations, "equipo_identity")
diff --git a/internal/equipo/oficinaid/migrations/0001_lifecycle.sql b/internal/equipo/oficinaid/migrations/0001_lifecycle.sql
new file mode 100644
index 00000000..214f0575
--- /dev/null
+++ b/internal/equipo/oficinaid/migrations/0001_lifecycle.sql
@@ -0,0 +1,18 @@
+CREATE TRIGGER equipo_id_member_delete AFTER DELETE ON members BEGIN
+ DELETE FROM sessions WHERE method='oficina-id' AND subject IN (SELECT subject FROM home_identity_links WHERE person_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key));
+ DELETE FROM home_identity_links WHERE person_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key);
+ DELETE FROM equipo_id_reauth WHERE account_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key);
+ DELETE FROM equipo_id_accounts WHERE member_key=OLD.identity_key;
+ DELETE FROM home_link_flows;
+ DELETE FROM oficina_handoff_pending;
+ DELETE FROM oficina_handoff_inbox;
+END;
+CREATE TRIGGER equipo_id_member_change AFTER UPDATE OF address ON members WHEN OLD.address<>NEW.address BEGIN
+ DELETE FROM sessions WHERE method='oficina-id' AND subject IN (SELECT subject FROM home_identity_links WHERE person_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key));
+ DELETE FROM home_identity_links WHERE person_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key);
+ DELETE FROM equipo_id_reauth WHERE account_id IN (SELECT id FROM equipo_id_accounts WHERE member_key=OLD.identity_key);
+ DELETE FROM equipo_id_accounts WHERE member_key=OLD.identity_key;
+ DELETE FROM home_link_flows;
+ DELETE FROM oficina_handoff_pending;
+ DELETE FROM oficina_handoff_inbox;
+END;
diff --git a/internal/equipo/oficinaid/reauth.go b/internal/equipo/oficinaid/reauth.go
new file mode 100644
index 00000000..9ff0bde9
--- /dev/null
+++ b/internal/equipo/oficinaid/reauth.go
@@ -0,0 +1,33 @@
+package oficinaid
+
+import (
+ "net/http"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+// LocalReauth keeps the initiating session available to the link transaction.
+// The normal email handler still earns and mints the replacement session.
+// CompleteReauth rechecks and revokes the original together with its proof.
+func (h *HTTP) LocalReauth(next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ proof, token := cookie(r, reauthCookie), h.token(r)
+ if proof != "" && token != "" && (r.URL.Path == "/auth/callback" || r.Method == http.MethodPost) {
+ var one int
+ e := h.Store.DB.QueryRowContext(r.Context(), "SELECT 1 FROM equipo_id_reauth WHERE id_hash=? AND session_hash=? AND ready=0 AND expires>?", sessions.HashToken(proof), sessions.HashToken(token), time.Now().Unix()).Scan(&one)
+ if _, sessionErr := h.Store.Session(r.Context(), token, time.Now()); e == nil && sessionErr == nil {
+ nextRequest := r.Clone(r.Context())
+ nextRequest.Header = r.Header.Clone()
+ nextRequest.Header.Del("Cookie")
+ for _, c := range r.Cookies() {
+ if c.Name != h.Auth.SessionCookie() {
+ nextRequest.AddCookie(c)
+ }
+ }
+ r = nextRequest
+ }
+ }
+ next(w, r)
+ }
+}
diff --git a/internal/equipo/oficinaid/review_test.go b/internal/equipo/oficinaid/review_test.go
new file mode 100644
index 00000000..0da66830
--- /dev/null
+++ b/internal/equipo/oficinaid/review_test.go
@@ -0,0 +1,175 @@
+package oficinaid
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+func TestIDLocalGesture(t *testing.T) {
+ for _, purpose := range []string{"link", "unlink"} {
+ for _, method := range []string{"magiclink", "keymail"} {
+ for _, gesture := range []string{"missing", "old", "fresh", "future"} {
+ t.Run(purpose+"/"+method+"/"+gesture, func(t *testing.T) {
+ s, _ := fixture(t)
+ ctx := context.Background()
+ now := time.Now().Truncate(time.Second)
+ old := seedLocal(t, s, "local@example.invalid", now)
+ proof, e := s.BeginReauth(ctx, old, purpose, now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ fresh := seedLocal(t, s, "local@example.invalid", now.Add(time.Second))
+ at := ""
+ switch gesture {
+ case "old":
+ at = now.Add(-time.Second).Format(time.RFC3339)
+ case "fresh":
+ at = now.Format(time.RFC3339)
+ case "future":
+ at = now.Add(time.Minute).Format(time.RFC3339)
+ }
+ if _, e = s.DB.Exec("UPDATE sessions SET method=?,auth_time=? WHERE token_hash=?", method, at, sessions.HashToken(fresh)); e != nil {
+ t.Fatal(e)
+ }
+ _, _, e = s.CompleteReauth(ctx, proof, fresh, now.Add(time.Second))
+ want := gesture == "fresh" || (method == "magiclink" && gesture == "missing")
+ if (e == nil) != want {
+ t.Fatalf("gesture accepted=%v want=%v: %v", e == nil, want, e)
+ }
+ if e == nil && purpose == "unlink" {
+ if e = s.Unlink(ctx, proof, fresh, now.Add(time.Second)); e != nil {
+ t.Fatal(e)
+ }
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestIDReauthCleanupScope(t *testing.T) {
+ for _, action := range []string{"unlink", "delete", "address"} {
+ t.Run(action, func(t *testing.T) {
+ s, k := fixture(t)
+ ctx := context.Background()
+ now := time.Now().Truncate(time.Second)
+ local, _ := establish(t, s, k, now)
+ migration, e := migrations.ReadFile("migrations/0001_lifecycle.sql")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = s.DB.Exec(string(migration)); e != nil {
+ t.Fatal(e)
+ }
+ other := seedLocal(t, s, "other@example.invalid", now)
+ otherProof, e := s.BeginReauth(ctx, other, "link", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ proof, e := s.BeginReauth(ctx, local, "unlink", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ switch action {
+ case "unlink":
+ fresh := seedLocal(t, s, "local-canary@example.invalid", now)
+ if _, _, e = s.CompleteReauth(ctx, proof, fresh, now); e != nil {
+ t.Fatal(e)
+ }
+ e = s.Unlink(ctx, proof, fresh, now)
+ case "delete":
+ _, e = s.DB.Exec("DELETE FROM members WHERE address='local-canary@example.invalid'")
+ case "address":
+ _, e = s.DB.Exec("UPDATE members SET address='changed@example.invalid' WHERE address='local-canary@example.invalid'")
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ var n int
+ if e = s.DB.QueryRow("SELECT count(*) FROM equipo_id_reauth WHERE id_hash=?", sessions.HashToken(proof)).Scan(&n); e != nil || n != 0 {
+ t.Fatal("affected proof survived", n, e)
+ }
+ fresh := seedLocal(t, s, "other@example.invalid", now)
+ if _, _, e = s.CompleteReauth(ctx, otherProof, fresh, now); e != nil {
+ t.Fatal("other account reauthentication lost", e)
+ }
+ })
+ }
+}
+
+func TestIDStartIPLimit(t *testing.T) {
+ for _, platform := range []bool{false, true} {
+ t.Run(strconv.FormatBool(platform), func(t *testing.T) {
+ socket := ""
+ if platform {
+ socket = "/not-opened"
+ }
+ t.Setenv("CARLOS_CONTROL_SOCKET", socket)
+ testStartIPLimit(t, platform)
+ })
+ }
+}
+func testStartIPLimit(t *testing.T, platform bool) {
+ t.Helper()
+ s, _ := fixture(t)
+ h := &HTTP{Store: s, Render: func(w http.ResponseWriter, _ *http.Request, _ View, status int) { w.WriteHeader(status) }}
+ start := func(ip, port string, i int) int {
+ r := httptest.NewRequest("GET", s.Origin+"/auth/home", nil)
+ r.RemoteAddr = ip + ":" + port
+ r.Header.Set("X-Forwarded-For", "198.51.100."+strconv.Itoa(i))
+ if platform {
+ r.RemoteAddr = "127.0.0.1:" + port
+ r.Header.Add("X-Forwarded-For", ip)
+ }
+ w := httptest.NewRecorder()
+ h.Start(w, r)
+ return w.Code
+ }
+ for i := 0; i < 20; i++ {
+ if got := start("192.0.2.1", strconv.Itoa(1000+i), i); got != 303 {
+ t.Fatal("allowance", i, got)
+ }
+ }
+ for i := 0; i < 3; i++ {
+ if got := start("192.0.2.1", strconv.Itoa(2000+i), i+20); got != 429 {
+ t.Fatal("IP budget bypassed", got)
+ }
+ }
+ var n int
+ if e := s.DB.QueryRow("SELECT count(*) FROM oficina_handoff_pending").Scan(&n); e != nil || n != 20 {
+ t.Fatal("limited request inserted pending", n, e)
+ }
+ if got := start("192.0.2.2", "3000", 40); got != 303 {
+ t.Fatal("other IP blocked", got)
+ }
+}
+
+func TestIDUnlinkRechecksKeymailGesture(t *testing.T) {
+ s, k := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ local, _ := establish(t, s, k, now)
+ ctx := context.Background()
+ proof, e := s.BeginReauth(ctx, local, "unlink", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ fresh := seedLocal(t, s, "local-canary@example.invalid", now)
+ if _, e = s.DB.Exec("UPDATE sessions SET method='keymail',auth_time=? WHERE token_hash=?", now.Format(time.RFC3339), sessions.HashToken(fresh)); e != nil {
+ t.Fatal(e)
+ }
+ if _, _, e = s.CompleteReauth(ctx, proof, fresh, now); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = s.DB.Exec("UPDATE sessions SET auth_time='' WHERE token_hash=?", sessions.HashToken(fresh)); e != nil {
+ t.Fatal(e)
+ }
+ if e = s.Unlink(ctx, proof, fresh, now); e == nil {
+ t.Fatal("unlink accepted Keymail without gesture")
+ }
+}
diff --git a/internal/equipo/oficinaid/signout.go b/internal/equipo/oficinaid/signout.go
new file mode 100644
index 00000000..41e895d1
--- /dev/null
+++ b/internal/equipo/oficinaid/signout.go
@@ -0,0 +1,63 @@
+package oficinaid
+
+import (
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "encoding/base64"
+ "net/http"
+ "strconv"
+ "time"
+)
+
+func (h *HTTP) Signout(w http.ResponseWriter, r *http.Request) { h.guard(h.signout)(w, r) }
+func (h *HTTP) signout(w http.ResponseWriter, r *http.Request) {
+ token := h.token(r)
+ tx, e := h.Store.DB.BeginTx(r.Context(), nil)
+ if e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ defer tx.Rollback()
+ var method string
+ if token != "" {
+ _ = tx.QueryRowContext(r.Context(), "SELECT method FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&method)
+ if _, e = tx.ExecContext(r.Context(), "DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(token)); e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ }
+ if e = tx.Commit(); e != nil {
+ h.fail(w, r, e)
+ return
+ }
+ set(w, h.Auth.SessionCookie(), "", -1)
+ set(w, logoutCookie, "", -1)
+ if method == Method {
+ sealed, e := h.Store.seal.Seal("signed-out", []byte(strconv.FormatInt(time.Now().Unix()+300, 10)))
+ if e == nil {
+ set(w, logoutCookie, base64.RawURLEncoding.EncodeToString(sealed), 300)
+ }
+ }
+ http.Redirect(w, r, "/signed-out", http.StatusSeeOther)
+}
+func (h *HTTP) SignedOut(w http.ResponseWriter, r *http.Request) {
+ view := View{State: "signed-out"}
+ values := []string{}
+ for _, c := range r.Cookies() {
+ if c.Name == logoutCookie {
+ values = append(values, c.Value)
+ }
+ }
+ if len(values) == 1 && len(values[0]) < 256 {
+ sealed, e := base64.RawURLEncoding.Strict().DecodeString(values[0])
+ if e == nil {
+ plain, e := h.Store.seal.Open("signed-out", sealed)
+ if e == nil {
+ until, e := strconv.ParseInt(string(plain), 10, 64)
+ if e == nil && until > time.Now().Unix() && until <= time.Now().Unix()+300 {
+ view.HomeSignout = h.Store.Config.Issuer + "/signout"
+ }
+ }
+ }
+ }
+ h.Render(w, r, view, 200)
+}
diff --git a/internal/equipo/oficinaid/store.go b/internal/equipo/oficinaid/store.go
new file mode 100644
index 00000000..ab133daa
--- /dev/null
+++ b/internal/equipo/oficinaid/store.go
@@ -0,0 +1,262 @@
+package oficinaid
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "errors"
+ "strconv"
+ "time"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/oficina/home/handoff/seal"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+const Method = "oficina-id"
+
+var ErrRefused = errors.New("oficina identity refused")
+var ErrUnlinked = errors.New("oficina identity unlinked")
+
+const SchemaSQL = `CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL DEFAULT 0);
+CREATE TABLE equipo_id_reauth (id_hash TEXT PRIMARY KEY, account_id INTEGER NOT NULL, session_hash TEXT NOT NULL, started INTEGER NOT NULL, expires INTEGER NOT NULL, purpose TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0);`
+
+type Account struct {
+ MemberKey string `gorm:"not null;unique"`
+ ID int64
+ Binding string `gorm:"not null;unique"`
+ LinkedAt int64 `gorm:"not null;default:0"`
+}
+
+func (Account) TableName() string { return "equipo_id_accounts" }
+
+type Reauth struct {
+ IDHash string `gorm:"primaryKey"`
+ AccountID int64 `gorm:"not null"`
+ SessionHash string `gorm:"not null"`
+ Started int64 `gorm:"not null"`
+ Expires int64 `gorm:"not null"`
+ Purpose string `gorm:"not null"`
+ Ready int64 `gorm:"not null;default:0"`
+}
+
+func (Reauth) TableName() string { return "equipo_id_reauth" }
+
+var Models = []any{&Account{}, &Reauth{}}
+
+type Store struct {
+ DB *sql.DB
+ Origin string
+ Config *connect.DecodedCredentials
+ Exchange *handoff.Store
+ Links *linkstore.Store
+ seal *seal.Sealer
+}
+
+func New(db *sql.DB, origin string, cfg *connect.DecodedCredentials) (*Store, error) {
+ if cfg == nil {
+ return nil, nil
+ }
+ sealed, e := seal.New(cfg.DEK, "oficina/equipo")
+ if e != nil {
+ return nil, e
+ }
+ s := &Store{DB: db, Origin: origin, Config: cfg, seal: sealed}
+ s.Exchange, e = handoff.NewStore(db, sealed, cfg.Issuer, origin, cfg.Keys)
+ if e != nil {
+ return nil, e
+ }
+ s.Links, e = linkstore.New(db, cfg.DEK, origin, cfg.Issuer, "oficina/equipo", s.lookup)
+ if e != nil {
+ return nil, e
+ }
+ return s, nil
+}
+func (s *Store) binding(address string) string {
+ m := hmac.New(sha256.New, s.Config.DEK)
+ m.Write([]byte("equipo-local-account\x00" + address))
+ return hex.EncodeToString(m.Sum(nil))
+}
+func (s *Store) lookup(ctx context.Context, q linkstore.Queryer, id int64) (string, error) {
+ var address string
+ var active bool
+ if e := q.QueryRowContext(ctx, "SELECT m.address,m.active FROM equipo_id_accounts a JOIN members m ON m.identity_key=a.member_key WHERE a.id=?", id).Scan(&address, &active); e != nil {
+ return "", e
+ }
+ if !active {
+ return "", sql.ErrNoRows
+ }
+ return address, nil
+}
+func (s *Store) account(ctx context.Context, tx *sql.Tx, address string) (int64, error) {
+ var active bool
+ var memberKey string
+ if e := tx.QueryRowContext(ctx, "SELECT active,identity_key FROM members WHERE address=?", address).Scan(&active, &memberKey); e != nil || !active || memberKey == "" {
+ return 0, ErrRefused
+ }
+ binding := s.binding(address)
+ var id int64
+ e := tx.QueryRowContext(ctx, "SELECT id FROM equipo_id_accounts WHERE binding=?", binding).Scan(&id)
+ if e == nil {
+ return id, nil
+ }
+ if !errors.Is(e, sql.ErrNoRows) {
+ return 0, e
+ }
+ result, e := tx.ExecContext(ctx, "INSERT INTO equipo_id_accounts(binding,member_key) VALUES(?,?)", binding, memberKey)
+ if e != nil {
+ return 0, e
+ }
+ return result.LastInsertId()
+}
+func (s *Store) begin(ctx context.Context, now time.Time) (*sql.Tx, error) {
+ tx, e := s.DB.BeginTx(ctx, nil)
+ if e != nil {
+ return nil, e
+ }
+ if _, e = s.clock(ctx, tx, now); e != nil {
+ tx.Rollback()
+ return nil, e
+ }
+ return tx, nil
+}
+func (s *Store) clock(ctx context.Context, tx *sql.Tx, now time.Time) (int64, error) {
+ result, e := tx.ExecContext(ctx, "UPDATE home_link_clock SET high_water=MAX(high_water,?) WHERE id=1 AND high_water<=?", now.Unix(), now.Unix()+30)
+ if e != nil {
+ return 0, e
+ }
+ n, e := result.RowsAffected()
+ if e != nil || n != 1 {
+ return 0, ErrRefused
+ }
+ var high int64
+ e = tx.QueryRowContext(ctx, "SELECT MAX(high_water,(SELECT observed FROM oficina_handoff_clock WHERE id=1)) FROM home_link_clock WHERE id=1").Scan(&high)
+ if e != nil {
+ return 0, e
+ }
+ if now.Unix() < high-30 {
+ return 0, ErrRefused
+ }
+ return high, nil
+}
+
+func (s *Store) session(ctx context.Context, q linkstore.Queryer, token string, now time.Time) (sessions.Session, error) {
+ var out sessions.Session
+ var at, auth, expires string
+ if token == "" {
+ return out, ErrRefused
+ }
+ e := q.QueryRowContext(ctx, "SELECT subject,method,auth_time,created_at,expires_at FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&out.Subject, &out.Method, &auth, &at, &expires)
+ if e != nil {
+ return out, ErrRefused
+ }
+ out.At, e = time.Parse(time.RFC3339, at)
+ if e != nil {
+ return out, ErrRefused
+ }
+ expiry, e := time.Parse(time.RFC3339, expires)
+ if e != nil || !expiry.After(now) {
+ return out, ErrRefused
+ }
+ if auth != "" {
+ out.AuthTime, e = time.Parse(time.RFC3339, auth)
+ if e != nil {
+ return out, ErrRefused
+ }
+ }
+ address := out.Subject
+ if out.Method == Method {
+ _, address, e = s.Links.ResolveOn(ctx, q, s.Config.Issuer, out.Subject)
+ if e != nil {
+ return out, ErrRefused
+ }
+ }
+ var active bool
+ var epoch int64
+ if e = q.QueryRowContext(ctx, "SELECT active,session_epoch FROM members WHERE address=?", address).Scan(&active, &epoch); e != nil || !active || out.At.Unix() < epoch {
+ return out, ErrRefused
+ }
+ out.Subject = address
+ return out, nil
+}
+func (s *Store) Session(ctx context.Context, token string, now time.Time) (sessions.Session, error) {
+ return s.session(ctx, s.DB, token, now)
+}
+func (s *Store) local(ctx context.Context, tx *sql.Tx, token string, now time.Time) (linkstore.Local, error) {
+ sess, e := s.session(ctx, tx, token, now)
+ if e != nil || (sess.Method != "magiclink" && sess.Method != "keymail") {
+ return linkstore.Local{}, ErrRefused
+ }
+ high, e := s.clock(ctx, tx, now)
+ if e != nil {
+ return linkstore.Local{}, e
+ }
+ at := sess.AuthTime
+ if at.IsZero() {
+ if sess.Method == "keymail" {
+ return linkstore.Local{}, ErrRefused
+ }
+ at = sess.At
+ }
+ if at.After(now) || high-at.Unix() > 300 {
+ return linkstore.Local{}, ErrRefused
+ }
+ id, e := s.account(ctx, tx, sess.Subject)
+ return linkstore.Local{PersonID: id, SessionToken: token, AuthTime: at}, e
+}
+func (s *Store) Finish(ctx context.Context, secret, handle, token, init string, now time.Time) (string, string, error) {
+ var minted string
+ _, path, e := s.Exchange.FinishAtomic(ctx, secret, handle, "", now, func(tx *sql.Tx, c assertion.Claims, path string) error {
+ if init != "" {
+ local, e := s.local(ctx, tx, token, now)
+ if e != nil {
+ return e
+ }
+ minted, e = s.Links.CompleteOn(ctx, tx, init, local, linkstore.Home{Issuer: c.Issuer, Subject: c.Subject, Nonce: c.Nonce, AuthTime: time.Unix(c.AuthTime, 0)}, now)
+ return e
+ }
+ if path == "/account/home/confirm" {
+ return ErrRefused
+ }
+ id, address, e := s.Links.ResolveOn(ctx, tx, c.Issuer, c.Subject)
+ if errors.Is(e, linkstore.ErrRefused) {
+ return ErrUnlinked
+ }
+ if e != nil {
+ return e
+ }
+ if token != "" {
+ current, e := s.session(ctx, tx, token, now)
+ if e != nil || current.Subject != address {
+ return ErrRefused
+ }
+ }
+ var epoch int64
+ if e = tx.QueryRowContext(ctx, "SELECT session_epoch FROM members WHERE address=? AND active=1", address).Scan(&epoch); e != nil || now.Unix() < epoch {
+ return ErrRefused
+ }
+ var hash string
+ minted, hash, e = sessions.NewToken()
+ if e != nil {
+ return e
+ }
+ _, e = tx.ExecContext(ctx, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, c.Subject, Method, time.Unix(c.AuthTime, 0).UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339), now.Add(30*24*time.Hour).UTC().Format(time.RFC3339))
+ if e != nil {
+ return e
+ }
+ return s.audit(ctx, tx, id, "oficina_id.signin", now)
+ })
+ if e != nil {
+ return "", "", e
+ }
+ return minted, path, nil
+}
+func (s *Store) audit(ctx context.Context, tx *sql.Tx, id int64, kind string, now time.Time) error {
+ _, e := tx.ExecContext(ctx, "INSERT INTO audit_events(actor,kind,record_id,at) VALUES(?,?,?,?)", "local-account:"+strconv.FormatInt(id, 10), kind, strconv.FormatInt(id, 10), now.UTC())
+ return e
+}
diff --git a/internal/equipo/oficinaid/store_test.go b/internal/equipo/oficinaid/store_test.go
new file mode 100644
index 00000000..498bc370
--- /dev/null
+++ b/internal/equipo/oficinaid/store_test.go
@@ -0,0 +1,418 @@
+package oficinaid
+
+import (
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/crypto"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/base64"
+ "encoding/json"
+ _ "modernc.org/sqlite"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func fixture(t *testing.T) (*Store, *crypto.Keypair) {
+ t.Helper()
+ db, e := sql.Open("sqlite", filepath.Join(t.TempDir(), "id.db")+"?_pragma=busy_timeout(5000)")
+ if e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() { db.Close() })
+ db.SetMaxOpenConns(1)
+ for _, fs := range []struct {
+ read func(string) ([]byte, error)
+ names []string
+ }{{handoff.Migrations.ReadFile, []string{"migrations/0001_exchange.sql"}}, {linkstore.Migrations.ReadFile, []string{"migrations/0001_links.sql", "migrations/0002_person_binding.sql"}}} {
+ for _, n := range fs.names {
+ b, e := fs.read(n)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = db.Exec(string(b)); e != nil {
+ t.Fatal(e)
+ }
+ }
+ }
+ if _, e = db.Exec(`CREATE TABLE audit_events(id INTEGER PRIMARY KEY,actor TEXT,kind TEXT,record_id TEXT,at TEXT); CREATE TABLE members(address TEXT PRIMARY KEY,active INTEGER,session_epoch INTEGER,identity_key TEXT DEFAULT 'local-test-member'); CREATE TABLE sessions(token_hash TEXT PRIMARY KEY,subject TEXT,method TEXT,auth_time TEXT,created_at TEXT,expires_at TEXT);` + SchemaSQL); e != nil {
+ t.Fatal(e)
+ }
+ k, e := crypto.Generate()
+ if e != nil {
+ t.Fatal(e)
+ }
+ s, e := New(db, "https://equipo.example", &connect.DecodedCredentials{Issuer: "https://id.example", ConsumerID: "equipo", Keys: map[string][]byte{"k": k.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)})
+ if e != nil {
+ t.Fatal(e)
+ }
+ return s, k
+}
+func TestIDReceiptGuards(t *testing.T) {
+ for _, kind := range []string{"valid", "replay", "audience", "expired", "nonce", "unlinked"} {
+ t.Run(kind, func(t *testing.T) {
+ s, k := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ secret, nonce, e := s.Exchange.Start(context.Background(), "/work", "", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ c := assertion.Claims{Version: 1, KeyID: "k", Issuer: s.Config.Issuer, Audience: s.Origin, Subject: "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: now.Unix(), Nonce: nonce}
+ c.ID, _ = assertion.RandomID()
+ switch kind {
+ case "audience":
+ c.Audience = "https://other.example"
+ case "expired":
+ c.AuthTime -= 121
+ c.IssuedAt -= 121
+ c.ExpiresAt -= 121
+ case "nonce":
+ c.Nonce, _ = assertion.RandomID()
+ }
+ token, e := assertion.Sign(k, c)
+ if e != nil {
+ t.Fatal(e)
+ }
+ handle, e := s.Exchange.ReceivePending(context.Background(), token, now)
+ if kind == "audience" || kind == "expired" || kind == "nonce" {
+ if e == nil {
+ t.Fatal("accepted invalid receipt")
+ }
+ return
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ if kind == "replay" {
+ if _, e = s.Exchange.ReceivePending(context.Background(), token, now); e == nil {
+ t.Fatal("replayed receipt")
+ }
+ }
+ if kind == "unlinked" {
+ if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e != ErrUnlinked {
+ t.Fatal("unlinked identity admitted", e)
+ }
+ }
+ })
+ }
+}
+
+func seedLocal(t *testing.T, s *Store, address string, now time.Time) string {
+ t.Helper()
+ if _, e := s.DB.Exec("INSERT OR IGNORE INTO members(address,active,session_epoch,identity_key) VALUES(?,1,0,?)", address, s.binding(address)); e != nil {
+ t.Fatal(e)
+ }
+ token, hash, e := sessions.NewToken()
+ if e != nil {
+ t.Fatal(e)
+ }
+ stamp := now.UTC().Format(time.RFC3339)
+ if _, e = s.DB.Exec("INSERT INTO sessions VALUES(?,?,?, ?,?,?)", hash, address, "magiclink", "", stamp, now.Add(time.Hour).UTC().Format(time.RFC3339)); e != nil {
+ t.Fatal(e)
+ }
+ return token
+}
+func readyLink(t *testing.T, s *Store, now time.Time) (string, string) {
+ t.Helper()
+ old := seedLocal(t, s, "local-canary@example.invalid", now.Add(-time.Hour))
+ // Keep the initial session live for this test.
+ s.DB.Exec("UPDATE sessions SET expires_at=?", now.Add(time.Hour).UTC().Format(time.RFC3339))
+ reauth, e := s.BeginReauth(context.Background(), old, "link", now.Add(-time.Second))
+ if e != nil {
+ t.Fatal(e)
+ }
+ token := seedLocal(t, s, "local-canary@example.invalid", now)
+ init, purpose, e := s.CompleteReauth(context.Background(), reauth, token, now)
+ if e != nil || purpose != "link" {
+ t.Fatal("reauth", e)
+ }
+ return token, init
+}
+func receive(t *testing.T, s *Store, k *crypto.Keypair, init, token, subject string, auth, now time.Time) (string, string) {
+ t.Helper()
+ ctx := context.Background()
+ start := s.Exchange.Start
+ if init != "" {
+ start = s.Exchange.StartFresh
+ }
+ path := "/work"
+ if init != "" {
+ path = "/account/home/confirm"
+ }
+ secret, nonce, e := start(ctx, path, "", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if init != "" {
+ if e = s.Bind(ctx, init, token, nonce, now); e != nil {
+ t.Fatal(e)
+ }
+ }
+ id, _ := assertion.RandomID()
+ signed, e := assertion.Sign(k, assertion.Claims{Version: 1, KeyID: "k", Issuer: s.Config.Issuer, Audience: s.Origin, Subject: subject, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: auth.Unix(), Nonce: nonce, ID: id})
+ if e != nil {
+ t.Fatal(e)
+ }
+ handle, e := s.Exchange.ReceivePending(ctx, signed, now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return secret, handle
+}
+func TestIDLinkRequiresNewLocalAndHomeProofs(t *testing.T) {
+ ctx := context.Background()
+ now := time.Now().Truncate(time.Second)
+ for _, kind := range []string{"same-session", "wrong-account", "stale-local", "older-home", "valid"} {
+ t.Run(kind, func(t *testing.T) {
+ s, k := fixture(t)
+ old := seedLocal(t, s, "local-canary@example.invalid", now)
+ proof, e := s.BeginReauth(ctx, old, "link", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ token := old
+ switch kind {
+ case "wrong-account":
+ token = seedLocal(t, s, "other@example.invalid", now)
+ case "stale-local":
+ token = seedLocal(t, s, "local-canary@example.invalid", now.Add(-time.Second))
+ case "older-home", "valid":
+ token = seedLocal(t, s, "local-canary@example.invalid", now)
+ }
+ init, _, e := s.CompleteReauth(ctx, proof, token, now)
+ if kind == "same-session" || kind == "wrong-account" || kind == "stale-local" {
+ if e == nil {
+ t.Fatal("accepted missing fresh local proof")
+ }
+ return
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ homeAt := now
+ if kind == "older-home" {
+ homeAt = now.Add(-time.Second)
+ }
+ secret, handle := receive(t, s, k, init, token, "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", homeAt, now)
+ pending, _, e := s.Finish(ctx, secret, handle, token, init, now)
+ if kind == "older-home" {
+ if e == nil {
+ t.Fatal("Home proof predates link start")
+ }
+ return
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, _, e = s.Links.Resolve(ctx, s.Config.Issuer, "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa"); e == nil {
+ t.Fatal("linked before explicit confirmation")
+ }
+ if e = s.Confirm(ctx, pending, token, now); e != nil {
+ t.Fatal(e)
+ }
+ if e = s.Confirm(ctx, pending, token, now); e == nil {
+ t.Fatal("replayed link confirmation")
+ }
+ })
+ }
+}
+
+func TestIDRejectsAddressAsSubject(t *testing.T) {
+ s, k := fixture(t)
+ now := time.Now()
+ _, nonce, e := s.Exchange.Start(context.Background(), "/", "", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ id, _ := assertion.RandomID()
+ claims := assertion.Claims{Version: 1, KeyID: "k", Issuer: s.Config.Issuer, Audience: s.Origin, Subject: "home-private-canary@example.invalid", ID: id, Nonce: nonce, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: now.Unix()}
+ raw, e := json.Marshal(claims)
+ if e != nil {
+ t.Fatal(e)
+ }
+ sig, e := crypto.Sign(k, "rastrillo/assertion/v1", raw)
+ if e != nil {
+ t.Fatal(e)
+ }
+ wire := base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(sig)
+ if _, e = s.Exchange.ReceivePending(context.Background(), wire, now); e == nil {
+ t.Fatal("address accepted as opaque ref")
+ }
+ var n int
+ if e = s.DB.QueryRow("SELECT count(*) FROM oficina_handoff_inbox").Scan(&n); e != nil || n != 0 {
+ t.Fatal("address retained", n, e)
+ }
+}
+
+func establish(t *testing.T, s *Store, k *crypto.Keypair, now time.Time) (string, string) {
+ t.Helper()
+ token, init := readyLink(t, s, now)
+ secret, handle := receive(t, s, k, init, token, "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now)
+ proof, _, e := s.Finish(context.Background(), secret, handle, token, init, now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = s.Confirm(context.Background(), proof, token, now); e != nil {
+ t.Fatal(e)
+ }
+ secret, handle = receive(t, s, k, "", "", "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now)
+ home, _, e := s.Finish(context.Background(), secret, handle, "", "", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return token, home
+}
+func TestIDAtomicMintFailureAndSwappedBrowser(t *testing.T) {
+ s, k := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ establish(t, s, k, now)
+ secret, handle := receive(t, s, k, "", "", "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now)
+ other, _, e := s.Exchange.Start(context.Background(), "/", "", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, _, e = s.Finish(context.Background(), other, handle, "", "", now); e == nil {
+ t.Fatal("swapped browser accepted")
+ }
+ if _, e = s.DB.Exec("CREATE TRIGGER reject_id_mint BEFORE INSERT ON sessions BEGIN SELECT RAISE(ABORT,'mint blocked'); END"); e != nil {
+ t.Fatal(e)
+ }
+ if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e == nil {
+ t.Fatal("mint failure accepted")
+ }
+ if _, e = s.DB.Exec("DROP TRIGGER reject_id_mint"); e != nil {
+ t.Fatal(e)
+ }
+ if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e != nil {
+ t.Fatal("proof consumed outside mint transaction", e)
+ }
+ if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e == nil {
+ t.Fatal("finished proof replayed")
+ }
+}
+func TestIDUnlinkRevokesReceiptsAndRelinkCannotRevive(t *testing.T) {
+ s, k := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ local, home := establish(t, s, k, now)
+ survivor := seedLocal(t, s, "local-canary@example.invalid", now)
+ secret, handle := receive(t, s, k, "", "", "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now)
+ proof, e := s.BeginReauth(context.Background(), local, "unlink", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ fresh := seedLocal(t, s, "local-canary@example.invalid", now)
+ if _, _, e = s.CompleteReauth(context.Background(), proof, fresh, now); e != nil {
+ t.Fatal(e)
+ }
+ if e = s.Unlink(context.Background(), proof, fresh, now); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = s.Session(context.Background(), home, now); e == nil {
+ t.Fatal("Home session survived unlink")
+ }
+ if _, e = s.Session(context.Background(), survivor, now); e != nil {
+ t.Fatal("local session revoked")
+ }
+ establish(t, s, k, now)
+ if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e == nil {
+ t.Fatal("old receipt revived after relink")
+ }
+}
+func TestIDReauthRejectsRevokedOriginalEpoch(t *testing.T) {
+ s, _ := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ old := seedLocal(t, s, "local-canary@example.invalid", now.Add(-time.Second))
+ proof, e := s.BeginReauth(context.Background(), old, "link", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = s.DB.Exec("UPDATE members SET session_epoch=?", now.Unix()); e != nil {
+ t.Fatal(e)
+ }
+ fresh := seedLocal(t, s, "local-canary@example.invalid", now)
+ if _, _, e = s.CompleteReauth(context.Background(), proof, fresh, now); e == nil {
+ t.Fatal("revoked original session authorized linking")
+ }
+}
+func TestIDReauthClockRollback(t *testing.T) {
+ s, _ := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ old := seedLocal(t, s, "local-canary@example.invalid", now)
+ proof, e := s.BeginReauth(context.Background(), old, "unlink", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ fresh := seedLocal(t, s, "local-canary@example.invalid", now)
+ if _, e = s.DB.Exec("UPDATE home_link_clock SET high_water=?", now.Unix()+400); e != nil {
+ t.Fatal(e)
+ }
+ if _, _, e = s.CompleteReauth(context.Background(), proof, fresh, now); e == nil {
+ t.Fatal("clock rollback revived reauthentication")
+ }
+}
+
+func TestIDConflictingConfirmationBurnsProof(t *testing.T) {
+ s, k := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ establish(t, s, k, now)
+ token, init := readyLink(t, s, now)
+ secret, handle := receive(t, s, k, init, token, "pr_bbbbbbbbbbbbbbbbbbbbbbbbbb", now, now)
+ proof, _, e := s.Finish(context.Background(), secret, handle, token, init, now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = s.Confirm(context.Background(), proof, token, now); e == nil {
+ t.Fatal("conflicting link overwritten")
+ }
+ var n int
+ if e = s.DB.QueryRow("SELECT count(*) FROM home_link_flows WHERE stage='pending'").Scan(&n); e != nil || n != 0 {
+ t.Fatal("rejected proof restored", n, e)
+ }
+}
+
+func TestIDConcurrentUnlinkAndMint(t *testing.T) {
+ s, k := fixture(t)
+ now := time.Now().Truncate(time.Second)
+ local, _ := establish(t, s, k, now)
+ secret, handle := receive(t, s, k, "", "", "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now)
+ proof, e := s.BeginReauth(context.Background(), local, "unlink", now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ fresh := seedLocal(t, s, "local-canary@example.invalid", now)
+ if _, _, e = s.CompleteReauth(context.Background(), proof, fresh, now); e != nil {
+ t.Fatal(e)
+ }
+ ready := make(chan struct{})
+ type minted struct {
+ token string
+ err error
+ }
+ result := make(chan minted, 1)
+ unlinked := make(chan error, 1)
+ go func() {
+ <-ready
+ token, _, err := s.Finish(context.Background(), secret, handle, "", "", now)
+ result <- minted{token, err}
+ }()
+ go func() { <-ready; unlinked <- s.Unlink(context.Background(), proof, fresh, now) }()
+ close(ready)
+ got := <-result
+ if e = <-unlinked; e != nil {
+ t.Fatal(e)
+ }
+ if got.err == nil {
+ if _, e = s.Session(context.Background(), got.token, now); e == nil {
+ t.Fatal("concurrent mint survived unlink")
+ }
+ }
+ var n int
+ if e = s.DB.QueryRow("SELECT count(*) FROM sessions WHERE method=?", Method).Scan(&n); e != nil || n != 0 {
+ t.Fatal("Home sessions survived unlink", n, e)
+ }
+}
diff --git a/internal/equipo/onboarding.go b/internal/equipo/onboarding.go
index 4f8d1348..4b052cb5 100644
--- a/internal/equipo/onboarding.go
+++ b/internal/equipo/onboarding.go
@@ -1,10 +1,10 @@
package equipo
import (
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/equipo/setup"
"amadan.net/oficina/equipo/internal/release"
"amadan.net/rastrillo/rastrillo"
- "amadan.net/rastrillo/rastrillo/auth"
"io"
"net/http"
)
@@ -15,7 +15,7 @@ func (a *application) onboardingHandler() *setup.OnboardingHandler {
instance, _ := runnerInstance(a.store.db.G)
return &setup.OnboardingHandler{InstanceID: instance, InstallAvailable: a.installAssets.CachedAvailable, Store: a.store, Origin: a.origin, Version: rastrillo.BuildVersion, Manifest: release.BuildManifest(), Invalid: ErrInvalid, Failure: a.failure,
Actor: func(r *http.Request) (Actor, error) {
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
return Actor{}, ErrForbidden
}
diff --git a/internal/equipo/personapi/auth.go b/internal/equipo/personapi/auth.go
index 953be004..7c265f68 100644
--- a/internal/equipo/personapi/auth.go
+++ b/internal/equipo/personapi/auth.go
@@ -83,9 +83,13 @@ func OriginAllowed(r *http.Request, origin string) bool {
// Dispatcher bypasses the browser wrapper only for registered protocol routes.
// Their handlers verify their own credentials before accepting a mutation.
-func Dispatcher(origin string, runner, person chi.Routes, refuseRunner func(http.ResponseWriter)) func(http.Handler) http.Handler {
+func Dispatcher(origin string, runner, person chi.Routes, refuseRunner func(http.ResponseWriter), assertionCallback ...bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
- browser := csrf.Protect(origin)(next)
+ var options []csrf.Option
+ if len(assertionCallback) == 1 && assertionCallback[0] {
+ options = append(options, csrf.Exempt("/auth/assertion"))
+ }
+ browser := csrf.Protect(origin, options...)(next)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Escaped separators must never select a different lane than chi's RawPath.
if strings.Contains(strings.ToLower(r.URL.RawPath), "%2f") {
diff --git a/internal/equipo/planning/handlers.go b/internal/equipo/planning/handlers.go
index 1dcac6f0..30e80e69 100644
--- a/internal/equipo/planning/handlers.go
+++ b/internal/equipo/planning/handlers.go
@@ -7,9 +7,9 @@ import (
"strconv"
"strings"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/equipo/kernel"
"amadan.net/oficina/equipo/internal/taskplan"
- "amadan.net/rastrillo/rastrillo/auth"
"github.com/go-chi/chi/v5"
)
@@ -46,7 +46,7 @@ func ReadMutation(w http.ResponseWriter, r *http.Request, invalid error) (kernel
}
func (h *Handler) actor(w http.ResponseWriter, r *http.Request) (kernel.Actor, bool) {
w.Header().Set("Cache-Control", "no-store")
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
h.Failure(w, r, h.Forbidden)
}
diff --git a/internal/equipo/question_handlers.go b/internal/equipo/question_handlers.go
index 8c57b9c4..a1bb7a82 100644
--- a/internal/equipo/question_handlers.go
+++ b/internal/equipo/question_handlers.go
@@ -7,8 +7,8 @@ import (
"strconv"
"strings"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/runnerproto"
- "amadan.net/rastrillo/rastrillo/auth"
"github.com/go-chi/chi/v5"
)
@@ -24,7 +24,7 @@ func (a *application) answerQuestion(w http.ResponseWriter, r *http.Request) {
return
}
}
- actor, ok := auth.From(r)
+ actor, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return
diff --git a/internal/equipo/render.go b/internal/equipo/render.go
index f7f4fd88..5aeb1805 100644
--- a/internal/equipo/render.go
+++ b/internal/equipo/render.go
@@ -42,7 +42,7 @@ var pasteBox = func() chatmarkdown.Labels {
}()
func init() {
- for _, name := range []string{"person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "housekeeping", "work_tasks", "work_task", "work_projects", "work_project", "models", "work_needs", "settings_hub", "team", "usage"} {
+ for _, name := range []string{"oficina_id", "id_public", "person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "housekeeping", "work_tasks", "work_task", "work_projects", "work_project", "models", "work_needs", "settings_hub", "team", "usage"} {
page := template.Must(template.New("layout").
Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))).
Funcs(template.FuncMap{"chatMarkdown": pasteBox.Render, "chatDraft": pasteBox.RenderDraft, "fileSize": fileSize, "loadingLine": loadingLine, "split": strings.Split, "since": sinceMillis, "elapsed": elapsedText, "short": short, "agoData": agoData, "agoText": agoText, "hostOf": hostOf, "deref": deref, "agoFormats": agoFormats, "projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} },
@@ -50,7 +50,7 @@ func init() {
"ownerKey": func(k string) string { return "owner." + k },
"roleKey": func(k Role) string { return "role." + string(k) },
}).ParseFS(ui.Templates(), "*.html"))
- if name == "signin_page" {
+ if name == "signin_page" || name == "id_public" {
stage, ok := ui.Layout("stage")
if !ok {
panic(copyMissingStage)
@@ -59,9 +59,12 @@ func init() {
} else {
page = template.Must(page.ParseFS(appFS, "templates/layout.html"))
}
- if name != "signin_page" && name != "errors" {
+ if name != "signin_page" && name != "id_public" && name != "errors" {
page = template.Must(page.ParseFS(appFS, "templates/chrome.html", "templates/forms.html", "templates/task_card.html", "templates/conversation_card.html", "templates/work_parts.html", "templates/housekeeping_settings.html", "templates/settings_nav.html", "templates/merge_policy.html"))
}
+ if name == "oficina_id" || name == "id_public" {
+ page = template.Must(page.ParseFS(appFS, "templates/id_body.html"))
+ }
pages[name] = template.Must(page.ParseFS(appFS, "templates/"+name+".html"))
}
}
diff --git a/internal/equipo/runner_handlers.go b/internal/equipo/runner_handlers.go
index 7d22398b..83ae4136 100644
--- a/internal/equipo/runner_handlers.go
+++ b/internal/equipo/runner_handlers.go
@@ -9,10 +9,10 @@ import (
"strconv"
"strings"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/rastrillo/rastrillo"
- "amadan.net/rastrillo/rastrillo/auth"
"github.com/go-chi/chi/v5"
)
@@ -164,7 +164,7 @@ func (a *application) machinesAdd(w http.ResponseWriter, r *http.Request) {
func (a *application) machinesScreen(w http.ResponseWriter, r *http.Request, adding bool) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "no-referrer")
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return
@@ -221,7 +221,7 @@ func (a *application) approveEnrolment(w http.ResponseWriter, r *http.Request) {
a.failure(w, r, ErrInvalid)
return
}
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return
@@ -270,7 +270,7 @@ func (a *application) revokeRunner(w http.ResponseWriter, r *http.Request) {
a.failure(w, r, ErrInvalid)
return
}
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return
@@ -294,7 +294,7 @@ func (a *application) removeRunnerNow(w http.ResponseWriter, r *http.Request) {
a.failure(w, r, ErrInvalid)
return
}
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return
diff --git a/internal/equipo/settings_hub.go b/internal/equipo/settings_hub.go
index cc11b33b..fb06ca07 100644
--- a/internal/equipo/settings_hub.go
+++ b/internal/equipo/settings_hub.go
@@ -43,6 +43,7 @@ type settingsLink struct {
}
var settingsSections = []settingsLink{
+ {Key: "oficina-id", Href: "/conversation/settings/oficina-id", CopyKey: "id.title", Icon: "users"},
{Key: "thinking", Href: "/conversation/settings/thinking", CopyKey: "thinking.title", Icon: "type"},
{Key: "connections", Href: "/conversation/settings/connections", CopyKey: "settings.connections", Icon: "plug"},
{Key: "machines", Href: "/conversation/settings/machines", CopyKey: "runner.title", Icon: "monitor"},
@@ -70,6 +71,9 @@ func (a *application) settingsPage(r *http.Request, section string, root bool) (
return data, err
}
for _, s := range settingsSections {
+ if s.Key == "oficina-id" && a.home == nil {
+ continue
+ }
s.Current = s.Key == section
data.SettingsNav = append(data.SettingsNav, s)
}
diff --git a/internal/equipo/setup/project_form.go b/internal/equipo/setup/project_form.go
index 769db508..096c3ed4 100644
--- a/internal/equipo/setup/project_form.go
+++ b/internal/equipo/setup/project_form.go
@@ -1,8 +1,8 @@
package setup
import (
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/oficina/equipo/internal/equipo/kernel"
- "amadan.net/rastrillo/rastrillo/auth"
"context"
"net/http"
"strconv"
@@ -10,7 +10,7 @@ import (
// OwnerForm accepts only the named fields and derives the actor from the session.
func OwnerForm(w http.ResponseWriter, r *http.Request, member func(context.Context, string) (Member, error), invalid, forbidden error, allowed ...string) (Actor, error) {
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
return Actor{}, forbidden
}
diff --git a/internal/equipo/setup/session_handlers.go b/internal/equipo/setup/session_handlers.go
index 515bace4..3d5feb7c 100644
--- a/internal/equipo/setup/session_handlers.go
+++ b/internal/equipo/setup/session_handlers.go
@@ -1,6 +1,7 @@
package setup
import (
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"amadan.net/rastrillo/rastrillo/auth"
"amadan.net/rastrillo/rastrillo/db"
"amadan.net/rastrillo/rastrillo/mail"
@@ -13,12 +14,13 @@ import (
)
type SessionHandler struct {
- Auth *auth.Auth
- Member func(context.Context, string) (Member, error)
- Remember func(context.Context, Actor) error
- Render func(http.ResponseWriter, auth.SigninState)
- Failure func(http.ResponseWriter, *http.Request, int)
- NotFound error
+ Auth *auth.Auth
+ Authenticate func(http.Handler) http.Handler
+ Member func(context.Context, string) (Member, error)
+ Remember func(context.Context, Actor) error
+ Render func(http.ResponseWriter, auth.SigninState)
+ Failure func(http.ResponseWriter, *http.Request, int)
+ NotFound error
}
type AuthOptions struct {
Origin, Key string
@@ -79,9 +81,13 @@ func (h *SessionHandler) RequireMember(next http.Handler) http.Handler {
if h.Auth == nil || h.Member == nil {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.fail(w, r, http.StatusServiceUnavailable) })
}
- browser := h.Auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ authenticate := h.Auth.RequireSession
+ if h.Authenticate != nil {
+ authenticate = h.Authenticate
+ }
+ browser := authenticate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
h.fail(w, r, http.StatusForbidden)
return
diff --git a/internal/equipo/task_handlers.go b/internal/equipo/task_handlers.go
index c724ebc6..780adece 100644
--- a/internal/equipo/task_handlers.go
+++ b/internal/equipo/task_handlers.go
@@ -4,7 +4,7 @@ import (
"net/http"
"strconv"
- "amadan.net/rastrillo/rastrillo/auth"
+ "amadan.net/oficina/equipo/internal/equipo/identity"
"github.com/go-chi/chi/v5"
)
@@ -20,7 +20,7 @@ func (a *application) createBug(w http.ResponseWriter, r *http.Request) {
return
}
}
- id, ok := auth.From(r)
+ id, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return
@@ -44,7 +44,7 @@ func (a *application) cancelTask(w http.ResponseWriter, r *http.Request) {
a.failure(w, r, ErrInvalid)
return
}
- actor, ok := auth.From(r)
+ actor, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return
@@ -63,7 +63,7 @@ func (a *application) oldRunnerStopped(w http.ResponseWriter, r *http.Request) {
a.failure(w, r, ErrInvalid)
return
}
- actor, ok := auth.From(r)
+ actor, ok := identity.From(r)
if !ok {
a.failure(w, r, ErrForbidden)
return
diff --git a/internal/equipo/templates/id_body.html b/internal/equipo/templates/id_body.html
new file mode 100644
index 00000000..c5e5473e
--- /dev/null
+++ b/internal/equipo/templates/id_body.html
@@ -0,0 +1,21 @@
+{{define "id-body"}}
+{{if eq .ID.State "settings"}}
+{{if .ID.Subject}}<p><code>{{.ID.Subject}}</code></p><p>{{printf (copy "id.linked_at") (.ID.LinkedAt.UTC.Format "2006-01-02 15:04 UTC")}}</p>
+{{else}}<p>{{copy "id.not_linked"}}</p>{{end}}
+<p>{{copy "id.reauth"}}</p>
+<form method="post" action="/account/home/reauth">
+{{if .ID.Subject}}<input type="hidden" name="purpose" value="unlink"><button rst-btn type="submit">{{copy "id.unlink"}}</button>
+{{else}}<input type="hidden" name="purpose" value="link"><button rst-btn type="submit">{{copy "id.link"}}</button>{{end}}</form>
+{{else if eq .ID.State "confirm"}}
+<p>{{copy "id.confirm"}}</p><form method="post" action="/account/home/confirm"><button rst-btn="primary" type="submit">{{copy "id.confirm_button"}}</button></form>
+{{else if eq .ID.State "unlink"}}
+<p>{{copy "id.unlink_confirm"}}</p><form method="post" action="/account/home/unlink"><button rst-btn="danger" type="submit">{{copy "id.unlink"}}</button></form>
+{{else if eq .ID.State "unlinked"}}
+<p>{{copy "id.unlinked"}}</p><p>{{copy "id.help"}}</p><a rst-btn href="/signin?force=1&amp;return_to=%2Fconversation%2Fsettings%2Foficina-id">{{copy "id.email"}}</a>
+{{else if eq .ID.State "signed-out"}}
+<p>{{copy "id.signed_out"}}</p><a rst-btn href="/signin?force=1">{{copy "id.email"}}</a>
+{{with .ID.HomeSignout}}<p><a rst-btn href="{{.}}">{{copy "id.home_signout"}}</a></p>{{end}}
+{{else}}
+<p>{{copy "id.failed"}}</p><a rst-btn href="/signin?force=1">{{copy "id.email"}}</a>
+{{end}}
+{{end}}
diff --git a/internal/equipo/templates/id_public.html b/internal/equipo/templates/id_public.html
new file mode 100644
index 00000000..b48bc284
--- /dev/null
+++ b/internal/equipo/templates/id_public.html
@@ -0,0 +1,3 @@
+{{define "title"}}{{copy "id.title"}}{{end}}
+{{define "content"}}{{template "id-body" .}}{{end}}
+{{define "backdrop"}}{{stageArt "equipo"}}{{end}}
diff --git a/internal/equipo/templates/oficina_id.html b/internal/equipo/templates/oficina_id.html
new file mode 100644
index 00000000..996aa965
--- /dev/null
+++ b/internal/equipo/templates/oficina_id.html
@@ -0,0 +1,11 @@
+{{define "up"}}{{template "settings-up" .}}{{end}}
+{{define "up-label"}}{{template "settings-up-label" .}}{{end}}
+{{define "title"}}{{copy "id.title"}}{{end}}
+{{define "content"}}
+<div equipo-settings-layout data-section="oficina-id">
+{{template "settings-nav" .}}
+<section equipo-settings-body equipo-settings-section>
+{{template "settings-head" (dict "Title" "id.title")}}
+{{template "id-body" .}}
+</section></div>
+{{end}}
diff --git a/internal/equipo/templates/signin_page.html b/internal/equipo/templates/signin_page.html
index 862761d4..195bb932 100644
--- a/internal/equipo/templates/signin_page.html
+++ b/internal/equipo/templates/signin_page.html
@@ -1,3 +1,3 @@
{{define "title"}}{{template "signin-title" .}}{{end}}
-{{define "content"}}{{template "signin" .}}{{end}}
+{{define "content"}}{{template "signin" .}}{{with .HomeDoor}}<p><a rst-btn href="{{.}}">{{copy "id.door"}}</a></p>{{end}}{{end}}
{{define "backdrop"}}{{stageArt "equipo"}}{{end}}
diff --git a/internal/equipotest/execution_schema_test.go b/internal/equipotest/execution_schema_test.go
index c0a37b34..65f4cf46 100644
--- a/internal/equipotest/execution_schema_test.go
+++ b/internal/equipotest/execution_schema_test.go
@@ -468,6 +468,12 @@ func TestExecutionBackupIncludesArtifacts(t *testing.T) {
}
func schemaBefore(id, version string) bool {
+ // Oficina ID stores arrived with 0082, after these historical snapshots.
+ for _, prefix := range []string{"oficina_handoff/", "oficina_connect_link/", "equipo_identity/"} {
+ if strings.HasPrefix(id, prefix) {
+ return version >= "0082"
+ }
+ }
return !strings.HasPrefix(id, "equipo/") || strings.Split(strings.TrimPrefix(id, "equipo/"), "_")[0] <= version
}
func schemaAfter(version string) []string {
diff --git a/internal/idtest/deletion_test.go b/internal/idtest/deletion_test.go
new file mode 100644
index 00000000..131bc1bc
--- /dev/null
+++ b/internal/idtest/deletion_test.go
@@ -0,0 +1,83 @@
+package idtest
+
+import (
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "net/url"
+ "testing"
+ "time"
+)
+
+func TestIDDeletedAccountCannotBeRecreatedWithOldLink(t *testing.T) {
+ f := newFixture(t, true)
+ f.link(t)
+ done, _ := f.exchange(t, nil, nil, person)
+ session := cookie(t, done, "__Host-rastrillo_session")
+ if _, e := f.db.Writer().Exec("DELETE FROM members WHERE address=?", address); e != nil {
+ t.Fatal(e)
+ }
+ if _, e := f.db.Writer().Exec("INSERT INTO members(address,role,active,session_epoch) VALUES(?,'owner',1,?)", address, time.Now().Unix()); e != nil {
+ t.Fatal(e)
+ }
+ if r := f.request("GET", "/work", "", nil, session); r.Code == 200 {
+ t.Fatal("deleted account's Home session revived")
+ }
+ if r, _ := f.exchange(t, nil, nil, person); r.Code != 403 {
+ t.Fatal("old Home link transferred to recreated account", r.Code)
+ }
+}
+func TestIDAddressChangeNeedsFreshLink(t *testing.T) {
+ f := newFixture(t, true)
+ f.link(t)
+ if _, e := f.db.Writer().Exec("UPDATE members SET address='changed@example.invalid' WHERE address=?", address); e != nil {
+ t.Fatal(e)
+ }
+ if r, _ := f.exchange(t, nil, nil, person); r.Code != 403 {
+ t.Fatal("address change preserved link", r.Code)
+ }
+}
+
+func TestIDLocalReauthenticationUsesRealEmail(t *testing.T) {
+ f := newFixture(t, true)
+ old := f.local(t, address)
+ start := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"link"}}, old)
+ proof := cookie(t, start, "__Host-equipo-id-reauth")
+ fresh := f.emailWith(t, start.Header().Get("Location"), old, proof)
+ if fresh.Value == old.Value {
+ t.Fatal("local reauthentication reused session")
+ }
+ var oldRows int
+ if e := f.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE token_hash=?", sessions.HashToken(old.Value)).Scan(&oldRows); e != nil || oldRows != 1 {
+ t.Fatal("original session lost before proof completion", oldRows, e)
+ }
+ end := f.request("GET", "/account/home/reauth-complete", "", nil, proof, fresh)
+ if end.Code != 303 || end.Header().Get("Location") != "/auth/home" {
+ t.Fatal("local proof did not start Home leg", end.Code, end.Body.String())
+ }
+ if e := f.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE token_hash=?", sessions.HashToken(old.Value)).Scan(&oldRows); e != nil || oldRows != 0 {
+ t.Fatal("original session was not rotated", oldRows, e)
+ }
+ done, _ := f.exchange(t, cookie(t, end, "__Host-equipo-id-init"), fresh, person)
+ if done.Code != 303 {
+ t.Fatal("fresh email then Home", done.Code)
+ }
+}
+
+func TestIDReauthHasNoAddressBridge(t *testing.T) {
+ f := newFixture(t, true)
+ local := f.local(t, address)
+ out := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"link"}}, local)
+ if out.Code != 303 {
+ t.Fatal("reauth start", out.Code)
+ }
+ var n int
+ if e := f.db.Writer().QueryRow("SELECT count(*) FROM pragma_table_info('equipo_id_accounts') WHERE name LIKE '%address%'").Scan(&n); e != nil || n != 0 {
+ t.Fatal("redundant address bridge remains", n, e)
+ }
+ var key, memberKey string
+ if e := f.db.Writer().QueryRow("SELECT member_key FROM equipo_id_accounts").Scan(&key); e != nil {
+ t.Fatal(e)
+ }
+ if e := f.db.Writer().QueryRow("SELECT identity_key FROM members WHERE address=?", address).Scan(&memberKey); e != nil || key != memberKey {
+ t.Fatal("immutable member binding missing", e)
+ }
+}
diff --git a/internal/idtest/guards_test.go b/internal/idtest/guards_test.go
new file mode 100644
index 00000000..f68ad78d
--- /dev/null
+++ b/internal/idtest/guards_test.go
@@ -0,0 +1,165 @@
+package idtest
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+func TestIDCallbackGuardAndPendingNonce(t *testing.T) {
+ for _, kind := range []string{"missing-nonce", "wrong-origin", "duplicate-origin", "duplicate-assertion", "wrong-method", "oversize", "replay"} {
+ t.Run(kind, func(t *testing.T) {
+ f := newFixture(t, true)
+ start := f.request("GET", "/auth/home", "", nil)
+ u, _ := url.Parse(start.Header().Get("Location"))
+ nonce := u.Query().Get("nonce")
+ if kind == "missing-nonce" {
+ nonce, _ = assertion.RandomID()
+ }
+ token := f.signed(t, nonce, person, time.Now())
+ form := url.Values{"assertion": {token}}
+ origin := f.issuer
+ method := "POST"
+ switch kind {
+ case "wrong-origin":
+ origin = "https://evil.example"
+ case "duplicate-assertion":
+ form.Add("assertion", token)
+ case "wrong-method":
+ method = "GET"
+ case "oversize":
+ form.Set("assertion", strings.Repeat("x", 13*1024))
+ }
+ var outCode int
+ if kind == "duplicate-origin" {
+ req := httptest.NewRequest("POST", f.origin+"/auth/assertion", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Add("Origin", origin)
+ req.Header.Add("Origin", origin)
+ out := httptest.NewRecorder()
+ f.h.ServeHTTP(out, req)
+ outCode = out.Code
+ } else {
+ out := f.request(method, "/auth/assertion", origin, form)
+ if kind == "replay" {
+ if out.Code != 303 {
+ t.Fatal(out.Code)
+ }
+ out = f.request(method, "/auth/assertion", origin, form)
+ }
+ outCode = out.Code
+ }
+ if outCode < 400 {
+ t.Fatal("bad callback accepted", kind, outCode)
+ }
+ var n int
+ if e := f.db.Writer().QueryRow("SELECT count(*) FROM oficina_handoff_inbox").Scan(&n); e != nil {
+ t.Fatal(e)
+ }
+ want := 0
+ if kind == "replay" {
+ want = 1
+ }
+ if n != want {
+ t.Fatal("invalid callback stored receipt", n)
+ }
+ })
+ }
+}
+func TestIDIdenticalAdmissionAndNoAccountSwitch(t *testing.T) {
+ for _, kind := range []string{"removed", "epoch", "lookup-error", "other-account"} {
+ t.Run(kind, func(t *testing.T) {
+ f := newFixture(t, true)
+ local := f.link(t)
+ done, _ := f.exchange(t, nil, nil, person)
+ home := cookie(t, done, "__Host-rastrillo_session")
+ switch kind {
+ case "removed":
+ f.db.Writer().Exec("UPDATE members SET active=0")
+ case "epoch":
+ f.db.Writer().Exec("UPDATE members SET session_epoch=?", time.Now().Unix()+1)
+ case "lookup-error":
+ f.db.Writer().Exec("ALTER TABLE members RENAME TO unavailable_members")
+ case "other-account":
+ f.db.Writer().Exec("INSERT INTO members(address,role,active,session_epoch) VALUES('other@example.invalid','member',1,0)")
+ other := f.local(t, "other@example.invalid")
+ out, _ := f.exchange(t, nil, other, person)
+ if out.Code < 400 {
+ t.Fatal("Home replaced another account")
+ }
+ return
+ }
+ for _, session := range []*http.Cookie{local, home} {
+ if out := f.request("GET", "/work", "", nil, session); out.Code == 200 {
+ t.Fatal("inadmissible session accepted", kind)
+ }
+ }
+ })
+ }
+}
+func TestIDConfigurationPins(t *testing.T) {
+ k, e := crypto.Generate()
+ if e != nil {
+ t.Fatal(e)
+ }
+ manifest, _ := json.Marshal(map[string]string{"old": base64.StdEncoding.EncodeToString(k.SignPub())})
+ env := map[string]string{"EQUIPO_ORIGIN": appOrigin, "EQUIPO_INSTANCE_KEY": "config-key", "CARLOS_SMTP_HOST": "smtp.example", "CARLOS_SMTP_FROM": "sender@example.invalid"}
+ get := func(k string) string { return env[k] }
+ cfg, e := equipo.LoadConfig(get)
+ if e != nil || cfg.Home != nil {
+ t.Fatal("default on", e)
+ }
+ env["EQUIPO_HOME_ISSUER"] = issuer
+ if _, e = equipo.LoadConfig(get); e == nil {
+ t.Fatal("partial config accepted")
+ }
+ env["EQUIPO_HOME_CONSUMER_ID"] = "equipo"
+ env["EQUIPO_HOME_KEYS_BASE64"] = base64.StdEncoding.EncodeToString(manifest)
+ env["EQUIPO_HOME_DEK_BASE64"] = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))
+ cfg, e = equipo.LoadConfig(get)
+ if e != nil || cfg.Home == nil {
+ t.Fatal("valid pins", e)
+ }
+ newer, e := crypto.Generate()
+ if e != nil {
+ t.Fatal(e)
+ }
+ keys := map[string][]byte{"old": k.SignPub(), "new": newer.SignPub()}
+ now := time.Now()
+ id, _ := assertion.RandomID()
+ nonce, _ := assertion.RandomID()
+ claims := assertion.Claims{Version: 1, KeyID: "new", Issuer: issuer, Audience: appOrigin, Subject: person, ID: id, Nonce: nonce, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: now.Unix()}
+ token, e := assertion.Sign(newer, claims)
+ if e != nil {
+ t.Fatal(e)
+ }
+ old, e := assertion.NewVerifier(issuer, appOrigin, cfg.Home.Keys)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = old.Verify(token, now); e == nil {
+ t.Fatal("unknown pin accepted")
+ }
+ both, e := assertion.NewVerifier(issuer, appOrigin, keys)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = both.Verify(token, now); e != nil {
+ t.Fatal("rotation pins", e)
+ }
+ manifest = []byte(`{"old":"bad","old":"bad"}`)
+ env["EQUIPO_HOME_KEYS_BASE64"] = base64.StdEncoding.EncodeToString(manifest)
+ if _, e = equipo.LoadConfig(get); e == nil {
+ t.Fatal("duplicate pin accepted")
+ }
+}
diff --git a/internal/idtest/id_browser_test.go b/internal/idtest/id_browser_test.go
new file mode 100644
index 00000000..c3efee98
--- /dev/null
+++ b/internal/idtest/id_browser_test.go
@@ -0,0 +1,151 @@
+//go:build browser
+
+package idtest
+
+import (
+ "context"
+ "fmt"
+ "html/template"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/browsertest"
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/emulation"
+ "github.com/chromedp/chromedp"
+)
+
+// The test Home uses the production assertion signer and closed authorize
+// contract. Its identity is fixed; Home's own WebAuthn browser tests exercise
+// earning that identity. This test covers Equipo's real cross-site door.
+func TestBrowserOficinaIDDoor(t *testing.T) {
+ const origin = "https://equipo.example.test"
+ const home = "https://id.example.org"
+ f := fixtureAt(t, true, origin, home)
+ local := f.link(t)
+ var callbacks atomic.Int32
+ var nonce string
+ continuePage := template.Must(template.New("continue").Parse(`<!doctype html><title>Oficina ID</title><form method="post" action="/continue"><button id="continue">Continue</button></form>`))
+ receiptPage := template.Must(template.New("receipt").Parse(`<!doctype html><title>Oficina ID</title><form method="post" action="{{.Target}}"><input type="hidden" name="assertion" value="{{.Token}}"><button id="return">Continue to Equipo</button></form>`))
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Host == "equipo.example.test" {
+ if r.URL.Path == "/auth/assertion" {
+ callbacks.Add(1)
+ if r.Header.Get("Origin") != home {
+ t.Error("callback lost issuer Origin")
+ }
+ for _, c := range r.Cookies() {
+ if c.Name == "__Host-equipo-id-pending" {
+ t.Error("Lax pending cookie sent on cross-site POST")
+ }
+ }
+ }
+ f.h.ServeHTTP(w, r)
+ return
+ }
+ if r.Host != "id.example.org" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
+ switch r.URL.Path {
+ case "/authorize":
+ q := r.URL.Query()
+ if r.Method != "GET" || len(q) != 2 || len(q["consumer"]) != 1 || q.Get("consumer") != "equipo" || len(q["nonce"]) != 1 {
+ http.Error(w, "invalid test authorization", 400)
+ return
+ }
+ nonce = q.Get("nonce")
+ _ = continuePage.Execute(w, nil)
+ case "/continue":
+ if r.Method != "POST" || r.Header.Get("Origin") != home || nonce == "" {
+ http.Error(w, "invalid test continuation", 400)
+ return
+ }
+ token := f.signed(t, nonce, person, time.Now())
+ nonce = ""
+ _ = receiptPage.Execute(w, struct{ Target, Token string }{origin + "/auth/assertion", token})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer server.Close()
+ u, _ := url.Parse(server.URL)
+ profile := t.TempDir()
+ opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.UserDataDir(profile), chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("no-proxy-server", true), chromedp.Flag("host-resolver-rules", "MAP equipo.example.test "+u.Host+", MAP id.example.org "+u.Host))
+ alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...)
+ defer stop()
+ ctx, cancel := chromedp.NewContext(alloc)
+ defer cancel()
+ ctx, deadline := context.WithTimeout(ctx, 60*time.Second)
+ defer deadline()
+ run := func(actions ...chromedp.Action[chromedp.Void]) {
+ t.Helper()
+ if e := chromedp.Do(ctx, actions...); e != nil {
+ t.Fatal(e)
+ }
+ }
+ run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ _, e := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true})
+ return e
+ }))
+ run(chromedp.Navigate(origin+"/signin"), browsertest.Wait(`!!document.querySelector('a[href^="/auth/home"]')`))
+ capture := func(name string) {
+ for _, width := range []int64{390, 1280} {
+ run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ _, e := cdp.Call(ctx, target, emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: width, Height: 900, DeviceScaleFactor: 1, Mobile: width == 390})
+ if e != nil {
+ return e
+ }
+ overflow, e := chromedp.Evaluate[bool](`document.documentElement.scrollWidth>innerWidth`)(ctx, target)
+ if e != nil {
+ return e
+ }
+ if overflow {
+ return fmt.Errorf("%s overflows at %d", name, width)
+ }
+ if dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS"); dir != "" {
+ shot, e := chromedp.CaptureScreenshot()(ctx, target)
+ if e != nil {
+ return e
+ }
+ if e = os.MkdirAll(dir, 0700); e != nil {
+ return e
+ }
+ return os.WriteFile(filepath.Join(dir, fmt.Sprintf("%s-%d.png", name, width)), shot, 0600)
+ }
+ return nil
+ }))
+ }
+ }
+ capture("oficina-id-door")
+ run(browsertest.Click(`a[href^="/auth/home"]`), browsertest.Wait(`location.origin==="https://id.example.org" && !!document.querySelector('#continue')`), browsertest.Click("#continue"), browsertest.Wait(`!!document.querySelector('#return')`), browsertest.Click("#return"), browsertest.Wait(`location.origin==="https://equipo.example.test" && location.pathname==="/conversation"`))
+ if callbacks.Load() != 1 {
+ t.Fatal("full callback did not run", callbacks.Load())
+ }
+ run(chromedp.Navigate(origin+"/conversation/settings/oficina-id"), browsertest.Wait(`document.body.textContent.includes("pr_aaaaaaaaaaaaaaaaaaaaaaaaaa")`))
+ capture("oficina-id-settings")
+ run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ body, e := chromedp.Evaluate[string](`document.body.textContent`)(ctx, target)
+ if e != nil {
+ return e
+ }
+ if strings.Contains(body, homeAddress) {
+ return fmt.Errorf("Home address leaked")
+ }
+ return nil
+ }))
+ // Local credentials remain valid after the browser signs in through Home.
+ if r := f.request("GET", "/work", "", nil, local); r.Code != 200 {
+ t.Fatal("email session changed", r.Code)
+ }
+}
diff --git a/internal/idtest/id_test.go b/internal/idtest/id_test.go
new file mode 100644
index 00000000..03451ae5
--- /dev/null
+++ b/internal/idtest/id_test.go
@@ -0,0 +1,443 @@
+package idtest
+
+import (
+ "bytes"
+ "context"
+ "html"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/oficinaid"
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/crypto"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/pow"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+const appOrigin = "https://equipo.example"
+const issuer = "https://id.example"
+const person = "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa"
+const address = "local-canary@example.invalid"
+const homeAddress = "home-private-canary@example.invalid"
+
+type mailer struct {
+ mu sync.Mutex
+ body string
+}
+
+func (m *mailer) Send(_ context.Context, _, _, body string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.body = body
+ return nil
+}
+
+type fixture struct {
+ db *db.DB
+ h http.Handler
+ k *crypto.Keypair
+ mail *mailer
+ logs *bytes.Buffer
+ path string
+ origin, issuer string
+}
+
+func newFixture(t *testing.T, enabled bool) *fixture { return fixtureAt(t, enabled, appOrigin, issuer) }
+func fixtureAt(t *testing.T, enabled bool, origin, home string) *fixture {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "equipo.db")
+ logs := new(bytes.Buffer)
+ logger := slog.New(slog.NewTextHandler(logs, nil))
+ d, e := db.Open(path, logger)
+ if e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() { d.Close() })
+ k, e := crypto.Generate()
+ if e != nil {
+ t.Fatal(e)
+ }
+ m := new(mailer)
+ cfg := equipo.Config{Origin: origin, InstanceKey: "id-test-key", Owners: []string{address}}
+ if enabled {
+ cfg.Home = &connect.DecodedCredentials{Issuer: home, ConsumerID: "equipo", Keys: map[string][]byte{"k": k.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)}
+ }
+ h, e := equipo.App(d, cfg, m, logger)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return &fixture{d, h, k, m, logs, path, origin, home}
+}
+func (f *fixture) request(method, path, origin string, form url.Values, cookies ...*http.Cookie) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, f.origin+path, strings.NewReader(form.Encode()))
+ if method == "POST" {
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ }
+ if origin != "" {
+ req.Header.Set("Origin", origin)
+ }
+ for _, c := range cookies {
+ if c != nil {
+ req.AddCookie(c)
+ }
+ }
+ out := httptest.NewRecorder()
+ f.h.ServeHTTP(out, req)
+ return out
+}
+func cookie(t *testing.T, w *httptest.ResponseRecorder, name string) *http.Cookie {
+ t.Helper()
+ for _, c := range w.Result().Cookies() {
+ if c.Name == name && c.Value != "" && c.MaxAge >= 0 {
+ return c
+ }
+ }
+ t.Fatalf("no cookie %s, status %d body %.200s", name, w.Code, w.Body.String())
+ return nil
+}
+func (f *fixture) local(t *testing.T, who string) *http.Cookie {
+ t.Helper()
+ now := time.Now().UTC()
+ token, hash, e := sessions.NewToken()
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = f.db.Writer().Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, who, "magiclink", "", now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)); e != nil {
+ t.Fatal(e)
+ }
+ return &http.Cookie{Name: "__Host-rastrillo_session", Value: token, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}
+}
+func (f *fixture) signed(t *testing.T, nonce, subject string, at time.Time) string {
+ t.Helper()
+ now := time.Now()
+ jti, _ := assertion.RandomID()
+ token, e := assertion.Sign(f.k, assertion.Claims{Version: 1, KeyID: "k", Issuer: f.issuer, Audience: f.origin, Subject: subject, ID: jti, Nonce: nonce, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: at.Unix()})
+ if e != nil {
+ t.Fatal(e)
+ }
+ return token
+}
+func (f *fixture) exchange(t *testing.T, init, local *http.Cookie, subject string) (*httptest.ResponseRecorder, []*http.Cookie) {
+ t.Helper()
+ start := f.request("GET", "/auth/home?return_to=%2Fwork", "", nil, init, local)
+ if start.Code != 303 {
+ t.Fatalf("start %d %s", start.Code, start.Body.String())
+ }
+ u, e := url.Parse(start.Header().Get("Location"))
+ if e != nil {
+ t.Fatal(e)
+ }
+ q := u.Query()
+ if q.Get("consumer") != "equipo" || len(q) != 2+btoi(init != nil) {
+ t.Fatal("authorize query", q)
+ }
+ if init != nil && q.Get("max_age") != "300" {
+ t.Fatal("link omitted fresh prompt")
+ }
+ receipt := f.request("POST", "/auth/assertion", f.issuer, url.Values{"assertion": {f.signed(t, q.Get("nonce"), subject, time.Now())}})
+ if receipt.Code != 303 {
+ t.Fatalf("callback %d %s", receipt.Code, receipt.Body.String())
+ }
+ cookies := []*http.Cookie{cookie(t, start, "__Host-equipo-id-pending"), cookie(t, receipt, "__Host-equipo-id-inbox"), init, local}
+ done := f.request("GET", "/auth/finish", "", nil, cookies...)
+ return done, cookies
+}
+func btoi(b bool) int {
+ if b {
+ return 1
+ }
+ return 0
+}
+func (f *fixture) link(t *testing.T) *http.Cookie {
+ t.Helper()
+ old := f.local(t, address)
+ start := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"link"}}, old)
+ if start.Code != 303 {
+ t.Fatalf("reauth begin %d %s", start.Code, start.Body.String())
+ }
+ fresh := f.local(t, address)
+ end := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, cookie(t, start, "__Host-equipo-id-reauth"))
+ if end.Code != 303 {
+ t.Fatalf("reauth end %d %s", end.Code, end.Body.String())
+ }
+ done, _ := f.exchange(t, cookie(t, end, "__Host-equipo-id-init"), fresh, person)
+ if done.Code != 303 {
+ t.Fatalf("link finish %d %s", done.Code, done.Body.String())
+ }
+ proof := cookie(t, done, "__Host-equipo-id-proof")
+ page := f.request("GET", "/account/home/confirm", "", nil, fresh, proof)
+ if page.Code != 200 {
+ t.Fatalf("confirm page %d %.200s", page.Code, page.Body.String())
+ }
+ confirm := f.request("POST", "/account/home/confirm", f.origin, nil, fresh, proof)
+ if confirm.Code != 303 {
+ t.Fatalf("confirm %d %s", confirm.Code, confirm.Body.String())
+ }
+ return fresh
+}
+func TestIDDoorOffAndUnlinked(t *testing.T) {
+ off := newFixture(t, false)
+ if strings.Contains(off.request("GET", "/signin", "", nil).Body.String(), "Sign in with Oficina ID") {
+ t.Fatal("door enabled without config")
+ }
+ f := newFixture(t, true)
+ if !strings.Contains(f.request("GET", "/signin", "", nil).Body.String(), "Sign in with Oficina ID") {
+ t.Fatal("missing door")
+ }
+ done, _ := f.exchange(t, nil, nil, person)
+ if done.Code != 403 || !strings.Contains(done.Body.String(), "No Equipo account is linked to this Oficina ID.") || !strings.Contains(done.Body.String(), "Sign in by email") {
+ t.Fatal("unlinked path", done.Code, done.Body.String())
+ }
+ var n int
+ if e := f.db.Writer().QueryRow("SELECT count(*) FROM members").Scan(&n); e != nil || n != 1 {
+ t.Fatal("created account", n, e)
+ }
+}
+func TestIDFullLinkSigninUnlink(t *testing.T) {
+ f := newFixture(t, true)
+ local := f.link(t)
+ settings := f.request("GET", "/conversation/settings/oficina-id", "", nil, local)
+ if settings.Code != 200 || !strings.Contains(settings.Body.String(), person) || !strings.Contains(settings.Body.String(), "Linked on") {
+ t.Fatal("linked settings", settings.Code, settings.Body.String())
+ }
+ done, _ := f.exchange(t, nil, nil, person)
+ if done.Code != 303 {
+ t.Fatal("signin", done.Code, done.Body.String())
+ }
+ home := cookie(t, done, "__Host-rastrillo_session")
+ if r := f.request("GET", "/work", "", nil, home); r.Code != 200 {
+ t.Fatal("home session admission", r.Code)
+ }
+ start := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"unlink"}}, home)
+ reauth := cookie(t, start, "__Host-equipo-id-reauth")
+ fresh := f.local(t, address)
+ if r := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, reauth); r.Code != 303 {
+ t.Fatal("unlink reauth", r.Code)
+ }
+ if r := f.request("POST", "/account/home/unlink", f.origin, nil, fresh, reauth); r.Code != 303 {
+ t.Fatal("unlink", r.Code, r.Body.String())
+ }
+ if r := f.request("GET", "/work", "", nil, home); r.Code == 200 {
+ t.Fatal("Home session survived unlink")
+ }
+ if r := f.request("GET", "/work", "", nil, local); r.Code != 200 {
+ t.Fatal("local session lost", r.Code)
+ }
+ if r, _ := f.exchange(t, nil, nil, person); r.Code != 403 {
+ t.Fatal("unlinked subject signed in")
+ }
+}
+func TestIDLeakage(t *testing.T) {
+ f := newFixture(t, true)
+ f.link(t)
+ done, _ := f.exchange(t, nil, nil, person)
+ if done.Code != 303 {
+ t.Fatal(done.Code)
+ }
+ for _, table := range []string{"equipo_id_accounts", "equipo_id_reauth", "home_identity_links", "home_link_flows", "oficina_handoff_pending", "oficina_handoff_inbox", "audit_events"} {
+ rows, e := f.db.Writer().Query("SELECT * FROM " + table)
+ if e != nil {
+ t.Fatal(e)
+ }
+ cols, _ := rows.Columns()
+ for rows.Next() {
+ v := make([]any, len(cols))
+ ptr := make([]any, len(v))
+ for i := range v {
+ ptr[i] = &v[i]
+ }
+ if e = rows.Scan(ptr...); e != nil {
+ t.Fatal(e)
+ }
+ for _, value := range v {
+ var raw []byte
+ switch value := value.(type) {
+ case []byte:
+ raw = value
+ case string:
+ raw = []byte(value)
+ }
+ if bytes.Contains(raw, []byte(address)) || bytes.Contains(raw, []byte(homeAddress)) {
+ t.Fatal("address in identity storage", table)
+ }
+ }
+ }
+ rows.Close()
+ }
+ var n int
+ if e := f.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE method=? AND subject LIKE '%@%'", oficinaid.Method).Scan(&n); e != nil || n != 0 {
+ t.Fatal("address in Home session")
+ }
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ raw, e := os.ReadFile(f.path + suffix)
+ if e != nil && !os.IsNotExist(e) {
+ t.Fatal(e)
+ }
+ if bytes.Contains(raw, []byte(homeAddress)) {
+ t.Fatal("Home address at rest")
+ }
+ }
+ if strings.Contains(f.logs.String(), address) || strings.Contains(f.logs.String(), homeAddress) {
+ t.Fatal("address in logs")
+ }
+}
+func fields(body, action string) url.Values {
+ v := url.Values{}
+ for _, form := range regexp.MustCompile(`(?s)<form\b[^>]*>.*?</form>`).FindAllString(body, -1) {
+ if !strings.Contains(form, `action="`+action+`"`) {
+ continue
+ }
+ for _, in := range regexp.MustCompile(`<input\b[^>]*>`).FindAllString(form, -1) {
+ attrs := map[string]string{}
+ for _, m := range regexp.MustCompile(`([a-z_-]+)="([^"]*)"`).FindAllStringSubmatch(in, -1) {
+ attrs[m[1]] = html.UnescapeString(m[2])
+ }
+ if attrs["name"] != "" {
+ v.Set(attrs["name"], attrs["value"])
+ }
+ }
+ }
+ return v
+}
+func (f *fixture) email(t *testing.T) { f.emailWith(t, "/signin?force=1", nil) }
+func (f *fixture) emailWith(t *testing.T, start string, original ...*http.Cookie) *http.Cookie {
+ t.Helper()
+ page := f.request("GET", start, "", nil, original...)
+ form := fields(page.Body.String(), "/auth/begin")
+ form.Set("address", address)
+ time.Sleep(pow.DefaultMinAge + 20*time.Millisecond)
+ begin := f.request("POST", "/auth/begin", f.origin, form, original...)
+ if begin.Code != 303 {
+ t.Fatal("email begin", begin.Code, begin.Body.String())
+ }
+ f.mail.mu.Lock()
+ body := f.mail.body
+ f.mail.mu.Unlock()
+ var target string
+ for _, word := range strings.Fields(body) {
+ if strings.Contains(word, "/auth/verify?") {
+ u, e := url.Parse(word)
+ if e != nil {
+ t.Fatal(e)
+ }
+ target = u.RequestURI()
+ break
+ }
+ }
+ if target == "" {
+ t.Fatal("no emailed link")
+ }
+ jar := mergeCookies(original, page.Result().Cookies(), begin.Result().Cookies())
+ confirm := f.request("GET", target, "", nil, jar...)
+ if confirm.Code != 200 {
+ t.Fatal("email confirmation", confirm.Code)
+ }
+ values := fields(confirm.Body.String(), "/auth/verify")
+ done := f.request("POST", "/auth/verify", f.origin, values, mergeCookies(jar, confirm.Result().Cookies())...)
+ if done.Code != 303 {
+ t.Fatal("email verify", done.Code, done.Body.String())
+ }
+ startURL, _ := url.Parse(start)
+ if back := startURL.Query().Get("return_to"); back != "" && done.Header().Get("Location") != back {
+ t.Fatal("email lost return target", done.Header().Get("Location"))
+ }
+ local := cookie(t, done, "__Host-rastrillo_session")
+ if r := f.request("GET", "/work", "", nil, local); r.Code != 200 {
+ t.Fatal("local admission", r.Code)
+ }
+ return local
+}
+func TestIDHangingHomeLocalSignoutAndEmail(t *testing.T) {
+ entered := make(chan struct{}, 1)
+ stop := make(chan struct{})
+ home := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { entered <- struct{}{}; <-stop }))
+ defer home.Close()
+ defer close(stop)
+ // Establish a real connection which remains unanswered during local operations.
+ go func() {
+ resp, e := home.Client().Get(home.URL)
+ if e == nil {
+ resp.Body.Close()
+ }
+ }()
+ <-entered
+ u, _ := url.Parse(home.URL)
+ _, port, _ := net.SplitHostPort(u.Host)
+ transport := home.Client().Transport.(*http.Transport).Clone()
+ transport.TLSClientConfig = transport.TLSClientConfig.Clone()
+ transport.TLSClientConfig.InsecureSkipVerify = true // The test issuer is served only on loopback.
+ transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, u.Host)
+ }
+ previous := http.DefaultClient
+ http.DefaultClient = &http.Client{Transport: transport, Timeout: 2 * time.Second}
+ defer func() { http.DefaultClient = previous; transport.CloseIdleConnections() }()
+ f := fixtureAt(t, true, appOrigin, "https://id.example:"+port)
+ f.link(t)
+ done, _ := f.exchange(t, nil, nil, person)
+ session := cookie(t, done, "__Host-rastrillo_session")
+ before := time.Now()
+ out := f.request("POST", "/signout", f.origin, nil, session)
+ if out.Code != 303 || out.Header().Get("Location") != "/signed-out" || time.Since(before) > time.Second {
+ t.Fatal("signout waited for Home")
+ }
+ landing := f.request("GET", "/signed-out", "", nil, cookie(t, out, "__Host-equipo-id-logout"))
+ if landing.Code != 200 || !strings.Contains(landing.Body.String(), "Sign out of Oficina ID too") {
+ t.Fatal("local landing", landing.Code)
+ }
+ if r := f.request("GET", "/work", "", nil, session); r.Code == 200 {
+ t.Fatal("session not revoked")
+ }
+ f.email(t)
+ localForUnlink := f.local(t, address)
+ reauth := f.request("POST", "/account/home/reauth", f.origin, url.Values{"purpose": {"unlink"}}, localForUnlink)
+ fresh := f.local(t, address)
+ proof := cookie(t, reauth, "__Host-equipo-id-reauth")
+ if r := f.request("GET", "/account/home/reauth-complete", "", nil, fresh, proof); r.Code != 303 {
+ t.Fatal("outage reauth", r.Code)
+ }
+ before = time.Now()
+ if r := f.request("POST", "/account/home/unlink", f.origin, nil, fresh, proof); r.Code != 303 || time.Since(before) > time.Second {
+ t.Fatal("unlink depends on Home", r.Code)
+ }
+ local := f.local(t, address)
+ out = f.request("POST", "/signout", f.origin, nil, local)
+ landing = f.request("GET", "/signed-out", "", nil, out.Result().Cookies()...)
+ if strings.Contains(landing.Body.String(), "Sign out of Oficina ID too") {
+ t.Fatal("local session offered Home hop")
+ }
+}
+
+func mergeCookies(groups ...[]*http.Cookie) []*http.Cookie {
+ jar := map[string]*http.Cookie{}
+ for _, group := range groups {
+ for _, c := range group {
+ if c == nil {
+ continue
+ }
+ if c.MaxAge < 0 {
+ delete(jar, c.Name)
+ } else {
+ jar[c.Name] = c
+ }
+ }
+ }
+ var out []*http.Cookie
+ for _, c := range jar {
+ out = append(out, c)
+ }
+ return out
+}
diff --git a/internal/idtest/main_test.go b/internal/idtest/main_test.go
new file mode 100644
index 00000000..c4947702
--- /dev/null
+++ b/internal/idtest/main_test.go
@@ -0,0 +1,9 @@
+package idtest
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/plan3test/plan3_upgrade_test.go b/internal/plan3test/plan3_upgrade_test.go
index d8ed59d1..c0ed0ce1 100644
--- a/internal/plan3test/plan3_upgrade_test.go
+++ b/internal/plan3test/plan3_upgrade_test.go
@@ -27,6 +27,10 @@ func TestPlan3Upgrade(t *testing.T) {
defer func() { must(t, d.Close()) }()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
+ // These snapshots predate Oficina ID and its cross-store triggers.
+ if strings.HasPrefix(m.ID, "oficina_handoff/") || strings.HasPrefix(m.ID, "oficina_connect_link/") || strings.HasPrefix(m.ID, "equipo_identity/") {
+ continue
+ }
if !strings.HasPrefix(m.ID, "equipo/") || version == "main" && m.ID == "equipo/0019_direct_reconcile" || strings.Split(strings.TrimPrefix(m.ID, "equipo/"), "_")[0] <= map[string]string{"0018": "0018", "0023": "0023", "main": "0018"}[version] {
before.Add(m)
}