oficina / equipo Public

Add explicit Oficina ID sign-in and account linking to Equipo

Paul Campbell pushed by paul@keymail.dev ce505f47f3c7300de7b4366b1abc8b09d0402056 parent 47b6eb6
42 files changed, +2,016 −58
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +21 −0
  • go.mod +9 −3
  • go.sum +6 −0
  • internal/equipo/app.go +18 −4
  • internal/equipo/auth.go +5 −1
  • internal/equipo/chat_page.go +2 −2
  • internal/equipo/config.go +10 −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/library/handlers.go +2 −2
  • internal/equipo/migrations.go +3 −1
  • internal/equipo/migrations/0082_oficina_id.sql +2 −0
  • internal/equipo/models.go +3 −0
  • internal/equipo/oficina_id.go +51 −0
  • internal/equipo/oficinaid/http.go +307 −0
  • internal/equipo/oficinaid/link.go +211 −0
  • internal/equipo/oficinaid/signout.go +63 −0
  • internal/equipo/oficinaid/store.go +275 −0
  • internal/equipo/oficinaid/store_test.go +356 −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/idtest/id_browser_test.go +147 −0
  • internal/idtest/id_test.go +389 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 27313757..1078e886 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 19707 - 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..095bf076 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -4704,6 +4704,27 @@ 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).
+
+- `id.door`: Sign in with Oficina ID
+- `id.title`: Oficina ID
+- `id.unlinked`: No Equipo account is linked to this Oficina ID.
+- `id.help`: Sign in by email, then link your Oficina ID in Settings.
+- `id.link`: Link Oficina ID
+- `id.reauth`: Sign in by email again before linking or unlinking your Oficina ID.
+- `id.confirm`: Link this Oficina ID to your Equipo account?
+- `id.confirm_button`: Confirm link
+- `id.unlink`: Unlink Oficina ID
+- `id.unlink_confirm`: Unlink your Oficina ID? You can still sign in by email. Your work will stay in Equipo.
+- `id.linked_at`: Linked on %s
+- `id.not_linked`: You have not linked an Oficina ID.
+- `id.failed`: This sign-in could not be completed. Try again or sign in by email.
+- `id.email`: Sign in by email
+- `id.signed_out`: You are signed out of Equipo.
+- `id.home_signout`: Sign out of Oficina ID too
+- `copyIDConfig`: Oficina ID configuration is incomplete or invalid.
+
+
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..20c62166 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-20261113224411-fe44c43fd256
+ amadan.net/oficina/home/handoff v0.0.0-20261113224054-3010b00019e2
+ 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..ba340f69 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-20261113224411-fe44c43fd256 h1:grzC5lwhUXJw14j/V8axWjBfiBQnQaF7M79BRG5zGA0=
+amadan.net/oficina/home/connect v0.0.0-20261113224411-fe44c43fd256/go.mod h1:7tsJ//7X4o5QkD068WoUGVDxj/e3ygZ2adF+PHhvBxE=
+amadan.net/oficina/home/handoff v0.0.0-20261113224054-3010b00019e2 h1:TNM61Isk73O8sior0TumLPOw2KoPdpKv/kyCCAM0hNk=
+amadan.net/oficina/home/handoff v0.0.0-20261113224054-3010b00019e2/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..b32cbb7e 100644
--- a/internal/equipo/auth.go
+++ b/internal/equipo/auth.go
@@ -43,7 +43,11 @@ 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)
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..1d23e551 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,14 @@ 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 {
+ 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/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..3de6c0c2 100644
--- a/internal/equipo/migrations.go
+++ b/internal/equipo/migrations.go
@@ -1,6 +1,8 @@
package equipo
import (
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/handoff"
"embed"
"amadan.net/rastrillo/rastrillo/auth"
@@ -15,4 +17,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)
diff --git a/internal/equipo/migrations/0082_oficina_id.sql b/internal/equipo/migrations/0082_oficina_id.sql
new file mode 100644
index 00000000..657f3411
--- /dev/null
+++ b/internal/equipo/migrations/0082_oficina_id.sql
@@ -0,0 +1,2 @@
+CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, sealed_address BLOB NOT NULL, 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..3dd0a7b7
--- /dev/null
+++ b/internal/equipo/oficinaid/http.go
@@ -0,0 +1,307 @@
+package oficinaid
+
+import (
+ "encoding/base64"
+ "errors"
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "strings"
+ "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 {
+ 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.Post("/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
+ }
+ 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) {
+ 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", 303)
+ } else {
+ http.Redirect(w, r, "/account/home/unlink", 303)
+ }
+}
+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, 303)
+}
+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, 303)
+}
+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 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ id, ok := h.Session(r)
+ if !ok {
+ var method string
+ if e := h.Store.DB.QueryRowContext(r.Context(), "SELECT method FROM sessions WHERE token_hash=?", sessions.HashToken(h.token(r))).Scan(&method); e == nil && method == Method {
+ h.fail(w, r, ErrRefused)
+ return
+ }
+ h.Auth.RequireSession(next).ServeHTTP(w, r)
+ return
+ }
+ if string(id.Method) != Method {
+ h.Auth.RequireSession(next).ServeHTTP(w, r)
+ return
+ }
+ // Downstream handlers receive the same admitted member identity for either door.
+ next.ServeHTTP(w, identity.With(sessions.WithSession(r, sessions.Session{Subject: id.Address, Method: string(id.Method), AuthTime: id.AuthTime, At: id.At}), id))
+ })
+}
diff --git a/internal/equipo/oficinaid/link.go b/internal/equipo/oficinaid/link.go
new file mode 100644
index 00000000..932ed8a2
--- /dev/null
+++ b/internal/equipo/oficinaid/link.go
@@ -0,0 +1,211 @@
+package oficinaid
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "time"
+
+ "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
+ }
+ 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 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
+ }
+ for _, table := range []string{"home_link_flows", "oficina_handoff_pending", "oficina_handoff_inbox", "equipo_id_reauth"} {
+ 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/signout.go b/internal/equipo/oficinaid/signout.go
new file mode 100644
index 00000000..96d84858
--- /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", 303)
+}
+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..2c0c5d89
--- /dev/null
+++ b/internal/equipo/oficinaid/store.go
@@ -0,0 +1,275 @@
+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, sealed_address BLOB NOT NULL, 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 {
+ ID int64
+ Binding string `gorm:"not null;unique"`
+ SealedAddress []byte `gorm:"not null"`
+ 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 sealed []byte
+ if e := q.QueryRowContext(ctx, "SELECT sealed_address FROM equipo_id_accounts WHERE id=?", id).Scan(&sealed); e != nil {
+ return "", e
+ }
+ plain, e := s.seal.Open("account."+strconv.FormatInt(id, 10), sealed)
+ if e != nil {
+ return "", ErrRefused
+ }
+ address := string(plain)
+ var active bool
+ if e = q.QueryRowContext(ctx, "SELECT active FROM members WHERE address=?", address).Scan(&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
+ if e := tx.QueryRowContext(ctx, "SELECT active FROM members WHERE address=?", address).Scan(&active); e != nil || !active {
+ 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,sealed_address) VALUES(?,?)", binding, []byte{})
+ if e != nil {
+ return 0, e
+ }
+ id, e = result.LastInsertId()
+ if e != nil {
+ return 0, e
+ }
+ sealed, e := s.seal.Seal("account."+strconv.FormatInt(id, 10), []byte(address))
+ if e != nil {
+ return 0, e
+ }
+ _, e = tx.ExecContext(ctx, "UPDATE equipo_id_accounts SET sealed_address=? WHERE id=?", sealed, id)
+ return id, e
+}
+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() {
+ 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..5f906981
--- /dev/null
+++ b/internal/equipo/oficinaid/store_test.go
@@ -0,0 +1,356 @@
+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); 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 VALUES(?,1,0)", 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)
+ 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(), local, 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")
+ }
+}
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/idtest/id_browser_test.go b/internal/idtest/id_browser_test.go
new file mode 100644
index 00000000..dc574091
--- /dev/null
+++ b/internal/idtest/id_browser_test.go
@@ -0,0 +1,147 @@
+//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"]')`))
+ 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("door overflows at %d", 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("oficina-id-door-%d.png", width)), shot, 0600)
+ }
+ return nil
+ }))
+ }
+ 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")`))
+ 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..36765c9e
--- /dev/null
+++ b/internal/idtest/id_test.go
@@ -0,0 +1,389 @@
+package idtest
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "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)
+ }
+ raw, _ := json.Marshal(v)
+ 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) {
+ t.Helper()
+ page := f.request("GET", "/signin?force=1", "", nil)
+ 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)
+ 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")
+ }
+ confirm := f.request("GET", target, "", nil)
+ 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, confirm.Result().Cookies()...)
+ if done.Code != 303 {
+ t.Fatal("email verify", done.Code, done.Body.String())
+ }
+ local := cookie(t, done, "__Host-rastrillo_session")
+ if r := f.request("GET", "/work", "", nil, local); r.Code != 200 {
+ t.Fatal("local admission", r.Code)
+ }
+}
+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)
+ host, port, _ := net.SplitHostPort(u.Host)
+ _ = host
+ 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)
+ 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")
+ }
+}