| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | "net/http/httptest" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/home/connect" |
| 11 | "amadan.net/oficina/home/connect/linkstore" |
| 12 | "amadan.net/rastrillo/rastrillo/sessions" |
| 13 | ) |
| 14 | |
| 15 | // subjectsFunc stands in for connect's Resolve. |
| 16 | type subjectsFunc func(ctx context.Context, subject string) (connect.Person, error) |
| 17 | |
| 18 | func (f subjectsFunc) Resolve(ctx context.Context, subject string) (connect.Person, error) { |
| 19 | return f(ctx, subject) |
| 20 | } |
| 21 | |
| 22 | // freshLocalAuthentication is connect's rule before linking |
| 23 | // (connect.FreshLocal, the rule Docs' own bridge had), over the sessions |
| 24 | // Docs actually mints. |
| 25 | func freshLocalAuthentication(s sessions.Session, now time.Time) (time.Time, bool) { |
| 26 | return connect.FreshLocal(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, now) |
| 27 | } |
| 28 | |
| 29 | func identityRequest(method, subject, authMethod string) *http.Request { |
| 30 | return sessions.WithSession(httptest.NewRequest(method, "https://docs.example/", nil), sessions.Session{Subject: subject, Method: authMethod}) |
| 31 | } |
| 32 | |
| 33 | func TestHomeIdentityNeverCreatesPersonOrSamples(t *testing.T) { |
| 34 | app := newSampleDocumentsInternalTestApp(t, "1") |
| 35 | store := app.Store() |
| 36 | h := &handlers{store: store} |
| 37 | for _, subject := range []string{"opaque_subject", "looks-like-local@example.com"} { |
| 38 | r := identityRequest("GET", subject, homeAssertionMethod) |
| 39 | if _, err := h.owner(r); err != errIdentityRefused { |
| 40 | t.Fatal("unconfigured Home identity reached legacy owner", err) |
| 41 | } |
| 42 | if _, err := h.actor(r); err != errIdentityRefused { |
| 43 | t.Fatal("unconfigured Home identity reached legacy actor", err) |
| 44 | } |
| 45 | if h.member(r) { |
| 46 | t.Fatal("unconfigured Home identity gained membership") |
| 47 | } |
| 48 | for _, answer := range []struct { |
| 49 | p connect.Person |
| 50 | err error |
| 51 | }{{connect.Person{}, linkstore.ErrRefused}, {connect.Person{ID: 0, Label: "x@example.com"}, nil}, {connect.Person{ID: 999999}, nil}} { |
| 52 | v := identityResolver{store: store, issuer: "https://id.example", links: subjectsFunc(func(ctx context.Context, got string) (connect.Person, error) { |
| 53 | if got != subject { |
| 54 | t.Fatal("subject changed") |
| 55 | } |
| 56 | return answer.p, answer.err |
| 57 | })} |
| 58 | reached := false |
| 59 | rec := httptest.NewRecorder() |
| 60 | v.middleware("/signin")(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true })).ServeHTTP(rec, r) |
| 61 | if reached || rec.Code != 303 { |
| 62 | t.Fatal("unknown Home identity reached handler") |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | var people, documents int64 |
| 67 | if err := store.db.Model(&Person{}).Count(&people).Error; err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | if err := store.db.Model(&Document{}).Count(&documents).Error; err != nil { |
| 71 | t.Fatal(err) |
| 72 | } |
| 73 | if people != 0 || documents != 0 { |
| 74 | t.Fatalf("Home path created people=%d documents=%d", people, documents) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func TestLinkedHomeIdentityPreservesOwnersAndAddressGrants(t *testing.T) { |
| 79 | app := newSampleDocumentsInternalTestApp(t, "0") |
| 80 | store := app.Store() |
| 81 | ctx := t.Context() |
| 82 | alice, err := store.EnsurePerson(ctx, "alice@example.com") |
| 83 | if err != nil { |
| 84 | t.Fatal(err) |
| 85 | } |
| 86 | bob, err := store.EnsurePerson(ctx, "bob@example.com") |
| 87 | if err != nil { |
| 88 | t.Fatal(err) |
| 89 | } |
| 90 | own, err := store.createDocument(ctx, alice, "Alice private", "", VisibilityPrivate) |
| 91 | if err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | shared, err := store.createDocument(ctx, bob, "Bob shared", "", VisibilityPrivate) |
| 95 | if err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | hidden, err := store.createDocument(ctx, bob, "Bob private", "", VisibilityPrivate) |
| 99 | if err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | if err = store.Grant(ctx, bob, shared.Sqid, "alice@example.com", RoleWriter); err != nil { |
| 103 | t.Fatal(err) |
| 104 | } |
| 105 | v := identityResolver{store: store, issuer: "https://id.example", links: subjectsFunc(func(ctx context.Context, subject string) (connect.Person, error) { |
| 106 | if subject != "opaque_alice" { |
| 107 | return connect.Person{}, linkstore.ErrRefused |
| 108 | } |
| 109 | // connect reads the person's current address on every Resolve. |
| 110 | address, err := linkedAddress(ctx, app.db.Writer(), alice) |
| 111 | return connect.Person{ID: alice, Label: address}, err |
| 112 | })} |
| 113 | memberAddresses := []string{} |
| 114 | h := &handlers{store: store, isMember: func(address string) bool { |
| 115 | memberAddresses = append(memberAddresses, address) |
| 116 | return address == "alice@example.com" |
| 117 | }} |
| 118 | reached := false |
| 119 | end := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 120 | reached = true |
| 121 | a, err := h.actor(r) |
| 122 | if err != nil || a.PersonID != alice || (a.VerifiedAddress == nil || *a.VerifiedAddress != "alice@example.com") { |
| 123 | t.Fatal("linked actor changed", a, err) |
| 124 | } |
| 125 | id, err := h.owner(r) |
| 126 | if err != nil || id != alice { |
| 127 | t.Fatal("linked owner changed", err) |
| 128 | } |
| 129 | if !h.member(r) { |
| 130 | t.Fatal("member did not use verified local address") |
| 131 | } |
| 132 | for _, d := range []*Document{own, shared} { |
| 133 | got, err := store.GetFor(ctx, a, d.Sqid) |
| 134 | if err != nil || got.ID != d.ID || !store.CanWrite(ctx, a, d.ID) { |
| 135 | t.Fatal("existing access lost", err) |
| 136 | } |
| 137 | } |
| 138 | if _, err := store.GetFor(ctx, a, hidden.Sqid); err == nil { |
| 139 | t.Fatal("link widened access") |
| 140 | } |
| 141 | if id, ok := currentIdentity(r); !ok || id.Session.Subject != "opaque_alice" { |
| 142 | t.Fatal("opaque identity not kept separate") |
| 143 | } |
| 144 | }) |
| 145 | rec := httptest.NewRecorder() |
| 146 | v.middleware("/signin")(end).ServeHTTP(rec, identityRequest("GET", "opaque_alice", homeAssertionMethod)) |
| 147 | if !reached || len(memberAddresses) != 1 { |
| 148 | t.Fatal("adapter not used") |
| 149 | } |
| 150 | var after Document |
| 151 | if err = store.db.First(&after, own.ID).Error; err != nil || after.OwnerID != alice { |
| 152 | t.Fatal("ownership rewritten") |
| 153 | } |
| 154 | grants, err := store.ListGrants(ctx, bob, shared.Sqid) |
| 155 | if err != nil || len(grants) != 1 || grants[0].Subject != "alice@example.com" { |
| 156 | t.Fatal("grant rewritten") |
| 157 | } |
| 158 | // Resolve the current local address on every request, not a saved copy. |
| 159 | if err = store.db.Model(&Person{}).Where("id=?", alice).Update("email", "renamed@example.com").Error; err != nil { |
| 160 | t.Fatal(err) |
| 161 | } |
| 162 | id, err := v.resolve(identityRequest("GET", "opaque_alice", homeAssertionMethod)) |
| 163 | if err != nil || (id.Actor.VerifiedAddress == nil || *id.Actor.VerifiedAddress != "renamed@example.com") { |
| 164 | t.Fatal("stale local address") |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | func TestHomeAdmissionRequiresAdapterAndCurrentAddress(t *testing.T) { |
| 169 | app := newSampleDocumentsInternalTestApp(t, "0") |
| 170 | store := app.Store() |
| 171 | person, err := store.EnsurePerson(t.Context(), "local@example.com") |
| 172 | if err != nil { |
| 173 | t.Fatal(err) |
| 174 | } |
| 175 | list, err := resolveAllowlist(Config{AllowedAddresses: "local@example.com"}) |
| 176 | if err != nil { |
| 177 | t.Fatal(err) |
| 178 | } |
| 179 | v := identityResolver{store: store, issuer: "https://id.example", links: subjectsFunc(func(context.Context, string) (connect.Person, error) { |
| 180 | return connect.Person{ID: person, Label: "local@example.com"}, nil |
| 181 | })} |
| 182 | reached := false |
| 183 | next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { reached = true }) |
| 184 | for _, method := range []string{"GET", "POST"} { |
| 185 | reached = false |
| 186 | rec := httptest.NewRecorder() |
| 187 | requireAdmission(list, "/signin")(next).ServeHTTP(rec, identityRequest(method, "local@example.com", homeAssertionMethod)) |
| 188 | if reached || (method == "GET" && rec.Code != 303) || (method == "POST" && rec.Code != 403) { |
| 189 | t.Fatal("opaque address bypassed adapter") |
| 190 | } |
| 191 | } |
| 192 | rec := httptest.NewRecorder() |
| 193 | v.middleware("/signin")(requireAdmission(list, "/signin")(next)).ServeHTTP(rec, identityRequest("GET", "opaque", homeAssertionMethod)) |
| 194 | if !reached { |
| 195 | t.Fatal("resolved local address not admitted") |
| 196 | } |
| 197 | reached = false |
| 198 | list, err = resolveAllowlist(Config{AllowedAddresses: "someone-else@example.com"}) |
| 199 | if err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | rec = httptest.NewRecorder() |
| 203 | v.middleware("/signin")(requireAdmission(list, "/signin")(next)).ServeHTTP(rec, identityRequest("POST", "opaque", homeAssertionMethod)) |
| 204 | if reached || rec.Code != 403 { |
| 205 | t.Fatal("link bypassed changed admission") |
| 206 | } |
| 207 | v.links = subjectsFunc(func(context.Context, string) (connect.Person, error) { return connect.Person{}, linkstore.ErrStorage }) |
| 208 | rec = httptest.NewRecorder() |
| 209 | v.middleware("/signin")(next).ServeHTTP(rec, identityRequest("POST", "opaque", homeAssertionMethod)) |
| 210 | if reached || rec.Code != 503 { |
| 211 | t.Fatal("storage failure became admission or permanent write refusal") |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | func TestLocalFreshnessUsesActualMethodAndVerificationTime(t *testing.T) { |
| 216 | now := time.Unix(1700000000, 0) |
| 217 | for _, tc := range []struct { |
| 218 | name, method string |
| 219 | auth, created time.Time |
| 220 | want bool |
| 221 | }{ |
| 222 | {"magic original", "magiclink", now.Add(-time.Minute), now, true}, |
| 223 | {"magic persisted creation", "magiclink", time.Time{}, now.Add(-time.Minute), true}, |
| 224 | {"boundary", "magiclink", now.Add(-5 * time.Minute), now, true}, |
| 225 | {"old verification fresh remint", "magiclink", now.Add(-301 * time.Second), now, false}, |
| 226 | {"old persisted creation", "magiclink", time.Time{}, now.Add(-301 * time.Second), false}, |
| 227 | {"future verification", "magiclink", now.Add(time.Second), now, false}, |
| 228 | {"future creation", "magiclink", time.Time{}, now.Add(time.Second), false}, |
| 229 | {"missing times", "magiclink", time.Time{}, time.Time{}, false}, |
| 230 | {"keymail actual", "keymail", now.Add(-time.Minute), now, true}, |
| 231 | {"keymail no original", "keymail", time.Time{}, now, false}, |
| 232 | {"keymail stale", "keymail", now.Add(-301 * time.Second), now, false}, |
| 233 | {"keymail future", "keymail", now.Add(time.Second), now, false}, |
| 234 | {"home original", "home-assertion", now, now, false}, |
| 235 | {"home remint", "home-assertion", time.Time{}, now, false}, |
| 236 | {"other original", "password", now, now, false}, |
| 237 | {"unknown remint", "", time.Time{}, now, false}, |
| 238 | } { |
| 239 | t.Run(tc.name, func(t *testing.T) { |
| 240 | got, ok := freshLocalAuthentication(sessions.Session{Subject: "local@example.com", Method: tc.method, AuthTime: tc.auth, At: tc.created}, now) |
| 241 | if ok != tc.want { |
| 242 | t.Fatal("wrong local freshness decision") |
| 243 | } |
| 244 | expected := tc.auth |
| 245 | if expected.IsZero() { |
| 246 | expected = tc.created |
| 247 | } |
| 248 | if ok && !got.Equal(expected) { |
| 249 | t.Fatal("verification time rewritten") |
| 250 | } |
| 251 | if !ok && !got.IsZero() { |
| 252 | t.Fatal("refused proof returned freshness") |
| 253 | } |
| 254 | }) |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | func TestLocalMagicLinkUsesPersistedVerificationAndRotation(t *testing.T) { |
| 259 | app := newSampleDocumentsInternalTestApp(t, "0") |
| 260 | reader, err := sessions.New(sessions.Config{DB: app.db.Writer(), Origin: app.cfg.Origin}) |
| 261 | if err != nil { |
| 262 | t.Fatal(err) |
| 263 | } |
| 264 | first := app.TestRequest(t, "local@example.com", "GET", "/", nil) |
| 265 | session, ok := reader.From(first) |
| 266 | // From rastrillo v0.45.0 a magic link records when it was verified |
| 267 | // (AuthTime), so freshness reads that rather than falling back to |
| 268 | // the row's creation time. |
| 269 | if !ok || session.Method != "magiclink" || session.AuthTime.IsZero() || session.At.IsZero() { |
| 270 | t.Fatal("real local magic-link session did not record its verification time") |
| 271 | } |
| 272 | verified, ok := freshLocalAuthentication(session, time.Now()) |
| 273 | if !ok || !verified.Equal(session.AuthTime) { |
| 274 | t.Fatal("actual completed magic link not fresh") |
| 275 | } |
| 276 | oldCookie, err := first.Cookie(reader.CookieName()) |
| 277 | if err != nil { |
| 278 | t.Fatal(err) |
| 279 | } |
| 280 | // Complete a second real local email token while presenting the first session. |
| 281 | link, err := app.TestSignIn(t, "local@example.com") |
| 282 | if err != nil { |
| 283 | t.Fatal(err) |
| 284 | } |
| 285 | verify := confirmRequest(link) |
| 286 | verify.AddCookie(oldCookie) |
| 287 | rec := httptest.NewRecorder() |
| 288 | app.Handler().ServeHTTP(rec, verify) |
| 289 | if rec.Code != 303 { |
| 290 | t.Fatal("local reverification failed", rec.Code) |
| 291 | } |
| 292 | second := httptest.NewRequest("GET", "/", nil) |
| 293 | for _, c := range rec.Result().Cookies() { |
| 294 | second.AddCookie(c) |
| 295 | } |
| 296 | if _, ok = reader.From(first); ok { |
| 297 | t.Fatal("reverification left old session usable") |
| 298 | } |
| 299 | next, ok := reader.From(second) |
| 300 | if !ok { |
| 301 | t.Fatal("rotated session missing") |
| 302 | } |
| 303 | if _, ok = freshLocalAuthentication(next, time.Now()); !ok { |
| 304 | t.Fatal("rotated real magic link not fresh") |
| 305 | } |
| 306 | newCookie, err := second.Cookie(reader.CookieName()) |
| 307 | if err != nil || newCookie.Value == oldCookie.Value { |
| 308 | t.Fatal("actual browser binding did not rotate") |
| 309 | } |
| 310 | } |
| 311 | |