oficina / base Public

Sign in to Base with Oficina ID

Base becomes a Home consumer through Home's connect package, wired as
Calendar wires it. BASE_HOME_ISSUER, BASE_HOME_CONSUMER_ID,
BASE_HOME_KEYS_BASE64 and BASE_HOME_DEK_BASE64 (plus the optional
HOME_DIRECTORY_ORIGIN) turn it on; none leaves Base as it was, and some
but not all refuses to start.

With it on, /signin leads with "Sign in with Oficina" and keeps the email
form and passkey below; /signin/local is the local door connect sends
people to. An Oficina sign-in with no link asks for one local sign-in,
which goes straight on to connecting the accounts. The roster stays the
authority: an Oficina session resolves through its link to a member who
must still exist, and nothing creates a member. Settings offers "Connect
your Oficina account" until there is a link, sign-out hops on to the
issuer's /signout, and POST /auth/assertion is the only route outside the
CSRF check. Installed apps get the same assertions as before, for the
same member, however they signed in.

New strings are listed in docs/copy-pending.md for review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev cf02cb72f8b160042cb71f5ae874e9591828157d parent 2d48ebc
21 files changed, +1,142 −48
  • README.md +21 −0
  • cmd/base/main.go +7 −1
  • docs/copy-pending.md +42 −0
  • go.mod +3 −0
  • go.sum +6 −0
  • internal/config/config.go +4 −0
  • internal/config/home.go +21 −0
  • internal/config/home_test.go +77 −0
  • internal/look/static/app.css +5 −0
  • internal/store/migrations.go +18 −0
  • internal/web/app.go +105 −22
  • internal/web/oficina.go +187 −0
  • internal/web/oficina_internal_test.go +33 −0
  • internal/web/settings.go +38 −13
  • internal/web/signin.go +11 −1
  • internal/web/templates/oficina.html +12 −0
  • internal/web/templates/settings.html +4 −3
  • internal/web/templates/signin.html +4 −2
  • internal/webtest/harness_test.go +11 −6
  • internal/webtest/oficina_harness_test.go +240 −0
  • internal/webtest/oficina_test.go +293 −0
diff --git a/README.md b/README.md
index 8c04c4e..69e0d8d 100644
--- a/README.md
+++ b/README.md
@@ -47,6 +47,27 @@ Everything is an environment variable. `BASE_ORIGIN`, `BASE_OWNER` and
- `BASE_ALLOW_LOGGED_MAIL=1` prints sign-in links instead of sending them.
Local only; Base refuses it on a non-loopback origin.
+To let your team sign in with Oficina ID, set all four of these. Without them
+Base has only its own sign-in. With some but not all, it refuses to start.
+Oficina ID needs `https://` in `BASE_ORIGIN`.
+
+- `BASE_HOME_ISSUER` is Oficina ID's address, such as `https://id.oficina.works`.
+- `BASE_HOME_CONSUMER_ID` is the id Oficina ID lists Base under, with Base's
+ origin.
+- `BASE_HOME_KEYS_BASE64` is Oficina ID's public keys: base64 of a JSON object
+ that maps each key id to the base64 of that public key.
+- `BASE_HOME_DEK_BASE64` is base64 of 32 random bytes that seal Oficina
+ sign-ins in flight and the links between accounts. Give Base a key of its
+ own and keep it: changing it breaks every connected account.
+ `openssl rand -base64 32` makes a good one.
+- `HOME_DIRECTORY_ORIGIN` is optional: the address of the Oficina directory.
+ Base checks it but doesn't link to it yet.
+
+With Oficina ID on, the sign-in page leads with "Sign in with Oficina", and
+email and passkeys stay below it. Everyone signs in with their email once and
+connects their Oficina account from Settings; after that, Oficina signs them
+in. Only members get in, and inviting people is still by email.
+
To install apps, Base also needs to reach the Platform. Without these five and
`BASE_ASSERTION_KEY`, it still runs and logs that installs are off.
diff --git a/cmd/base/main.go b/cmd/base/main.go
index ac155e6..a8231af 100644
--- a/cmd/base/main.go
+++ b/cmd/base/main.go
@@ -7,6 +7,7 @@ import (
"os"
"time"
+ "amadan.net/oficina/home/connect"
"amadan.net/rastrillo/rastrillo"
"amadan.net/rastrillo/rastrillo/db"
_ "amadan.net/rastrillo/rastrillo/locales/en"
@@ -34,6 +35,11 @@ func run(logger *slog.Logger) error {
if err != nil {
return err
}
+ // Sign-in with Oficina ID: off with no BASE_HOME_* settings, and a
+ // refusal to start with only some of them.
+ if cfg.Home, err = config.LoadHome(connect.CredentialsFromEnv("BASE"), cfg.Origin); err != nil {
+ return err
+ }
opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: "base.db", Logger: logger})
if err != nil {
return err
@@ -44,7 +50,7 @@ func run(logger *slog.Logger) error {
}
defer d.Close()
ctx := context.Background()
- if _, err := migrate.Apply(ctx, d, store.BootSchema); err != nil {
+ if _, err := migrate.Apply(ctx, d, store.Boot(cfg.Home != nil)); err != nil {
return err
}
if err := store.Bootstrap(ctx, d.Writer(), cfg.Owner); err != nil {
diff --git a/docs/copy-pending.md b/docs/copy-pending.md
index 2a37a06..938648a 100644
--- a/docs/copy-pending.md
+++ b/docs/copy-pending.md
@@ -168,3 +168,45 @@ Passkeys (sign-in page and Settings):
| internal/web/settings.go | Passkey list failed (503) | unavailable |
| README.md | Whole file (what Base is, local run, settings, deploy, operator steps, app contract) | README.md — whole file |
| docs/live-check.md | Whole file (the by-hand check against a real account, R26) | docs/live-check.md — whole file |
+
+## Review 4 (pending): sign-in with Oficina ID
+
+Not yet reviewed. New strings Base wrote itself:
+
+| File | Context | Text |
+|---|---|---|
+| internal/web/templates/signin.html | Sign-in page with Oficina ID on, the lead button | Sign in with Oficina |
+| internal/web/templates/signin.html | Sign-in page with Oficina ID on, the line between that button and the email form (replaces "Use your work email." there) | Or use your work email. |
+| internal/web/templates/settings.html | Settings label, shown only while no Oficina account is connected | Oficina account |
+| internal/web/templates/settings.html | Oficina account row, value | Not connected |
+| internal/web/templates/settings.html | Line under the sign-out button with Oficina ID on (instead of "This signs you out of Base only. [...]") | This signs you out of Base and your Oficina account. Apps you've opened stay signed in until you sign out of each one. |
+| internal/web/templates/oficina.html | Tab title of the connect pages and the signed-out page | {page title} · {Base name} |
+| internal/web/app.go | Adding a passkey while signed in with Oficina (403; Settings hides the button, so only a crafted request sees it) | forbidden |
+| internal/config/home.go | Start-up refusal: some BASE_HOME_* settings set but not all, or one that doesn't decode (operator-facing log) | BASE_HOME_ISSUER, BASE_HOME_CONSUMER_ID, BASE_HOME_KEYS_BASE64 and BASE_HOME_DEK_BASE64 turn on Oficina ID sign-in: set all four to valid values, or none (BASE_ORIGIN must be https, and HOME_DIRECTORY_ORIGIN, if set, a bare https origin) |
+| internal/web/oficina.go | /signin could not look up the signed-in member (503) | unavailable |
+| README.md | Settings: the Oficina ID paragraph, its five bullets and the paragraph after them (new lines only; nothing else changed) | To let your team sign in with Oficina ID, set all four of these. [...] Only members get in, and inviting people is still by email. |
+
+Reused as Calendar ships them, on the pages Base draws itself (internal/web/templates/oficina.html). The connect pages' words are connect's `English` (amadan.net/oficina/home/connect, view.go); the signed-out page's are the Oficina door's (estilo `chrome.English`), with Base's name where Calendar's says "Calendar":
+
+| File | Context | Text |
+|---|---|---|
+| internal/web/templates/settings.html | Settings button, shown only while no Oficina account is connected (connect `menu_action`) | Connect your Oficina account |
+| connect English, via oficina.html | Connect page, title | Connect your Oficina account |
+| connect English, via oficina.html | Connect page, body | Use your Oficina account to sign in to this account. Your content and sharing settings stay as they are. |
+| connect English, via oficina.html | Connect page, button | Connect |
+| connect English, via oficina.html | Connect and confirm pages, back button (goes to Settings) | Back |
+| connect English, via oficina.html | Confirm page, title | Connect these two accounts? |
+| connect English, via oficina.html | Confirm page, body (the member's address below it) | Your Oficina account is confirmed. Connect it to the account below, and you can sign in to that account with Oficina from now on. |
+| connect English, via oficina.html | Confirm page, button | Connect accounts |
+| connect English, via oficina.html | Oficina sign-in with no connected account here (403), title | Oficina account not connected |
+| connect English, via oficina.html | Same, body | Sign in to your existing account once to connect it to your Oficina account. |
+| connect English, via oficina.html | Same, and the failure page, button (to /signin/local) | Sign in to your existing account |
+| connect English, via oficina.html | Connecting failed, title | Could not connect accounts |
+| connect English, via oficina.html | Connecting failed, body | Return to the app and start again. |
+| connect English, via oficina.html | Connected, title | Accounts connected |
+| connect English, via oficina.html | Connected, body | You can now use your Oficina account to sign in to this account. |
+| connect English, via oficina.html | Connected, button | Back to the app |
+| internal/web/oficina.go | Where Oficina's sign-out lands (/signed-out), tab title | Signed out |
+| internal/web/oficina.go | Signed-out page, heading | You’re signed out |
+| internal/web/oficina.go | Signed-out page, body | You’ve signed out of {Base name} on this device. |
+| internal/web/oficina.go | Signed-out page, button (to /signin) | Sign in |
diff --git a/go.mod b/go.mod
index ea4a130..960db01 100644
--- a/go.mod
+++ b/go.mod
@@ -3,6 +3,8 @@ module amadan.net/carlos/base
go 1.26.0
require (
+ amadan.net/oficina/home/connect v0.0.0-20261110233753-14c83d71b992
+ amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/rastrillo/rastrillo v0.33.0
github.com/chromedp/cdproto v0.158.6
github.com/chromedp/chromedp v0.21.0
@@ -10,6 +12,7 @@ require (
)
require (
+ amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d // indirect
amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
diff --git a/go.sum b/go.sum
index 8e1b17f..77b68c1 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-20261110233753-14c83d71b992 h1:pyAvFStnIR6D/MSfMYpRQG+Lete8eYCF10nBdjtBbhA=
+amadan.net/oficina/home/connect v0.0.0-20261110233753-14c83d71b992/go.mod h1:7tsJ//7X4o5QkD068WoUGVDxj/e3ygZ2adF+PHhvBxE=
+amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM=
+amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/rastrillo/rastrillo v0.33.0 h1:aYK33p7SIKOglr6rZM3EQLXdpz02Rnq9NB4Zhitz5yw=
amadan.net/rastrillo/rastrillo v0.33.0/go.mod h1:IQnXick/ERWFvhqiQey87Zw1Td2aHlyloykFQB0g0pI=
amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
diff --git a/internal/config/config.go b/internal/config/config.go
index b6aabfc..86fc4af 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -13,6 +13,7 @@ import (
"time"
_ "time/tzdata" // the release binary must not depend on host zoneinfo
+ "amadan.net/oficina/home/connect"
"amadan.net/rastrillo/rastrillo/assertion"
"amadan.net/rastrillo/rastrillo/crypto"
@@ -45,6 +46,9 @@ type Config struct {
// InstanceKey seals sign-in state (BASE_INSTANCE_KEY). Keep it secret and
// stable: changing it invalidates links and sign-ins in flight.
InstanceKey string
+ // Home turns on sign-in with Oficina ID. Nil (no BASE_HOME_* settings)
+ // leaves it off; LoadHome sets it.
+ Home *connect.DecodedCredentials
}
// Load reads the configuration. getenv is os.Getenv in production.
diff --git a/internal/config/home.go b/internal/config/home.go
new file mode 100644
index 0000000..884f218
--- /dev/null
+++ b/internal/config/home.go
@@ -0,0 +1,21 @@
+package config
+
+import (
+ "errors"
+
+ "amadan.net/oficina/home/connect"
+)
+
+// LoadHome decodes the Oficina ID settings, which connect.CredentialsFromEnv
+// reads: BASE_HOME_ISSUER, BASE_HOME_CONSUMER_ID, BASE_HOME_KEYS_BASE64,
+// BASE_HOME_DEK_BASE64 and, optionally, HOME_DIRECTORY_ORIGIN. All four
+// empty (creds nil) leaves Oficina ID off and returns nil. Some but not all,
+// or any that do not decode, is an error, so Base never falls back to its own
+// sign-in by accident. The error never carries a value.
+func LoadHome(creds *connect.Credentials, origin string) (*connect.DecodedCredentials, error) {
+ home, err := connect.DecodeCredentials(creds, origin)
+ if err != nil {
+ return nil, errors.New("BASE_HOME_ISSUER, BASE_HOME_CONSUMER_ID, BASE_HOME_KEYS_BASE64 and BASE_HOME_DEK_BASE64 turn on Oficina ID sign-in: set all four to valid values, or none (BASE_ORIGIN must be https, and HOME_DIRECTORY_ORIGIN, if set, a bare https origin)")
+ }
+ return home, nil
+}
diff --git a/internal/config/home_test.go b/internal/config/home_test.go
new file mode 100644
index 0000000..4fc9d04
--- /dev/null
+++ b/internal/config/home_test.go
@@ -0,0 +1,77 @@
+package config
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+const homeOrigin = "https://base.example.com"
+
+// homeEnv sets all four BASE_HOME_* settings to working values.
+func homeEnv(t *testing.T) {
+ t.Helper()
+ key, err := crypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ keys, _ := json.Marshal(map[string]string{"k1": base64.StdEncoding.EncodeToString(key.SignPub())})
+ t.Setenv("BASE_HOME_ISSUER", "https://id.oficina.works")
+ t.Setenv("BASE_HOME_CONSUMER_ID", "base")
+ t.Setenv("BASE_HOME_KEYS_BASE64", base64.StdEncoding.EncodeToString(keys))
+ t.Setenv("BASE_HOME_DEK_BASE64", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)))
+}
+
+func TestLoadHomeOffWhenUnset(t *testing.T) {
+ for _, k := range []string{"BASE_HOME_ISSUER", "BASE_HOME_CONSUMER_ID", "BASE_HOME_KEYS_BASE64", "BASE_HOME_DEK_BASE64", "HOME_DIRECTORY_ORIGIN"} {
+ t.Setenv(k, "")
+ }
+ home, err := LoadHome(connect.CredentialsFromEnv("BASE"), homeOrigin)
+ if err != nil || home != nil {
+ t.Fatalf("all empty: %+v, %v; want off", home, err)
+ }
+}
+
+func TestLoadHomeOnWhenComplete(t *testing.T) {
+ homeEnv(t)
+ t.Setenv("HOME_DIRECTORY_ORIGIN", "https://oficina.works")
+ home, err := LoadHome(connect.CredentialsFromEnv("BASE"), homeOrigin)
+ if err != nil || home == nil {
+ t.Fatalf("complete: %+v, %v", home, err)
+ }
+ if home.Issuer != "https://id.oficina.works" || home.ConsumerID != "base" || len(home.DEK) != 32 || len(home.Keys) != 1 || home.Directory != "https://oficina.works" {
+ t.Errorf("decoded: %+v", home)
+ }
+}
+
+// One setting missing is a mistake, not a choice: Base refuses to start
+// rather than quietly falling back to its own sign-in.
+func TestLoadHomeRefusesPartialSettings(t *testing.T) {
+ for _, missing := range []string{"BASE_HOME_ISSUER", "BASE_HOME_CONSUMER_ID", "BASE_HOME_KEYS_BASE64", "BASE_HOME_DEK_BASE64"} {
+ t.Run(missing, func(t *testing.T) {
+ homeEnv(t)
+ t.Setenv(missing, "")
+ home, err := LoadHome(connect.CredentialsFromEnv("BASE"), homeOrigin)
+ if err == nil || home != nil {
+ t.Fatalf("without %s: %+v, %v; want a refusal", missing, home, err)
+ }
+ if !strings.Contains(err.Error(), "BASE_HOME_") {
+ t.Errorf("error does not name the settings: %v", err)
+ }
+ })
+ }
+}
+
+func TestLoadHomeErrorKeepsValuesOut(t *testing.T) {
+ homeEnv(t)
+ t.Setenv("BASE_HOME_DEK_BASE64", "c2VjcmV0LXNlY3JldA==")
+ _, err := LoadHome(connect.CredentialsFromEnv("BASE"), homeOrigin)
+ if err == nil || strings.Contains(err.Error(), "c2VjcmV0") {
+ t.Fatalf("err = %v", err)
+ }
+}
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index 3b2ae46..5704179 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -87,6 +87,11 @@ button.alt:hover { color: var(--frost); text-decoration: underline; text-underli
button.alt[aria-busy="true"] { cursor: progress; }
.signin .passkey-msg { margin: 0; font-size: 14px; text-align: center; }
.signin .passkey-msg:empty { display: none; }
+/* Oficina ID: the sign-in page's lead button, and the connect pages' actions. */
+.signin a.btn.full { justify-content: center; }
+.signin .btn + .btn, .signin form + .btn { margin-top: 10px; }
+.signin p.or { margin: 18px 0 10px; font-size: 14px; text-align: center; }
+.signin p.addr { color: var(--frost); font-weight: 500; overflow-wrap: anywhere; }
/* Home */
.home { padding: 18px 26px 28px; display: flex; flex-direction: column; }
diff --git a/internal/store/migrations.go b/internal/store/migrations.go
index 180fa3f..cf1b97d 100644
--- a/internal/store/migrations.go
+++ b/internal/store/migrations.go
@@ -4,6 +4,8 @@ package store
import (
"embed"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/handoff"
"amadan.net/rastrillo/rastrillo/auth"
"amadan.net/rastrillo/rastrillo/migrate"
"amadan.net/rastrillo/rastrillo/passkey"
@@ -20,3 +22,19 @@ var Schema = migrate.MustFromFS(migrationFS, "base")
// BootSchema adds the framework tables the sign-in flow needs: sessions,
// email links, the sign-in form's proof and passkeys.
var BootSchema = migrate.Merge(sessions.Schema, auth.Schema, pow.Schema, passkey.Schema, Schema)
+
+// HomeSchema is what Oficina ID sign-in adds: the hand-off exchange and the
+// account links, in the namespaces every Oficina app uses for them.
+var HomeSchema = migrate.Merge(
+ migrate.MustFromFS(handoff.Migrations, "oficina_handoff"),
+ migrate.MustFromFS(linkstore.Migrations, linkstore.SchemaNamespace),
+)
+
+// Boot is the schema to apply at start-up: BootSchema, and HomeSchema too
+// when Oficina ID sign-in is on.
+func Boot(home bool) *migrate.Set {
+ if home {
+ return migrate.Merge(BootSchema, HomeSchema)
+ }
+ return BootSchema
+}
diff --git a/internal/web/app.go b/internal/web/app.go
index 1368637..a141de1 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -14,6 +14,8 @@ import (
"github.com/go-chi/chi/v5"
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/handoff"
"amadan.net/rastrillo/rastrillo/auth"
"amadan.net/rastrillo/rastrillo/csrf"
"amadan.net/rastrillo/rastrillo/db"
@@ -47,9 +49,12 @@ type app struct {
inst Installer
logger *slog.Logger
auth *auth.Auth
+ sess *sessions.Sessions
pk *passkey.Handlers
pages *look.Renderer
mailer mail.Sender
+ // oficina is sign-in with Oficina ID, nil when cfg.Home is.
+ oficina *oficina
}
// App builds Base's router. d is rastrillo's database handle (auth and
@@ -80,13 +85,20 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
if err != nil {
return nil, err
}
+ // With Oficina ID on, /signin leads with Oficina, so the email and
+ // passkey door moves to /signin/local, and a local sign-in lands on
+ // connect's LocalCompletePath, which picks up a link waiting for it.
+ localSignin, signedIn := "/signin", "/"
+ if cfg.Home != nil {
+ localSignin, signedIn = "/signin/local", connect.LocalCompletePath
+ }
a.auth, err = auth.New(auth.Config{
DB: d.Writer(), Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: mailer, Logger: logger,
Proof: guard, KeymailServers: []string{"keymail.dev"}, SigninScreen: true,
- BeginPath: "/auth/begin", ForgetPath: "/auth/forget", SignedInPath: "/",
+ SigninPath: localSignin, BeginPath: "/auth/begin", ForgetPath: "/auth/forget", SignedInPath: signedIn,
Authorize: a.authorize,
Refused: func(w http.ResponseWriter, r *http.Request, _ auth.Identity) {
- http.Redirect(w, r, "/signin?refused=1", http.StatusSeeOther)
+ http.Redirect(w, r, localSignin+"?refused=1", http.StatusSeeOther)
},
RenderConfirm: a.renderConfirm,
})
@@ -100,6 +112,7 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
if err != nil {
return nil, err
}
+ a.sess = sess
a.pk, err = passkey.New(passkey.Config{
Sessions: sess, DB: d.Writer(), Origin: cfg.Origin, Logger: logger,
Authorize: a.authorize, SignedInPath: "/", Remember: a.auth.RememberJar(),
@@ -118,17 +131,48 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
}
}
+ if cfg.Home != nil {
+ if a.oficina, err = a.newOficina(cfg.Home); err != nil {
+ return nil, err
+ }
+ }
+
r := chi.NewRouter()
- r.Use(csrf.Protect(cfg.Origin))
+ if o := a.oficina; o != nil {
+ // connect's middleware is csrf.Protect with one exception, POST
+ // /auth/assertion, whose signed assertion is its own proof.
+ r.Use(o.routes.Middleware)
+ } else {
+ r.Use(csrf.Protect(cfg.Origin))
+ }
r.Get("/static/fonts/*", look.FontHandler().ServeHTTP)
r.Get("/static/*", look.Assets.Handler().ServeHTTP)
- r.Get("/signin", a.signin)
- r.Post("/auth/begin", a.auth.Begin)
- r.Get("/auth/callback", a.auth.Callback)
- r.Get("/auth/verify", a.auth.Verify)
- r.Post("/auth/verify", a.auth.Verify)
+ if o := a.oficina; o != nil {
+ r.Get("/signin", a.oficinaSignin)
+ r.Get("/signin/local", a.signin)
+ r.Get("/signed-out", o.routes.SignedOut)
+ r.Get(connect.LocalCompletePath, o.routes.LocalComplete)
+ r.Get(handoff.StartPath, o.bridge.Start)
+ r.Post(handoff.CallbackPath, o.bridge.Callback)
+ r.Get(handoff.FinishPath, o.bridge.Finish)
+ r.With(sess.Require).Get("/account/home", o.routes.Account)
+ r.With(sess.Require).Post("/account/home", o.routes.LinkStart)
+ r.With(sess.Require).Get("/account/home/confirm", o.bridge.ConfirmPage)
+ r.With(sess.Require).Post("/account/home/confirm", o.routes.ConfirmPost)
+ r.Post("/auth/begin", o.routes.LocalGuard(a.auth.Begin))
+ r.Get("/auth/callback", o.routes.LocalGuard(a.auth.Callback))
+ r.Get("/auth/verify", o.routes.LocalGuard(a.auth.Verify))
+ r.Post("/auth/verify", o.routes.LocalGuard(a.auth.Verify))
+ r.Post("/auth/signout", o.routes.Signout)
+ } else {
+ r.Get("/signin", a.signin)
+ r.Post("/auth/begin", a.auth.Begin)
+ r.Get("/auth/callback", a.auth.Callback)
+ r.Get("/auth/verify", a.auth.Verify)
+ r.Post("/auth/verify", a.auth.Verify)
+ r.Post("/auth/signout", a.auth.Signout)
+ }
r.Post("/auth/forget", a.auth.Forget)
- r.Post("/auth/signout", a.auth.Signout)
r.Get(webauthnModulePath, serveScript(webauthn.JS()))
r.Get(passkeyDoorPath, serveScript(passkey.JS()))
r.Post(passkeyDoor.BeginPath, a.pk.DiscoverBegin)
@@ -143,8 +187,8 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.Get("/store/{app}/uninstall", a.uninstallPage)
r.Post("/store/{app}/uninstall", a.storeUninstall)
r.Get("/settings", a.settings)
- r.Post(registerBeginPath, a.pk.RegisterBegin)
- r.Post(registerFinishPath, a.pk.RegisterFinish)
+ r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin)
+ r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish)
r.Method(http.MethodGet, "/authorize", authorize)
})
return r, nil
@@ -179,17 +223,26 @@ func CurrentMember(r *http.Request) (store.Member, bool) {
return m, ok
}
-// requireMember lets through only a browser session whose address is still a
-// member, and puts that member on the request.
+// requireMember lets through only a browser session that belongs to a
+// current member, and puts that member on the request. A session from Base's
+// own sign-in names the member's address; one from Oficina ID names an
+// Oficina account, which counts only through a stored link to a member who
+// still exists. A signed-out page request goes to /signin.
func (a *app) requireMember(next http.Handler) http.Handler {
- return a.auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gate := a.auth.RequireSession
+ if a.oficina != nil {
+ // sessions' own gate, whose sign-in page is /signin, not auth's
+ // /signin/local: a signed-out visitor is offered Oficina first.
+ gate = a.sess.Require
+ }
+ return gate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
- id, ok := auth.From(r)
+ s, ok := sessions.Current(r)
if !ok {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
- m, found, err := store.MemberByEmail(r.Context(), a.db, id.Address)
+ m, found, err := a.memberFor(r, s)
switch {
case err != nil:
a.logger.Error("member gate", "err", err)
@@ -202,16 +255,46 @@ func (a *app) requireMember(next http.Handler) http.Handler {
}))
}
+// memberFor is the member behind session s. found is false for a session
+// that names nobody who is a member now.
+func (a *app) memberFor(r *http.Request, s sessions.Session) (m store.Member, found bool, err error) {
+ if s.Method == connect.HomeMethod {
+ if a.oficina == nil {
+ // Left over from when Oficina ID was on: it names an Oficina
+ // account, never an address.
+ return store.Member{}, false, nil
+ }
+ return a.oficina.member(r)
+ }
+ return store.MemberByEmail(r.Context(), a.db, s.Subject)
+}
+
+// ownSignInOnly refuses a request whose session came from Oficina ID. A
+// passkey is filed under the session's subject, which for an Oficina session
+// is the Oficina account, not the member's address: a passkey added there
+// could never sign the member in.
+func ownSignInOnly(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if s, ok := sessions.Current(r); !ok || s.Method == connect.HomeMethod {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
// signedInAt is when the request's session signed in: the credential's own
-// verification time when the sign-in method records one (Keymail), else when
-// the session was created, which is the moment a magic link was confirmed.
+// verification time when the sign-in method records one (Keymail, and
+// Oficina ID, which records when the person last proved who they are at
+// Oficina), else when the session was created, which is the moment a magic
+// link was confirmed.
func signedInAt(r *http.Request) (time.Time, bool) {
- id, ok := auth.From(r)
+ s, ok := sessions.Current(r)
if !ok {
return time.Time{}, false
}
- if !id.AuthTime.IsZero() {
- return id.AuthTime, true
+ if !s.AuthTime.IsZero() {
+ return s.AuthTime, true
}
- return id.At, !id.At.IsZero()
+ return s.At, !s.At.IsZero()
}
diff --git a/internal/web/oficina.go b/internal/web/oficina.go
new file mode 100644
index 0000000..efdee32
--- /dev/null
+++ b/internal/web/oficina.go
@@ -0,0 +1,187 @@
+package web
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "net/http"
+ "net/url"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/csrf"
+ "amadan.net/rastrillo/rastrillo/sessions"
+
+ "amadan.net/carlos/base/internal/store"
+)
+
+// Sign-in with Oficina ID, through Home's shared connect package, wired as
+// Oficina Calendar wires it. Base's roster stays the authority: an Oficina
+// account opens Base only through a link a member made by signing in the
+// local way once, and only while that member still exists. Nothing here
+// creates a member.
+
+// oficinaNamespace keeps Base's sealed hand-off state apart from every other
+// app's, as connect asks.
+const oficinaNamespace = "carlos/base"
+
+type oficina struct {
+ bridge *connect.Bridge
+ routes *connect.Routes
+ db *sql.DB
+}
+
+func (a *app) newOficina(home *connect.DecodedCredentials) (*oficina, error) {
+ sess := a.sess
+ read := func(r *http.Request) (*connect.Session, error) {
+ s, ok := sess.From(r)
+ if !ok {
+ return nil, nil
+ }
+ return &connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, nil
+ }
+ // A link names a member by number. The address it hands back is the
+ // member's current one, so a link outlives nothing: a removed member's
+ // number names nobody, and connect refuses it.
+ lookup := func(ctx context.Context, q linkstore.Queryer, n int64) (string, error) {
+ return store.MemberAddress(ctx, q, n)
+ }
+ // A local session names a member by the address it proved. Passkey
+ // sessions are local too, but connect counts only an emailed link or
+ // Keymail as proof for linking.
+ local := func(ctx context.Context, s connect.Session) (connect.Person, error) {
+ if s.Method != "magiclink" && s.Method != "keymail" {
+ return connect.Person{}, sql.ErrNoRows
+ }
+ m, found, err := store.MemberByEmail(ctx, a.db, s.Subject)
+ if err != nil {
+ return connect.Person{}, err
+ }
+ if !found {
+ return connect.Person{}, sql.ErrNoRows
+ }
+ n, err := store.MemberNumber(ctx, a.db, m.ID)
+ if err != nil {
+ return connect.Person{}, err
+ }
+ return connect.Person{ID: n, Label: m.Email}, nil
+ }
+ cfg := connect.Config{DB: a.db, Origin: a.cfg.Origin, Issuer: home.Issuer, ConsumerID: home.ConsumerID, Keys: home.Keys, DEK: home.DEK,
+ Namespace: oficinaNamespace, SessionCookie: sess.CookieName(), ReadSession: read, LookupLocalSession: local, LookupPerson: lookup,
+ Render: a.oficinaPage,
+ MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error {
+ return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime})
+ }}
+ b, err := connect.New(cfg)
+ if err != nil {
+ return nil, err
+ }
+ routes, err := connect.NewRoutes(b, connect.RoutesConfig{Namespace: oficinaNamespace, Origin: a.cfg.Origin, Issuer: home.Issuer,
+ SessionCookie: sess.CookieName(), DEK: home.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.signin,
+ Protect: csrf.Protect(a.cfg.Origin), Render: a.oficinaPage, FormPolicy: formPolicy(home.Issuer)})
+ if err != nil {
+ return nil, err
+ }
+ return &oficina{bridge: b, routes: routes, db: a.db}, nil
+}
+
+// formPolicy is the Content-Security-Policy rastrillo gives every Base
+// response (serve.go's defaultCSP) with Oficina's issuer added to
+// form-action, as connect requires: Sign out's 307 to {issuer}/signout is a
+// form submission, and form-action governs where it may go.
+// TestFormPolicyIsRastrillosWithTheIssuer keeps the two in step.
+func formPolicy(issuer string) string {
+ return "default-src 'self'; " +
+ "style-src 'self' 'unsafe-hashes' 'sha256-yJxAE4rjdcckohdlnvecSporPcqS9xOaA4hJxi87LMc='; " +
+ "img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self' " + issuer
+}
+
+// member is the member an Oficina session belongs to, through its link.
+func (o *oficina) member(r *http.Request) (store.Member, bool, error) {
+ p, err := o.bridge.ResolveSession(r)
+ if errors.Is(err, linkstore.ErrStorage) {
+ return store.Member{}, false, err
+ }
+ if err != nil {
+ return store.Member{}, false, nil
+ }
+ m, found, err := store.MemberByNumber(r.Context(), o.db, p.ID)
+ if err != nil || !found || m.Email != p.Label {
+ return store.Member{}, false, err
+ }
+ return m, true, nil
+}
+
+// linked reports whether member m has an Oficina account connected. An
+// error counts as linked, so Settings offers nothing it cannot be sure of.
+func (o *oficina) linked(ctx context.Context, m store.Member) bool {
+ n, err := store.MemberNumber(ctx, o.db, m.ID)
+ if err != nil {
+ return true
+ }
+ linked, err := o.bridge.Linked(ctx, n)
+ return err != nil || linked
+}
+
+// oficinaSignin is GET /signin with Oficina ID on. Someone signed in as a
+// current member goes where they were headed, as connect's Routes.Signin
+// sends them. A session that names nobody who is a member now ends here,
+// and the page is asked for again without it. Everyone else gets the sign-in
+// page, which leads with Oficina and keeps the email form and passkey below.
+func (a *app) oficinaSignin(w http.ResponseWriter, r *http.Request) {
+ back := r.URL.Query().Get("return_to")
+ if !handoff.SafePath(back) {
+ back = ""
+ }
+ if s, ok := a.sess.From(r); ok {
+ _, found, err := a.memberFor(r, s)
+ if err != nil {
+ a.logger.Error("sign-in: member lookup", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ if found {
+ to := back
+ if to == "" {
+ to = "/"
+ }
+ http.Redirect(w, r, to, http.StatusSeeOther)
+ return
+ }
+ a.sess.SignOut(w, r)
+ http.Redirect(w, r, r.URL.RequestURI(), http.StatusSeeOther)
+ return
+ }
+ start := handoff.StartPath
+ if back != "" {
+ start += "?" + url.Values{"return_to": {back}}.Encode()
+ }
+ a.signinWith(w, r, start)
+}
+
+// oficinaPage is connect's Render hook: the shared connect pages, and where
+// Oficina's sign-out lands, drawn in Base's look. The words are connect's
+// English, as Calendar shows them; the signed-out page is in the Oficina
+// door's words, as Calendar's is.
+func (a *app) oficinaPage(w http.ResponseWriter, r *http.Request, state, label string, status int) {
+ p := oficinaView{Name: a.cfg.Name, Back: "/settings"}
+ if state == "signedout" {
+ p.Tab = "Signed out"
+ p.Page = connect.PageData{Title: "You’re signed out", Body: "You’ve signed out of " + a.cfg.Name + " on this device.", Action: "/signin", ActionLabel: "Sign in"}
+ } else {
+ p.Page = connect.PageFor(r, state, label)
+ p.Tab = p.Page.Title
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ if err := a.pages.PageStatus(w, status, "oficina", p); err != nil {
+ a.logger.Error("render", "page", "oficina", "err", err)
+ http.Error(w, "something went wrong", http.StatusInternalServerError)
+ }
+}
+
+type oficinaView struct {
+ Name, Tab, Back string
+ Page connect.PageData
+}
diff --git a/internal/web/oficina_internal_test.go b/internal/web/oficina_internal_test.go
new file mode 100644
index 0000000..ad17446
--- /dev/null
+++ b/internal/web/oficina_internal_test.go
@@ -0,0 +1,33 @@
+package web
+
+import (
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo"
+ _ "amadan.net/rastrillo/rastrillo/locales/en"
+)
+
+// Base runs under rastrillo's default Content-Security-Policy. With Oficina ID
+// on, connect's middleware replaces it, so formPolicy must be that same policy
+// with only the issuer added to form-action.
+func TestFormPolicyIsRastrillosWithTheIssuer(t *testing.T) {
+ out, closeAll, err := rastrillo.Handler(rastrillo.Options{Mux: http.NewServeMux(), Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer closeAll()
+ w := httptest.NewRecorder()
+ out.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/nothing-here", nil))
+ def := w.Header().Get("Content-Security-Policy")
+ if !strings.HasSuffix(def, "form-action 'self'") {
+ t.Fatalf("rastrillo's default CSP changed shape: %q", def)
+ }
+ if got, want := formPolicy("https://id.oficina.works"), def+" https://id.oficina.works"; got != want {
+ t.Errorf("formPolicy:\n got %q\nwant %q", got, want)
+ }
+}
diff --git a/internal/web/settings.go b/internal/web/settings.go
index 406ba09..cef5774 100644
--- a/internal/web/settings.go
+++ b/internal/web/settings.go
@@ -4,37 +4,62 @@ import (
"encoding/base64"
"net/http"
- "amadan.net/rastrillo/rastrillo/auth"
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/sessions"
)
type settingsPage struct {
Name string
Address string
// Passkeys is how many passkeys sign this member in; PasskeyAdded says
- // the page follows adding one.
- Passkeys int
- PasskeyAdded bool
+ // the page follows adding one. CanAddPasskey is false for an Oficina
+ // session, which cannot file a passkey under the member's address.
+ Passkeys int
+ PasskeyAdded bool
+ CanAddPasskey bool
// UserID is the WebAuthn user handle a new passkey stores: the member's
// random id, never their address.
UserID string
ModuleURL, RegisterBegin, RegisterEnd string
+ // Oficina says Oficina ID is on, so signing out also signs out of the
+ // Oficina account. Connect offers to connect one: there is no link yet.
+ Oficina, Connect bool
+ ConnectLabel string
}
func (a *app) settings(w http.ResponseWriter, r *http.Request) {
me, _ := CurrentMember(r)
- id, _ := auth.From(r)
- keys, err := a.pk.List(id.Address)
+ s, _ := sessions.Current(r)
+ viaOficina := s.Method == connect.HomeMethod
+ // Passkeys are filed under the address a member signs in with, which an
+ // Oficina session's subject is not.
+ subject := s.Subject
+ if viaOficina {
+ subject = me.Email
+ }
+ keys, err := a.pk.List(subject)
if err != nil {
a.logger.Error("settings: passkeys", "err", err)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
- w.Header().Set("Cache-Control", "no-store")
- a.render(w, "settings", settingsPage{
+ page := settingsPage{
Name: a.cfg.Name, Address: me.Email,
- Passkeys: len(keys),
- PasskeyAdded: len(keys) > 0 && r.URL.Query().Get("passkey") == "added",
- UserID: base64.RawURLEncoding.EncodeToString([]byte(me.ID)),
- ModuleURL: webauthnModulePath, RegisterBegin: registerBeginPath, RegisterEnd: registerFinishPath,
- })
+ Passkeys: len(keys),
+ PasskeyAdded: len(keys) > 0 && r.URL.Query().Get("passkey") == "added",
+ CanAddPasskey: !viaOficina,
+ UserID: base64.RawURLEncoding.EncodeToString([]byte(me.ID)),
+ ModuleURL: webauthnModulePath, RegisterBegin: registerBeginPath, RegisterEnd: registerFinishPath,
+ }
+ if a.oficina != nil {
+ page.Oficina = true
+ page.Connect = !a.oficina.linked(r.Context(), me)
+ page.ConnectLabel = connect.English["menu_action"]
+ // Sign out hops on to Oficina's /signout, which admits the hop by
+ // its Referer when the browser sends Origin: null. strict-origin
+ // sends this origin and nothing more.
+ w.Header().Set("Referrer-Policy", "strict-origin")
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ a.render(w, "settings", page)
}
diff --git a/internal/web/signin.go b/internal/web/signin.go
index 704b378..8a5f4df 100644
--- a/internal/web/signin.go
+++ b/internal/web/signin.go
@@ -12,6 +12,9 @@ type signinPage struct {
Refused bool
ProblemText string
Confirm *auth.ConfirmPageData
+ // Oficina is where "Sign in with Oficina" goes (/auth/start), set only
+ // on /signin with Oficina ID on.
+ Oficina string
}
var problemText = map[auth.SigninProblem]string{
@@ -24,7 +27,13 @@ var problemText = map[auth.SigninProblem]string{
auth.ProblemCheck: "Your browser couldn't finish a security check. Try again.",
}
-func (a *app) signin(w http.ResponseWriter, r *http.Request) {
+// signin is the email and passkey sign-in page: /signin, or /signin/local
+// with Oficina ID on.
+func (a *app) signin(w http.ResponseWriter, r *http.Request) { a.signinWith(w, r, "") }
+
+// signinWith is the sign-in page, led by "Sign in with Oficina" to oficina
+// when that is set.
+func (a *app) signinWith(w http.ResponseWriter, r *http.Request, oficina string) {
state := a.auth.SigninState(r)
door := passkeyDoor
state.Passkey = &door
@@ -34,6 +43,7 @@ func (a *app) signin(w http.ResponseWriter, r *http.Request) {
Name: a.cfg.Name, State: state,
Refused: r.URL.Query().Get("refused") == "1",
ProblemText: problemText[state.Problem],
+ Oficina: oficina,
})
}
diff --git a/internal/web/templates/oficina.html b/internal/web/templates/oficina.html
new file mode 100644
index 0000000..3397669
--- /dev/null
+++ b/internal/web/templates/oficina.html
@@ -0,0 +1,12 @@
+{{define "title"}}{{.Tab}} · {{.Name}}{{end}}
+{{define "main"}}{{$p := .Page}}<main class="signin">
+<div class="card glass">
+<div class="wordmark">base</div>
+<h2>{{$p.Title}}</h2>
+<p>{{$p.Body}}</p>
+{{with $p.Address}}<p class="addr"><bdi>{{.}}</bdi></p>
+{{end}}{{if $p.PostAction}}<form method="post" action="{{$p.Action}}"><button class="btn" type="submit">{{$p.ActionLabel}}</button></form>
+{{else}}<a class="btn full" href="{{$p.Action}}">{{$p.ActionLabel}}</a>
+{{end}}{{with $p.CancelLabel}}<a class="btn ghost full" href="{{$.Back}}">{{.}}</a>
+{{end}}</div>
+</main>{{end}}
diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html
index d240047..140c1fb 100644
--- a/internal/web/templates/settings.html
+++ b/internal/web/templates/settings.html
@@ -6,12 +6,13 @@
<ul class="people">
<li><div class="who">Base name<small>{{.Name}}</small></div></li>
<li><div class="who">Signed in as<small>{{.Address}}</small></div></li>
-<li><div class="who">Passkeys<small id="passkeys">{{if .Passkeys}}{{.Passkeys}} added{{else}}None yet{{end}}</small></div>{{/* Hidden until the script finds the browser can make a passkey, so with scripts off there is no dead button. */}}<button class="btn ghost" type="button" hidden data-passkey-add data-module="{{.ModuleURL}}" data-begin="{{.RegisterBegin}}" data-finish="{{.RegisterEnd}}" data-rp-name="{{.Name}}" data-user-id="{{.UserID}}" data-user-name="{{.Address}}" data-done="/settings?passkey=added" data-cancelled="No passkey was added." data-failed="That didn't work. Try again." aria-describedby="passkey-msg">Add a passkey</button></li>
-</ul>
+<li><div class="who">Passkeys<small id="passkeys">{{if .Passkeys}}{{.Passkeys}} added{{else}}None yet{{end}}</small></div>{{if .CanAddPasskey}}{{/* Hidden until the script finds the browser can make a passkey, so with scripts off there is no dead button. */}}<button class="btn ghost" type="button" hidden data-passkey-add data-module="{{.ModuleURL}}" data-begin="{{.RegisterBegin}}" data-finish="{{.RegisterEnd}}" data-rp-name="{{.Name}}" data-user-id="{{.UserID}}" data-user-name="{{.Address}}" data-done="/settings?passkey=added" data-cancelled="No passkey was added." data-failed="That didn't work. Try again." aria-describedby="passkey-msg">Add a passkey</button>{{end}}</li>
+{{if .Connect}}<li><div class="who">Oficina account<small>Not connected</small></div><a class="btn ghost" href="/account/home">{{.ConnectLabel}}</a></li>
+{{end}}</ul>
{{if .PasskeyAdded}}<p class="status" role="status" id="passkey-added">Passkey added. Next time, sign in with it.</p>
{{end}}<p class="status" id="passkey-msg" aria-live="polite"></p>
<form method="post" action="/auth/signout"><button class="btn ghost" type="submit">Sign out of Base</button></form>
-<p class="soon">This signs you out of Base only. Apps you've opened stay signed in until you sign out of each one.</p>
+<p class="soon">{{if .Oficina}}This signs you out of Base and your Oficina account. Apps you've opened stay signed in until you sign out of each one.{{else}}This signs you out of Base only. Apps you've opened stay signed in until you sign out of each one.{{end}}</p>
</div>
<script type="module" src="{{asset "static/passkey-add.js"}}"></script>
</main>{{end}}
diff --git a/internal/web/templates/signin.html b/internal/web/templates/signin.html
index 54571e0..b8b4d19 100644
--- a/internal/web/templates/signin.html
+++ b/internal/web/templates/signin.html
@@ -12,12 +12,14 @@
{{else}}<h2>Sign in to {{.Name}}</h2>
{{if .Refused}}<p role="status">Sign-in isn't available for that address. Ask whoever runs {{.Name}} to invite you, or try another address.</p>
{{else if $s.Problem}}<p role="status">{{.ProblemText}}</p>
-{{else}}<p>Use your work email.</p>
+{{else if not .Oficina}}<p>Use your work email.</p>
+{{end}}{{with .Oficina}}<a class="btn full" href="{{.}}">Sign in with Oficina</a>
+<p class="or">Or use your work email.</p>
{{end}}<form method="post" action="{{$s.BeginPath}}"{{with $s.Proof}} {{.Attrs}}{{end}}>{{with $s.Proof}}{{.Fields}}{{end}}
{{with $s.ReturnTo}}<input type="hidden" name="return_to" value="{{.}}">
{{end}}{{if or $s.Force (eq $s.Problem "keymail")}}<input type="hidden" name="force" value="1">
{{end}}<input class="input" type="email" name="address" value="{{$s.Address}}" autocomplete="email" required aria-label="Email address">
-<button class="btn" type="submit">{{if eq $s.Problem "keymail"}}Send me a link instead{{else}}Continue{{end}}</button>
+<button class="btn{{if .Oficina}} ghost{{end}}" type="submit">{{if eq $s.Problem "keymail"}}Send me a link instead{{else}}Continue{{end}}</button>
</form>
{{with $s.Passkey}}{{/* Hidden until rastrillo's door script finds the browser can run a passkey ceremony, so with scripts off there is no dead button. */}}<button class="alt" type="button" hidden data-rst-passkey data-rst-passkey-begin="{{.BeginPath}}" data-rst-passkey-finish="{{$s.PasskeyFinish}}" data-rst-passkey-module="{{.ModuleURL}}" data-rst-passkey-cancelled="No passkey was used. Try again, or use your email." data-rst-passkey-failed="That didn't work. Try again, or use your email." aria-describedby="passkey-msg">Or use a passkey</button>
<p class="passkey-msg" id="passkey-msg" aria-live="polite"></p>
diff --git a/internal/webtest/harness_test.go b/internal/webtest/harness_test.go
index 39bac7a..9a6903e 100644
--- a/internal/webtest/harness_test.go
+++ b/internal/webtest/harness_test.go
@@ -42,6 +42,7 @@ var schema = dbtest.FromSet(store.BootSchema)
func TestMain(m *testing.M) {
code := budget.Main(m)
schema.Remove()
+ homeSchema.Remove()
os.Exit(code)
}
@@ -80,10 +81,14 @@ func (r Resp) Location() string { return r.Header.Get("Location") }
type testApp struct {
t *testing.T
- srv *httptest.Server
+ srv *httptest.Server // nil for an app served in-process (newHomeApp)
client *http.Client
mail *capturingMailer
DB *sql.DB
+ // base prefixes every request path; origin is the same-origin evidence
+ // post presents; localSignin is the page with the email form.
+ base, origin, localSignin string
+ home *oficina // set by newHomeApp
}
// newApp builds the whole app per test over its own copy of the migrated
@@ -120,7 +125,7 @@ func newAppBuilt(t *testing.T, build func(*sql.DB, config.Config) web.Installer,
t.Cleanup(srv.Close)
jar, _ := cookiejar.New(nil)
client := &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
- return &testApp{t: t, srv: srv, client: client, mail: mailer, DB: d.Writer()}
+ return &testApp{t: t, srv: srv, client: client, mail: mailer, DB: d.Writer(), base: srv.URL, origin: testOrigin, localSignin: "/signin"}
}
func (a *testApp) do(req *http.Request) Resp {
@@ -136,7 +141,7 @@ func (a *testApp) do(req *http.Request) Resp {
func (a *testApp) get(target string) Resp {
a.t.Helper()
- req, _ := http.NewRequest(http.MethodGet, a.srv.URL+target, nil)
+ req, _ := http.NewRequest(http.MethodGet, a.base+target, nil)
return a.do(req)
}
@@ -144,9 +149,9 @@ func (a *testApp) get(target string) Resp {
// browser sends Origin on a form POST; a test client must too.
func (a *testApp) post(target string, form url.Values) Resp {
a.t.Helper()
- req, _ := http.NewRequest(http.MethodPost, a.srv.URL+target, strings.NewReader(form.Encode()))
+ req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Set("Origin", testOrigin)
+ req.Header.Set("Origin", a.origin)
return a.do(req)
}
@@ -191,7 +196,7 @@ func formFields(t *testing.T, body, action string) url.Values {
// three seconds before it will be accepted.
func (a *testApp) requestLink(email string) Resp {
a.t.Helper()
- page := a.get("/signin?rec=1&force=1")
+ page := a.get(a.localSignin + "?rec=1&force=1")
if page.Code != 200 {
a.t.Fatalf("signin page: %d", page.Code)
}
diff --git a/internal/webtest/oficina_harness_test.go b/internal/webtest/oficina_harness_test.go
new file mode 100644
index 0000000..de8cb7e
--- /dev/null
+++ b/internal/webtest/oficina_harness_test.go
@@ -0,0 +1,240 @@
+package webtest
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "html"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/cookiejar"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "time"
+
+ "testing"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/crypto"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/dbtest"
+
+ "amadan.net/carlos/base/internal/config"
+ "amadan.net/carlos/base/internal/store"
+ "amadan.net/carlos/base/internal/web"
+)
+
+// Base with Oficina ID on. It is served in-process at an https origin,
+// because connect's cookies are __Host- cookies, which a cookie jar only
+// sends over https, and its assertions name an https audience.
+const (
+ homeOrigin = "https://base.acme.test"
+ homeIssuer = "https://id.oficina.test"
+ homeConsumer = "base"
+ homeKeyID = "k1"
+)
+
+var homeSchema = dbtest.FromSet(store.Boot(true))
+
+// oficina plays id.oficina.test: it holds the key Base trusts for Oficina
+// assertions.
+type oficina struct {
+ key *crypto.Keypair
+ cfg config.Config
+}
+
+// newHomeApp builds Base exactly as main.go does with every BASE_HOME_*
+// setting present, with an assertion key so it can hand off to apps too.
+func newHomeApp(t *testing.T) *testApp {
+ t.Helper()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(homeSchema.Path(t), logger)
+ if err != nil {
+ t.Fatalf("db.Open: %v", err)
+ }
+ t.Cleanup(func() { d.Close() })
+ if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil {
+ t.Fatal(err)
+ }
+ key, err := crypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ keys, _ := json.Marshal(map[string]string{homeKeyID: base64.StdEncoding.EncodeToString(key.SignPub())})
+ home, err := config.LoadHome(&connect.Credentials{
+ Issuer: homeIssuer, ConsumerID: homeConsumer,
+ KeysBase64: base64.StdEncoding.EncodeToString(keys),
+ DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{9}, 32)),
+ }, homeOrigin)
+ if err != nil || home == nil {
+ t.Fatalf("LoadHome: %+v %v", home, err)
+ }
+ signing, err := crypto.Generate()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfg := config.Config{Origin: homeOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true,
+ Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC, AssertionKey: signing, Home: home}
+ mailer := &capturingMailer{}
+ h, err := web.App(d, cfg, mailer, noInstaller{}, logger)
+ if err != nil {
+ t.Fatalf("web.App: %v", err)
+ }
+ return &testApp{t: t, client: inProcessClient(h), mail: mailer, DB: d.Writer(),
+ base: homeOrigin, origin: homeOrigin, localSignin: "/signin/local", home: &oficina{key: key, cfg: cfg}}
+}
+
+// inProcessClient is a browser for h alone: a cookie jar, no redirects
+// followed, and every request to homeOrigin served by h without a socket.
+func inProcessClient(h http.Handler) *http.Client {
+ jar, _ := cookiejar.New(nil)
+ return &http.Client{Jar: jar, Transport: handlerTransport{h},
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+}
+
+type handlerTransport struct{ h http.Handler }
+
+func (t handlerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ if r.URL.Scheme+"://"+r.URL.Host != homeOrigin {
+ return nil, fmt.Errorf("test browser: no route to %s", r.URL.Redacted())
+ }
+ in := r.Clone(r.Context())
+ in.RequestURI, in.Host, in.RemoteAddr, in.TLS = r.URL.RequestURI(), r.URL.Host, "192.0.2.10:4321", &tls.ConnectionState{}
+ if in.Body == nil {
+ in.Body = http.NoBody
+ }
+ w := httptest.NewRecorder()
+ t.h.ServeHTTP(w, in)
+ res := w.Result()
+ res.Request = r
+ return res, nil
+}
+
+// newBrowser is another browser on the same Base: an empty cookie jar.
+func (a *testApp) newBrowser() *testApp {
+ b := *a
+ jar, _ := cookiejar.New(nil)
+ c := *a.client
+ c.Jar = jar
+ b.client = &c
+ return &b
+}
+
+var startLinkRE = regexp.MustCompile(`href="(/auth/start[^"]*)"`)
+
+// oficinaButton is the href of the sign-in page's "Sign in with Oficina".
+func (a *testApp) oficinaButton(page Resp) string {
+ a.t.Helper()
+ m := startLinkRE.FindStringSubmatch(page.Body)
+ if m == nil {
+ a.t.Fatalf("no Sign in with Oficina link in:\n%s", page.Body)
+ }
+ return html.UnescapeString(m[1])
+}
+
+// atOficina follows a 303 to the issuer's /authorize as id.oficina would:
+// it signs an assertion for subject with the request's nonce, has the
+// browser post it back to /auth/assertion, and returns what /auth/finish
+// answers. authAge is how long ago the person last proved who they are.
+func (a *testApp) atOficina(toIssuer Resp, subject string, authAge time.Duration) Resp {
+ a.t.Helper()
+ if toIssuer.Code != http.StatusSeeOther {
+ a.t.Fatalf("want a 303 to Oficina, got %d %q\n%s", toIssuer.Code, toIssuer.Location(), toIssuer.Body)
+ }
+ u, err := url.Parse(toIssuer.Location())
+ if err != nil || u.Scheme+"://"+u.Host != homeIssuer || u.Path != "/authorize" {
+ a.t.Fatalf("not sent to Oficina: %q", toIssuer.Location())
+ }
+ q := u.Query()
+ if q.Get("consumer") != homeConsumer || q.Get("nonce") == "" {
+ a.t.Fatalf("authorize query: %v", q)
+ }
+ now := time.Now().Unix()
+ jti, err := assertion.RandomID()
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ token, err := assertion.Sign(a.home.key, assertion.Claims{Version: 1, Issuer: homeIssuer, Audience: homeOrigin, Subject: subject,
+ KeyID: homeKeyID, ID: jti, Nonce: q.Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now - int64(authAge/time.Second)})
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ cb := a.postFrom(homeIssuer, "/auth/assertion", url.Values{"assertion": {token}})
+ if cb.Code != http.StatusSeeOther || cb.Location() != "/auth/finish" {
+ a.t.Fatalf("assertion callback: %d %q\n%s", cb.Code, cb.Location(), cb.Body)
+ }
+ return a.get("/auth/finish")
+}
+
+// postFrom posts a form as a page on origin would.
+func (a *testApp) postFrom(origin, target string, form url.Values) Resp {
+ a.t.Helper()
+ req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", origin)
+ return a.do(req)
+}
+
+// signInWithOficina presses "Sign in with Oficina" on /signin and comes back
+// from Oficina as subject. It returns /auth/finish's answer.
+func (a *testApp) signInWithOficina(subject string) Resp {
+ a.t.Helper()
+ page := a.get("/signin")
+ if page.Code != 200 {
+ a.t.Fatalf("signin page: %d %q", page.Code, page.Location())
+ }
+ return a.atOficina(a.get(a.oficinaButton(page)), subject, time.Hour)
+}
+
+// link connects email's member to the Oficina subject from scratch, the way
+// a person does it from Settings: sign in with email, Connect your Oficina
+// account, prove it at Oficina, confirm. It leaves this browser signed in
+// locally.
+func (a *testApp) link(email, subject string) {
+ a.t.Helper()
+ r := a.signIn(email)
+ if r.Code != 303 || r.Location() != connect.LocalCompletePath {
+ a.t.Fatalf("local sign-in: %d %q", r.Code, r.Location())
+ }
+ if land := a.get(r.Location()); land.Code != 303 || land.Location() != "/" {
+ a.t.Fatalf("local landing: %d %q", land.Code, land.Location())
+ }
+ settings := a.get("/settings")
+ if !strings.Contains(settings.Body, `href="/account/home"`) {
+ a.t.Fatalf("settings offers no Connect:\n%s", settings.Body)
+ }
+ start := a.get("/account/home")
+ if start.Code != 200 || !strings.Contains(start.Body, "Connect your Oficina account") {
+ a.t.Fatalf("connect page: %d\n%s", start.Code, start.Body)
+ }
+ toIssuer := a.get(a.post("/account/home", nil).Location())
+ finish := a.atOficina(toIssuer, subject, 30*time.Second)
+ a.confirmLink(finish, email)
+}
+
+// confirmLink takes /auth/finish's 303 to the confirm step through to
+// "Accounts connected".
+func (a *testApp) confirmLink(finish Resp, email string) {
+ a.t.Helper()
+ if finish.Code != 303 || finish.Location() != "/account/home/confirm" {
+ a.t.Fatalf("link finish: %d %q\n%s", finish.Code, finish.Location(), finish.Body)
+ }
+ confirm := a.get("/account/home/confirm")
+ if confirm.Code != 200 || !strings.Contains(confirm.Body, "Connect these two accounts?") || !strings.Contains(confirm.Body, email) {
+ a.t.Fatalf("confirm page: %d\n%s", confirm.Code, confirm.Body)
+ }
+ done := a.post("/account/home/confirm", nil)
+ if done.Code != 303 || !strings.HasPrefix(done.Location(), "/account/home/confirm?connected=1") {
+ a.t.Fatalf("confirm: %d %q", done.Code, done.Location())
+ }
+ if page := a.get(done.Location()); page.Code != 200 || !strings.Contains(page.Body, "Accounts connected") {
+ a.t.Fatalf("connected page: %d\n%s", page.Code, page.Body)
+ }
+}
diff --git a/internal/webtest/oficina_test.go b/internal/webtest/oficina_test.go
new file mode 100644
index 0000000..a0c804b
--- /dev/null
+++ b/internal/webtest/oficina_test.go
@@ -0,0 +1,293 @@
+package webtest
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/assertion"
+
+ "amadan.net/carlos/base/internal/install"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// With no BASE_HOME_* settings Base is exactly what it was: its own sign-in,
+// no Oficina routes, sign-out back to /signin.
+func TestOficinaOffKeepsBaseAsItWas(t *testing.T) {
+ a := newApp(t)
+ page := a.get("/signin")
+ if page.Code != 200 || strings.Contains(page.Body, "Oficina") || strings.Contains(page.Body, "/auth/start") {
+ t.Fatalf("signin page mentions Oficina: %d\n%s", page.Code, page.Body)
+ }
+ for _, p := range []string{"/auth/start", "/auth/finish", "/signin/local", "/signed-out", "/account/home"} {
+ if r := a.get(p); r.Code != http.StatusNotFound {
+ t.Errorf("GET %s: %d, want 404", p, r.Code)
+ }
+ }
+ a.signedInOwner()
+ if body := a.get("/settings").Body; strings.Contains(body, "/account/home") || strings.Contains(body, "Oficina") {
+ t.Errorf("settings offers Oficina:\n%s", body)
+ }
+ if r := a.post("/auth/signout", nil); r.Code != 303 || r.Location() != "/signin" {
+ t.Errorf("signout: %d %q", r.Code, r.Location())
+ }
+}
+
+func TestOficinaSigninPageLeadsWithOficina(t *testing.T) {
+ a := newHomeApp(t)
+ page := a.get("/signin")
+ if page.Code != 200 {
+ t.Fatalf("signin: %d %q", page.Code, page.Location())
+ }
+ if got := a.oficinaButton(page); got != "/auth/start" {
+ t.Errorf("Sign in with Oficina goes to %q", got)
+ }
+ oficina := strings.Index(page.Body, "Sign in with Oficina")
+ email := strings.Index(page.Body, `action="/auth/begin"`)
+ if oficina < 0 || email < 0 || oficina > email {
+ t.Errorf("Oficina (%d) does not lead the email form (%d):\n%s", oficina, email, page.Body)
+ }
+ // The way back after signing in rides along to Oficina.
+ if got := a.oficinaButton(a.get("/signin?return_to=%2Fpeople")); got != "/auth/start?return_to=%2Fpeople" {
+ t.Errorf("with return_to: %q", got)
+ }
+ csp := page.Header.Get("Content-Security-Policy")
+ if !strings.Contains(csp, "form-action 'self' "+homeIssuer) || strings.Contains(csp, "unsafe-inline") {
+ t.Errorf("CSP: %q", csp)
+ }
+ // The local door is still there, with email and passkey, and no Oficina
+ // button: it is where linking sends people to prove the local account.
+ local := a.get("/signin/local")
+ if local.Code != 200 || !strings.Contains(local.Body, `action="/auth/begin"`) || !strings.Contains(local.Body, "data-rst-passkey") || strings.Contains(local.Body, "/auth/start") {
+ t.Errorf("local sign-in page: %d\n%s", local.Code, local.Body)
+ }
+ // Someone already signed in is sent on, not shown the door again.
+ a.signedInOwner()
+ if r := a.get("/signin?return_to=%2Fpeople"); r.Code != 303 || r.Location() != "/people" {
+ t.Errorf("signed-in /signin: %d %q", r.Code, r.Location())
+ }
+}
+
+// An Oficina sign-in that Base has no link for creates nobody. It asks the
+// person to sign in the local way once, and that sign-in goes straight on to
+// connecting the two accounts. After that, Oficina alone signs them in.
+func TestOficinaUnlinkedPersonLinksAfterOneLocalSignIn(t *testing.T) {
+ a := newHomeApp(t)
+ members := func() int {
+ var n int
+ if err := a.DB.QueryRow(`SELECT count(*) FROM members`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+ }
+ before := members()
+
+ unknown := a.signInWithOficina("subject-owner")
+ if unknown.Code != http.StatusForbidden || !strings.Contains(unknown.Body, "Oficina account not connected") || !strings.Contains(unknown.Body, `href="/signin/local"`) {
+ t.Fatalf("unlinked arrival: %d\n%s", unknown.Code, unknown.Body)
+ }
+ if !strings.Contains(unknown.Body, `class="card glass"`) {
+ t.Errorf("not in Base's look:\n%s", unknown.Body)
+ }
+ if r := a.get("/"); r.Code != 303 || !strings.HasPrefix(r.Location(), "/signin") {
+ t.Fatalf("signed in without a link: %d %q", r.Code, r.Location())
+ }
+
+ r := a.signIn(ownerAddress)
+ if r.Code != 303 || r.Location() != connect.LocalCompletePath {
+ t.Fatalf("local sign-in: %d %q", r.Code, r.Location())
+ }
+ resume := a.get(r.Location())
+ if resume.Code != 303 || !strings.HasPrefix(resume.Location(), "/auth/start") {
+ t.Fatalf("local sign-in did not resume the link: %d %q", resume.Code, resume.Location())
+ }
+ toIssuer := a.get(resume.Location())
+ if u, _ := url.Parse(toIssuer.Location()); u == nil || u.Query().Get("max_age") != "300" {
+ t.Fatalf("link did not ask Oficina for a fresh sign-in: %q", toIssuer.Location())
+ }
+ a.confirmLink(a.atOficina(toIssuer, "subject-owner", 30*time.Second), ownerAddress)
+
+ if body := a.get("/settings").Body; strings.Contains(body, `href="/account/home"`) {
+ t.Errorf("settings still offers Connect after linking:\n%s", body)
+ }
+ b := a.newBrowser()
+ if fin := b.signInWithOficina("subject-owner"); fin.Code != 303 || fin.Location() != "/" {
+ t.Fatalf("linked Oficina sign-in: %d %q\n%s", fin.Code, fin.Location(), fin.Body)
+ }
+ if home := b.get("/"); home.Code != 200 {
+ t.Fatalf("GET / after Oficina sign-in: %d", home.Code)
+ }
+ if n := members(); n != before {
+ t.Errorf("members: %d, was %d", n, before)
+ }
+}
+
+func TestOficinaLinkedPersonReachesHome(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ a.setInstall("scratchpad", "installed", "")
+
+ b := a.newBrowser()
+ fin := b.signInWithOficina("subject-owner")
+ if fin.Code != 303 || fin.Location() != "/" {
+ t.Fatalf("finish: %d %q\n%s", fin.Code, fin.Location(), fin.Body)
+ }
+ if home := b.get("/"); home.Code != 200 || !strings.Contains(home.Body, "Scratchpad") {
+ t.Fatalf("Home: %d\n%s", home.Code, home.Body)
+ }
+ settings := b.get("/settings")
+ if settings.Code != 200 || !strings.Contains(settings.Body, ownerAddress) {
+ t.Fatalf("settings: %d\n%s", settings.Code, settings.Body)
+ }
+ if strings.Contains(settings.Body, `href="/account/home"`) || strings.Contains(settings.Body, "data-passkey-add") {
+ t.Errorf("settings for an Oficina session offers Connect or a new passkey:\n%s", settings.Body)
+ }
+
+ // Base still vouches for its own members to installed apps, as the same
+ // member whichever way they signed in.
+ n, _ := assertion.RandomID()
+ page := b.get("/authorize?" + url.Values{"consumer": {"scratchpad"}, "nonce": {n}}.Encode())
+ appOrigin := "https://acme-scratchpad.bab.oncarlos.com"
+ v := formFields(t, page.Body, appOrigin+"/auth/assertion")
+ kid, pub := install.KeySet(a.home.cfg.AssertionKey)
+ verifier, err := assertion.NewVerifier(homeOrigin, appOrigin, map[string][]byte{kid: pub})
+ if err != nil {
+ t.Fatal(err)
+ }
+ claims, err := verifier.Verify(v.Get("assertion"), time.Now())
+ if err != nil {
+ t.Fatalf("verify: %v", err)
+ }
+ owner, _, _ := store.MemberByEmail(context.Background(), a.DB, ownerAddress)
+ if claims.Subject != owner.ID || claims.Nonce != n {
+ t.Errorf("claims: %+v, want subject %s", claims, owner.ID)
+ }
+
+ // The way back survives the trip to Oficina.
+ c := a.newBrowser()
+ toIssuer := c.get(c.oficinaButton(c.get("/signin?return_to=%2Fpeople")))
+ if fin := c.atOficina(toIssuer, "subject-owner", time.Hour); fin.Code != 303 || fin.Location() != "/people" {
+ t.Errorf("finish with return_to: %d %q", fin.Code, fin.Location())
+ }
+}
+
+// The roster decides, on every request: an Oficina link to someone who is no
+// longer a member opens nothing.
+func TestOficinaRemovedMemberIsRefused(t *testing.T) {
+ a := newHomeApp(t)
+ ctx := context.Background()
+ if _, _, err := store.Invite(ctx, a.DB, "ana@acme.test"); err != nil {
+ t.Fatal(err)
+ }
+ a.link("ana@acme.test", "subject-ana")
+ b := a.newBrowser()
+ if fin := b.signInWithOficina("subject-ana"); fin.Code != 303 {
+ t.Fatalf("ana's Oficina sign-in: %d", fin.Code)
+ }
+ if r := b.get("/"); r.Code != 200 {
+ t.Fatalf("ana's Home: %d", r.Code)
+ }
+ if _, err := a.DB.Exec(`DELETE FROM members WHERE email = 'ana@acme.test'`); err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range []string{"/", "/settings", "/people"} {
+ if r := b.get(p); r.Code != http.StatusForbidden {
+ t.Errorf("removed member's Oficina session, GET %s: %d", p, r.Code)
+ }
+ }
+ c := a.newBrowser()
+ if fin := c.signInWithOficina("subject-ana"); fin.Code != http.StatusForbidden {
+ t.Errorf("removed member signed in again: %d %q", fin.Code, fin.Location())
+ }
+ if r := c.get("/"); r.Code != 303 || !strings.HasPrefix(r.Location(), "/signin") {
+ t.Errorf("removed member reached Home: %d %q", r.Code, r.Location())
+ }
+}
+
+// Sign out ends Base's session, then hands the same POST to Oficina's
+// /signout so the Oficina session ends too.
+func TestOficinaSignOutGoesThroughOficina(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ b := a.newBrowser()
+ b.signInWithOficina("subject-owner")
+ settings := b.get("/settings")
+ if got := settings.Header.Get("Referrer-Policy"); got != "strict-origin" {
+ t.Errorf("settings Referrer-Policy %q, want strict-origin", got)
+ }
+ if !strings.Contains(settings.Body, `action="/auth/signout"`) {
+ t.Fatalf("no sign-out form:\n%s", settings.Body)
+ }
+ out := b.post("/auth/signout", nil)
+ if out.Code != http.StatusTemporaryRedirect || out.Location() != homeIssuer+"/signout" {
+ t.Fatalf("signout: %d %q", out.Code, out.Location())
+ }
+ if r := b.get("/"); r.Code != 303 || !strings.HasPrefix(r.Location(), "/signin") {
+ t.Errorf("still signed in: %d %q", r.Code, r.Location())
+ }
+ // Oficina sends the browser back here.
+ page := b.get("/signed-out")
+ if page.Code != 200 || !strings.Contains(page.Body, "You’re signed out") || !strings.Contains(page.Body, `href="/signin"`) {
+ t.Errorf("signed-out page: %d\n%s", page.Code, page.Body)
+ }
+ // A local session signs out the same way.
+ if r := a.post("/auth/signout", nil); r.Code != http.StatusTemporaryRedirect || r.Location() != homeIssuer+"/signout" {
+ t.Errorf("local signout: %d %q", r.Code, r.Location())
+ }
+}
+
+// POST /auth/assertion is the one route another site may post to; the
+// bridge checks the signed assertion itself. Every other POST still needs
+// Base's own origin.
+func TestOficinaOnlyTheAssertionCallbackSkipsCSRF(t *testing.T) {
+ a := newHomeApp(t)
+ a.signedInOwner()
+ for _, p := range []string{"/auth/begin", "/auth/verify", "/auth/forget", "/auth/signout", "/people", "/account/home",
+ "/account/home/confirm", "/store/scratchpad/install", "/store/scratchpad/uninstall", "/passkey/discover/begin", "/passkey/register/begin"} {
+ if r := a.postFrom(homeIssuer, p, url.Values{"x": {"1"}}); r.Code != http.StatusForbidden {
+ t.Errorf("POST %s from Oficina's origin: %d, want 403", p, r.Code)
+ }
+ }
+ if r := a.get("/"); r.Code != 200 {
+ t.Fatalf("the refused POSTs changed the session: %d", r.Code)
+ }
+ // The callback itself takes Oficina's post (atOficina checks the 303).
+ b := a.newBrowser()
+ b.signInWithOficina("anyone")
+}
+
+// An Oficina session signs a member in, but a passkey belongs to the
+// member's own sign-in: one added from an Oficina session would be filed
+// under the Oficina subject and could never sign anyone in.
+func TestOficinaSessionCannotAddPasskey(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ b := a.newBrowser()
+ b.signInWithOficina("subject-owner")
+ req, _ := http.NewRequest(http.MethodPost, homeOrigin+"/passkey/register/begin", strings.NewReader("{}"))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Origin", homeOrigin)
+ if r := b.do(req); r.Code != http.StatusForbidden {
+ t.Errorf("register from an Oficina session: %d", r.Code)
+ }
+}
+
+// Settings offers "Connect your Oficina account" only while there is no link.
+func TestOficinaConnectOfferedOnlyUntilLinked(t *testing.T) {
+ a := newHomeApp(t)
+ a.signedInOwner()
+ body := a.get("/settings").Body
+ if !regexp.MustCompile(`<a[^>]*href="/account/home"[^>]*>Connect your Oficina account</a>`).MatchString(body) {
+ t.Fatalf("settings lacks the Connect link:\n%s", body)
+ }
+ b := a.newBrowser()
+ b.link(ownerAddress, "subject-owner")
+ if body := a.get("/settings").Body; strings.Contains(body, "Connect your Oficina account") {
+ t.Errorf("still offered after linking from another browser:\n%s", body)
+ }
+}