package connect
import (
"bytes"
"html/template"
"net/http"
"net/http/httptest"
"net/url"
"os/exec"
"strings"
"testing"
"time"
"amadan.net/oficina/home/handoff"
"amadan.net/rastrillo/rastrillo/csrf"
)
// doorFixture is Routes over navigationFixture's sealer, with a session
// reader that knows "verified" (a live Home sign-in), "guest" (a Calls
// guest, a session but not a sign-in) and "revoked" (no session). The
// app's door (LocalSignin) answers 299 and records what connect told it.
type doorFixture struct {
h *Routes
calls int
href string
path string
}
func newDoorFixture(t *testing.T) *doorFixture {
t.Helper()
_, n := navigationFixture(t)
f := &doorFixture{}
f.h = &Routes{bridge: &Bridge{now: time.Now, render: func(w http.ResponseWriter, r *http.Request, state, label string, status int) { w.WriteHeader(status) }}, navigation: n, cfg: RoutesConfig{Origin: navigationOrigin, SessionCookie: "__Host-rastrillo_session", ReadSession: func(r *http.Request) (*Session, error) {
c, err := r.Cookie("__Host-rastrillo_session")
if err != nil || (c.Value != "verified" && c.Value != "guest") {
return nil, nil
}
method := HomeMethod
if c.Value == "guest" {
method = "guest"
}
return &Session{Subject: "pr_live", Method: method, At: time.Now()}, nil
}}}
f.h.cfg.LocalSignin = func(w http.ResponseWriter, r *http.Request) {
f.calls++
f.href, f.path = OficinaHref(r), r.URL.Path
w.WriteHeader(299)
}
return f
}
func (f *doorFixture) get(handler http.HandlerFunc, target string, cookies ...*http.Cookie) *httptest.ResponseRecorder {
f.href, f.path = "unset", ""
r := httptest.NewRequest(http.MethodGet, navigationOrigin+target, nil)
for _, c := range cookies {
r.AddCookie(c)
}
w := httptest.NewRecorder()
handler(w, r)
return w
}
var (
liveSession = &http.Cookie{Name: "__Host-rastrillo_session", Value: "verified"}
staleSession = &http.Cookie{Name: "__Host-rastrillo_session", Value: "revoked"}
guestSession = &http.Cookie{Name: "__Host-rastrillo_session", Value: "guest"}
)
// TestBareSigninRendersTheDoor is the smart door's first route: GET /signin
// always renders the door, and never starts a Home exchange. Before, a bare
// /signin went straight to id.oficina.works (connect's query dispatch), so
// nobody could pick email from it. Nothing is remembered and no cookie is
// set: the exchange, and its return cookie, belong to /signin/oficina.
func TestBareSigninRendersTheDoor(t *testing.T) {
f := newDoorFixture(t)
for _, tc := range []struct {
target string
cookies []*http.Cookie
href string
}{
{"/signin", nil, SigninOficinaPath},
{"/signin?return_to=%2Fd%2F42%3Fview%3Dcompact", nil, "/signin/oficina?return_to=%2Fd%2F42%3Fview%3Dcompact"},
// A stale cookie, an ambiguous pair or a Calls guest is not signed
// in: the door, as for nobody.
{"/signin?return_to=%2Fd%2F42", []*http.Cookie{staleSession}, "/signin/oficina?return_to=%2Fd%2F42"},
{"/signin?return_to=%2Fd%2F42", []*http.Cookie{liveSession, liveSession}, "/signin/oficina?return_to=%2Fd%2F42"},
{"/signin?return_to=%2Fd%2F42", []*http.Cookie{guestSession}, "/signin/oficina?return_to=%2Fd%2F42"},
// The chooser and a picked way are the door's own pages.
{"/signin?ways=1&way=oficina", nil, SigninOficinaPath},
{"/signin?way=email&return_to=%2Fd%2F1", nil, "/signin/oficina?return_to=%2Fd%2F1"},
// A return_to connect would not follow is left off, as the exchange
// would land on "/" anyway.
{"/signin?return_to=https%3A%2F%2Fevil.example%2F", nil, SigninOficinaPath},
{"/signin?return_to=%2F%2Fevil.example", nil, SigninOficinaPath},
{"/signin?return_to=%2Fsignin", nil, SigninOficinaPath},
{"/signin?return_to=%2Fa&return_to=%2Fb", nil, SigninOficinaPath},
} {
calls := f.calls
w := f.get(f.h.SigninDoor, tc.target, tc.cookies...)
if w.Code != 299 || f.calls != calls+1 {
t.Fatalf("%s: %d %q, want the door", tc.target, w.Code, w.Header().Get("Location"))
}
if f.href != tc.href {
t.Fatalf("%s: Oficina href %q, want %q", tc.target, f.href, tc.href)
}
if len(w.Result().Cookies()) != 0 {
t.Fatalf("%s: the door set a cookie", tc.target)
}
}
}
// TestSigninWhenAlreadySignedIn is spec shared-chrome §9.4, kept on the
// door: a live session goes straight to the validated return_to, or /,
// with no door and no exchange. A query naming a state of the door (a
// sent link, a problem, Keymail's force, a step-up, a continuation) is
// drawn even then.
func TestSigninWhenAlreadySignedIn(t *testing.T) {
f := newDoorFixture(t)
for _, tc := range []struct{ query, want string }{
{"?return_to=%2Fd%2F42%3Fview%3Dcompact", "/d/42?view=compact"},
{"", "/"},
{"?return_to=https%3A%2F%2Fevil.example%2F", "/"},
{"?return_to=%2F%2Fevil.example", "/"},
{"?return_to=%2Fsignin", "/"},
{"?return_to=%2Fa&return_to=%2Fb", "/"},
} {
for _, route := range []struct {
path string
handler http.HandlerFunc
}{{SigninPath, f.h.SigninDoor}, {SigninOficinaPath, f.h.SigninOficina}} {
w := f.get(route.handler, route.path+tc.query, liveSession)
if w.Code != 303 || w.Header().Get("Location") != tc.want {
t.Fatalf("%s%s: %d %q", route.path, tc.query, w.Code, w.Header().Get("Location"))
}
if w.Header().Get("Cache-Control") != "no-store" || len(w.Result().Cookies()) != 0 {
t.Fatalf("%s%s: cacheable, or set a cookie", route.path, tc.query)
}
}
}
for _, query := range []string{"?force=1", "?err=removed", "?err=rate", "?sent=1&attempt=x", "?reauth=1", "?continue=abc"} {
calls := f.calls
if w := f.get(f.h.SigninDoor, SigninPath+query, liveSession); w.Code != 299 || f.calls != calls+1 {
t.Fatalf("%s with a live session: %d, want the door", query, w.Code)
}
}
if w := f.get(f.h.SigninDoor, "/signin?%zz", nil...); w.Code != 400 {
t.Fatal("a malformed query reached the door", w.Code)
}
}
// TestSigninLocalIsEmailOnly: /signin/local is where connect sends people
// Oficina ID could not help (unknown, failed, a link to resume, "Connect my
// existing account", a step-up to link). Its door must never offer Oficina
// ID, or those people would loop through Home and back. It has no
// signed-in shortcut either: a signed-in person too stale to link is sent
// here precisely to sign in again.
func TestSigninLocalIsEmailOnly(t *testing.T) {
f := newDoorFixture(t)
for _, target := range []string{"/signin/local", "/signin/local?return_to=%2Fd%2F42", "/signin/local?way=oficina", "/signin/local?ways=1"} {
for _, cookies := range [][]*http.Cookie{nil, {liveSession}} {
calls := f.calls
w := f.get(f.h.SigninLocal, target, cookies...)
if w.Code != 299 || f.calls != calls+1 || f.path != SigninLocalPath {
t.Fatalf("%s (%d cookies): %d %q, want the door", target, len(cookies), w.Code, w.Header().Get("Location"))
}
if f.href != "" {
t.Fatalf("%s offered Oficina ID: %q", target, f.href)
}
}
}
// Every flow that ends locally ends here.
for state, want := range map[string]string{"unknown": SigninLocalPath, "failed": SigninLocalPath, "anything": SigninLocalPath, "signedout": SigninPath} {
if got := Page(state, "").Action; got != want {
t.Errorf("%s leads to %q, want %q", state, got, want)
}
}
}
// TestOficinaHrefOnlyWhereTheDoorMayOfferIt: the href exists only on a
// request connect's /signin handed to the app, and never on a step-up.
func TestOficinaHrefOnlyWhereTheDoorMayOfferIt(t *testing.T) {
if got := OficinaHref(httptest.NewRequest(http.MethodGet, navigationOrigin+"/signin", nil)); got != "" {
t.Fatalf("a door connect did not hand over offers Oficina ID: %q", got)
}
f := newDoorFixture(t)
for _, query := range []string{"?reauth=1", "?reauth=1&return_to=%2Fd%2F42", "?reauth=0", "?reauth=1&way=oficina", "?ways=1&reauth=1"} {
f.get(f.h.SigninDoor, SigninPath+query)
if f.href != "" {
t.Fatalf("%s: a step-up offered Oficina ID: %q", query, f.href)
}
}
}
// TestSigninOficinaStartsTheExchange is "Continue with Oficina ID": the
// sealed return cookie remembers the page, and the browser goes to
// handoff.StartPath with it. A return_to connect would not follow is "/".
func TestSigninOficinaStartsTheExchange(t *testing.T) {
f := newDoorFixture(t)
for _, tc := range []struct {
query string
cookies []*http.Cookie
want string
}{
{"?return_to=%2Fd%2F42%3Fview%3Dcompact", nil, "/d/42?view=compact"},
{"", nil, "/"},
{"?return_to=https%3A%2F%2Fevil.example%2F", nil, "/"},
{"?return_to=%2F%2Fevil.example", nil, "/"},
{"?return_to=%2Fsignin", nil, "/"},
{"?return_to=%2Fauth%2Fstart", nil, "/"},
{"?return_to=%2Fa&return_to=%2Fb", nil, "/"},
{"?return_to=javascript%3Aalert(1)", nil, "/"},
{"?return_to=%2Fd%2F42", []*http.Cookie{staleSession}, "/d/42"},
{"?return_to=%2Fd%2F42", []*http.Cookie{liveSession, liveSession}, "/d/42"},
{"?return_to=%2Fd%2F42", []*http.Cookie{guestSession}, "/d/42"},
} {
w := f.get(f.h.SigninOficina, SigninOficinaPath+tc.query, tc.cookies...)
start := handoff.StartPath + "?" + url.Values{"return_to": {tc.want}}.Encode()
if w.Code != 303 || w.Header().Get("Location") != start {
t.Fatalf("%s: %d %q", tc.query, w.Code, w.Header().Get("Location"))
}
if w.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("%s: cacheable", tc.query)
}
var remembered *http.Cookie
for _, c := range w.Result().Cookies() {
if c.Name == homeReturnCookie {
remembered = c
}
}
if remembered == nil || remembered.MaxAge <= 0 || !remembered.Secure || !remembered.HttpOnly {
t.Fatalf("%s: the page was not remembered", tc.query)
}
back := httptest.NewRequest(http.MethodGet, navigationOrigin+"/auth/finish", nil)
back.AddCookie(remembered)
if got := f.h.navigation.returnPath(back); got != tc.want {
t.Fatalf("%s: remembered %q, want %q", tc.query, got, tc.want)
}
if f.calls != 0 {
t.Fatal("Continue with Oficina ID drew the door")
}
}
if w := f.get(f.h.SigninOficina, SigninOficinaPath+"?%zz"); w.Code != 400 || w.Header().Get("Location") != "" {
t.Fatal("a malformed query started an exchange", w.Code)
}
// Failing to remember is a 503, never an exchange that forgets the page.
f.h.navigation.now = func() time.Time { return time.Unix(0, 0) }
if w := f.get(f.h.SigninOficina, SigninOficinaPath+"?return_to=%2Fd%2F42"); w.Code != 503 || w.Header().Get("Location") != "" {
t.Fatal("an unremembered return started the exchange", w.Code)
}
}
// TestStepUpNeverReachesHome is the spec's reauth rule: a step-up offers
// local ways only. Linking needs FreshLocal, which no Home sign-in gives,
// and a live id.* session would hand back an old auth_time. So a reauth
// that reaches /signin/oficina anyway goes to the local door, keeping it.
func TestStepUpNeverReachesHome(t *testing.T) {
f := newDoorFixture(t)
for _, tc := range []struct{ query, want string }{
{"?reauth=1&return_to=%2Fd%2F42", "/signin/local?reauth=1&return_to=%2Fd%2F42"},
{"?reauth=1", "/signin/local?reauth=1"},
{"?reauth=yes&return_to=%2F%2Fevil.example", "/signin/local?reauth=1"},
} {
for _, cookies := range [][]*http.Cookie{nil, {liveSession}} {
w := f.get(f.h.SigninOficina, SigninOficinaPath+tc.query, cookies...)
if w.Code != 303 || w.Header().Get("Location") != tc.want || len(w.Result().Cookies()) != 0 {
t.Fatalf("%s: %d %q", tc.query, w.Code, w.Header().Get("Location"))
}
}
}
// The link flow's own step-up: a session too old to link goes to the
// local door, which offers no Oficina ID.
_, n := navigationFixture(t)
f.h.navigation = n
w := httptest.NewRecorder()
n.Begin(w, httptest.NewRequest(http.MethodGet, navigationOrigin+"/account/home", nil))
if w.Code != 303 || w.Header().Get("Location") != linkStepUpPath {
t.Fatalf("link step-up: %d %q", w.Code, w.Header().Get("Location"))
}
f.get(f.h.SigninLocal, w.Header().Get("Location"), liveSession)
if f.href != "" {
t.Fatal("the link step-up offered Oficina ID")
}
if _, fresh := FreshLocal(Session{Subject: "pr_x", Method: HomeMethod, AuthTime: time.Now()}, time.Now()); fresh {
t.Fatal("a Home sign-in counted as a fresh local one")
}
}
// TestLinkStepUpStaysLocalPastTheFirstPage is Fable's finding 1 on
// f763fbc. Linking sends a signed-in person to sign in again, and the
// first page is /signin/local. Every page after it is rastrillo's: an
// outcome, a chooser link, Forget and Begin all go to auth.Config.SigninPath,
// which is /signin on the smart door. Marked reauth=1, they carry the
// step-up, so /signin still draws the door (no shortcut to "/" before the
// person has signed in again) and still offers no Oficina ID.
func TestLinkStepUpStaysLocalPastTheFirstPage(t *testing.T) {
f := newDoorFixture(t)
_, n := navigationFixture(t)
w := httptest.NewRecorder()
n.Begin(w, httptest.NewRequest(http.MethodGet, navigationOrigin+"/account/home", nil))
first, err := url.Parse(w.Header().Get("Location"))
if err != nil || first.Path != SigninLocalPath || first.Query().Get("reauth") != "1" {
t.Fatalf("link step-up is not marked: %q", w.Header().Get("Location"))
}
// What rastrillo v0.38.0's one-way screen sends next, with SigninPath
// /signin (auth/oneway.go: signinHref sets reauth=1 on every chooser
// link and Back; afterForget and keepReauth keep it on Forget's and
// Begin's redirects). connect cannot import auth here without pulling
// rastrillo's whole module graph into its go.sum, so the shapes are
// written out.
for _, next := range []string{
SigninPath + "?reauth=1&way=email", // EmailHref, Use a different email
SigninPath + "?reauth=1", // Back
SigninPath + "?err=rate&reauth=1", // Begin's rate limit, kept by keepReauth
SigninPath + "?reauth=1&return_to=%2Fd%2F42&ways=1", // the chooser
} {
calls := f.calls
w := f.get(f.h.SigninDoor, next, liveSession)
if w.Code != 299 || f.calls != calls+1 {
t.Fatalf("%s bounced a person stepping up: %d %q", next, w.Code, w.Header().Get("Location"))
}
if f.href != "" {
t.Fatalf("%s offered Oficina ID to a step-up", next)
}
}
}
// TestSignedOutOffersForget: with ForgetPath, the signed-out page carries a
// second form, "Forget me on this device", posting to the app's Forget.
// Without it there is none, as before. It is a plain same-origin form, so
// the app's csrf.Protect admits it from this origin, refuses it from any
// other, and Middleware exempts nothing for it.
func TestSignedOutOffersForget(t *testing.T) {
f := newBridgeFixture(t)
for _, forget := range []string{"", "/signin/forget", "/auth/forget"} {
var got PageData
cfg := RoutesConfig{Namespace: "oficina/docs", Origin: bridgeOrigin, Issuer: bridgeIssuer, SessionCookie: f.sessions.cookie, DEK: bytes.Repeat([]byte{41}, 32), ForgetPath: forget,
ReadSession: func(*http.Request) (*Session, error) { return nil, nil },
SignOut: func(http.ResponseWriter, *http.Request) {}, LocalSignin: func(http.ResponseWriter, *http.Request) {},
Protect: csrf.Protect(bridgeOrigin),
Render: func(w http.ResponseWriter, r *http.Request, state, label string, status int) {
got = PageFor(r, state, label)
for _, other := range []string{"failed", "unknown", "success", "start"} {
if PageFor(r, other, label).ForgetAction != "" {
t.Fatalf("%s offered Forget", other)
}
}
w.WriteHeader(status)
}}
h, err := NewRoutes(f.b, cfg)
if err != nil {
t.Fatal(forget, err)
}
w := httptest.NewRecorder()
h.SignedOut(w, bridgeRequest(http.MethodGet, "/signed-out", nil))
if w.Code != 200 || got.Title != "You’re signed out" || got.Action != SigninPath || got.ForgetAction != forget {
t.Fatalf("ForgetPath %q: %d %+v", forget, w.Code, got)
}
if forget == "" {
continue
}
reached := 0
handler := h.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached++; w.WriteHeader(303) }))
for _, tc := range []struct {
header, value string
want int
}{{"Origin", bridgeOrigin, 303}, {"Sec-Fetch-Site", "same-origin", 303}, {"Origin", "https://evil.example", 403}, {"Sec-Fetch-Site", "cross-site", 403}, {"", "", 403}} {
r := httptest.NewRequest(http.MethodPost, bridgeOrigin+forget, strings.NewReader(""))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if tc.header != "" {
r.Header.Set(tc.header, tc.value)
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
if w.Code != tc.want {
t.Fatalf("Forget POST with %s %q: %d, want %d", tc.header, tc.value, w.Code, tc.want)
}
}
if reached != 2 {
t.Fatal("Forget reached past the same-origin check", reached)
}
}
// Only the page Routes.SignedOut draws carries it.
r := bridgeRequest(http.MethodGet, "/signed-out", nil)
if Page("signedout", "").ForgetAction != "" || PageFor(r, "signedout", "").ForgetAction != "" {
t.Fatal("Forget offered without the signed-out route")
}
// The Home-derived sign-out still chains to id.* (TestSignoutChainsToTheIssuer).
}
// TestForgetPathMustBeLocal: a form action that could leave the origin, or
// carry a query, is refused at boot rather than drawn.
func TestForgetPathMustBeLocal(t *testing.T) {
f := newBridgeFixture(t)
for _, bad := range []string{"signin/forget", "//evil.example/forget", "https://evil.example/forget", "/forget?x=1", "/forget#x", "/a/../forget", "/a\\forget", "/a%2Fforget", "/forget/", "/a//forget", "javascript:alert(1)"} {
_, err := NewRoutes(f.b, RoutesConfig{Namespace: "oficina/docs", Origin: bridgeOrigin, Issuer: bridgeIssuer, SessionCookie: f.sessions.cookie, DEK: bytes.Repeat([]byte{41}, 32), ForgetPath: bad,
ReadSession: func(*http.Request) (*Session, error) { return nil, nil }, SignOut: func(http.ResponseWriter, *http.Request) {}, LocalSignin: func(http.ResponseWriter, *http.Request) {},
Protect: func(next http.Handler) http.Handler { return next }, Render: f.b.render})
if err == nil {
t.Errorf("ForgetPath %q accepted", bad)
}
}
}
// TestPageDataStillDrawsTheSharedTemplate: PageData stopped being an alias
// of estilo's homeconnect.PageData when it gained ForgetAction. Its shared
// fields keep their names, so estilo's home-connect template draws it.
func TestPageDataStillDrawsTheSharedTemplate(t *testing.T) {
view := template.Must(template.ParseFS(Templates(), "templates/*.html"))
var out bytes.Buffer
if err := view.ExecuteTemplate(&out, "home-connect", Page("confirm", "person@example.test")); err != nil {
t.Fatal(err)
}
for _, want := range []string{English["confirm_title"], `action="/account/home/confirm"`, "person@example.test", English["cancel_action"]} {
if !strings.Contains(out.String(), want) {
t.Fatalf("missing %q in %s", want, out.String())
}
}
// And a struct embedding it, as Slides and Sheets do.
type appView struct{ PageData }
out.Reset()
if err := view.ExecuteTemplate(&out, "home-connect", appView{Page("start", "")}); err != nil || !strings.Contains(out.String(), English["start_title"]) {
t.Fatal("an embedding view no longer draws", err)
}
}
// TestMintedPersonIsWhoJustSignedIn: MintHomeSession is where an app
// remembers "Continue with Oficina ID" (the smart door's federated record),
// with the address of the person who just signed in, or none. connect hands
// it that person on the minting request only: the linked local account, or
// a Home-only person with no address. Never on link, choose or unknown.
func TestMintedPersonIsWhoJustSignedIn(t *testing.T) {
type mint struct {
person Person
ok bool
}
watch := func(f *bridgeFixture) *[]mint {
var seen []mint
inner := f.b.mintSession
f.b.mintSession = func(w http.ResponseWriter, r *http.Request, s Session) error {
p, ok := MintedPerson(r)
seen = append(seen, mint{p, ok})
return inner(w, r, s)
}
return &seen
}
f := newBridgeFixture(t)
seen := watch(f)
local := f.local(t, "one@example.com", "magiclink", time.Time{})
f.link(t, local, "opaque-subject-one")
if len(*seen) != 0 {
t.Fatal("linking minted a Home session")
}
unknown := f.finishAs(t, "opaque-subject-nobody", nil)
if unknown.Code != 403 || len(*seen) != 0 {
t.Fatal("an unknown subject minted", unknown.Code)
}
if w := f.finishAs(t, "opaque-subject-one", nil); w.Code != 303 {
t.Fatalf("ordinary finish=%d", w.Code)
}
var id int64
if err := f.db.QueryRow("SELECT id FROM people WHERE email='one@example.com'").Scan(&id); err != nil {
t.Fatal(err)
}
if len(*seen) != 1 || !(*seen)[0].ok || (*seen)[0].person != (Person{ID: id, Label: "one@example.com"}) {
t.Fatalf("minted with %+v", *seen)
}
if _, ok := MintedPerson(bridgeRequest(http.MethodGet, "/", nil)); ok {
t.Fatal("a person on a request that minted nothing")
}
team, _ := newHomeOnlyFixture(t)
seen = watch(team)
finish := team.finishAs(t, "pr_member", nil)
if len(*seen) != 0 {
t.Fatal("the choose page minted")
}
if _, w := team.choose(t, finish, "new", nil); w.Code != 303 {
t.Fatalf("choose new=%d", w.Code)
}
if len(*seen) != 1 || !(*seen)[0].ok || (*seen)[0].person.ID <= 1000 || (*seen)[0].person.Label != "" {
t.Fatalf("a new member minted with %+v", *seen)
}
}
// TestConnectImportsNoLastsignin: remembering the way in is each app's job
// (MintHomeSession), so connect never forces a rastrillo minor on its
// consumers by importing lastsignin, directly or through auth.
func TestConnectImportsNoLastsignin(t *testing.T) {
out, err := exec.Command("go", "list", "-deps", "./...").Output()
if err != nil {
t.Fatal("go list -deps failed, so nothing was checked:", err)
}
if !strings.Contains(string(out), "amadan.net/oficina/home/connect\n") {
t.Fatal("go list -deps did not list connect itself")
}
for _, dep := range strings.Fields(string(out)) {
switch dep {
case "amadan.net/rastrillo/rastrillo/lastsignin", "amadan.net/rastrillo/rastrillo/auth":
t.Errorf("connect depends on %s", dep)
}
}
}