| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/home/connect" |
| 12 | "amadan.net/oficina/home/connect/linkstore" |
| 13 | "amadan.net/rastrillo/rastrillo" |
| 14 | "amadan.net/rastrillo/rastrillo/sessions" |
| 15 | "github.com/carlosframework/docs/internal/docs/principalstore" |
| 16 | ) |
| 17 | |
| 18 | // homeAssertionMethod is the session method of a browser Home sign-in. It |
| 19 | // is connect's, and was Docs' own string before Docs used connect, so |
| 20 | // sessions minted then are still Home sessions now. Checks on a Home |
| 21 | // sign-in ask connect.IsHomeDerived, which also covers the native app's |
| 22 | // (connect.NativeMethod) and native-to-web sessions. |
| 23 | const homeAssertionMethod = connect.HomeMethod |
| 24 | |
| 25 | var ( |
| 26 | errIdentityRefused = errors.New("docs: identity refused") |
| 27 | errIdentityStorage = errors.New("docs: identity storage unavailable") |
| 28 | // errSessionEnded is a native or native-web session past its seven days |
| 29 | // (connect.Expired): refused like any identity, but ended rather than |
| 30 | // refused, so a non-GET says so in the session guard's own words. |
| 31 | errSessionEnded = fmt.Errorf("%w: session ended", errIdentityRefused) |
| 32 | ) |
| 33 | |
| 34 | // sessionEndedBody is what every session guard answers a non-GET whose |
| 35 | // session has ended: byte for byte rastrillo sessions.Require's refusal of |
| 36 | // a missing, unknown or revoked session ("signed out", and http.Error adds |
| 37 | // the newline). A wire contract, not copy: the native apps' Oficina ID |
| 38 | // transport (native/apple/Sources/DocsKit/DocsOficinaID.swift, |
| 39 | // DocsSessionWatch.signedOut) reads a 403 with exactly this body as an |
| 40 | // ended session and re-mints it, where any other 403 is a refusal of the |
| 41 | // request. native_contract_test.go pins it on every guard. |
| 42 | const sessionEndedBody = "signed out" |
| 43 | |
| 44 | // requestIdentity keeps the verified session separate from the local person |
| 45 | // and address that own documents and hold grants. |
| 46 | type requestIdentity struct { |
| 47 | Actor Actor |
| 48 | HomeSubject string |
| 49 | Session sessions.Session |
| 50 | } |
| 51 | type identityContextKey struct{} |
| 52 | |
| 53 | func currentIdentity(r *http.Request) (requestIdentity, bool) { |
| 54 | id, ok := r.Context().Value(identityContextKey{}).(requestIdentity) |
| 55 | return id, ok |
| 56 | } |
| 57 | |
| 58 | type identityResolver struct { |
| 59 | team *teamRuntime |
| 60 | store *Store |
| 61 | issuer string |
| 62 | // links resolves a Home subject: connect's account link (its binding |
| 63 | // checked against the person's current address), then in team mode the |
| 64 | // Home-only principal. Its errors are linkstore's and carry no identity |
| 65 | // values. It is the connect.Bridge. |
| 66 | links homeSubjects |
| 67 | } |
| 68 | |
| 69 | // homeSubjects is connect.Bridge's Resolve. |
| 70 | type homeSubjects interface { |
| 71 | Resolve(ctx context.Context, subject string) (connect.Person, error) |
| 72 | } |
| 73 | |
| 74 | // homePerson is links.Resolve as an identity error. |
| 75 | func (v identityResolver) homePerson(ctx context.Context, subject string) (connect.Person, error) { |
| 76 | if v.links == nil { |
| 77 | return connect.Person{}, errIdentityRefused |
| 78 | } |
| 79 | p, err := v.links.Resolve(ctx, subject) |
| 80 | switch { |
| 81 | case errors.Is(err, linkstore.ErrRefused): |
| 82 | return connect.Person{}, errIdentityRefused |
| 83 | case err != nil: |
| 84 | return connect.Person{}, errIdentityStorage |
| 85 | } |
| 86 | return p, nil |
| 87 | } |
| 88 | |
| 89 | func (v identityResolver) resolve(r *http.Request) (requestIdentity, error) { |
| 90 | session, ok := sessions.Current(r) |
| 91 | if !ok || session.Subject == "" || v.store == nil { |
| 92 | return requestIdentity{}, errIdentityRefused |
| 93 | } |
| 94 | if v.store.team != nil && v.team == nil { |
| 95 | return requestIdentity{}, errIdentityRefused |
| 96 | } |
| 97 | if connect.IsHomeDerived(session.Method) { |
| 98 | // A browser, native or native-web sign-in through Home. The two |
| 99 | // native kinds end seven days after they were minted, however |
| 100 | // recently used (connect.Expired); Docs resolves sessions itself, |
| 101 | // so it refuses what connect's ResolveSession would. |
| 102 | if connect.Expired(connect.Session{Subject: session.Subject, Method: session.Method, AuthTime: session.AuthTime, At: session.At}, time.Now()) { |
| 103 | return requestIdentity{}, errSessionEnded |
| 104 | } |
| 105 | person, err := v.homePerson(r.Context(), session.Subject) |
| 106 | if err != nil { |
| 107 | return requestIdentity{}, err |
| 108 | } |
| 109 | if v.team != nil { |
| 110 | p, err := v.team.principals.Person(r.Context(), person.ID) |
| 111 | if errors.Is(err, principalstore.ErrRefused) { |
| 112 | return requestIdentity{}, errIdentityRefused |
| 113 | } |
| 114 | if err != nil { |
| 115 | return requestIdentity{}, errIdentityStorage |
| 116 | } |
| 117 | return requestIdentity{Actor: Actor{PersonID: p.ID, VerifiedAddress: p.VerifiedAddress}, Session: session, HomeSubject: session.Subject}, nil |
| 118 | } |
| 119 | address := subjectOf(person.Label) |
| 120 | if person.ID <= 0 || address == "" { |
| 121 | return requestIdentity{}, errIdentityRefused |
| 122 | } |
| 123 | return requestIdentity{Actor: localActor(person.ID, address), Session: session}, nil |
| 124 | } |
| 125 | if v.team != nil && session.Method != "magiclink" && session.Method != "keymail" { |
| 126 | return requestIdentity{}, errIdentityRefused |
| 127 | } |
| 128 | // The local authentication plugin verified this address. Preserve its |
| 129 | // existing get-or-create behavior, including opt-in sample seeding. |
| 130 | person, err := v.store.EnsurePerson(r.Context(), session.Subject) |
| 131 | if err != nil { |
| 132 | return requestIdentity{}, errIdentityStorage |
| 133 | } |
| 134 | id := requestIdentity{Actor: localActor(person, session.Subject), Session: session} |
| 135 | if v.team != nil { |
| 136 | p, err := v.team.principals.Person(r.Context(), person) |
| 137 | if err != nil { |
| 138 | return requestIdentity{}, errIdentityStorage |
| 139 | } |
| 140 | if p.Kind != principalstore.Local { |
| 141 | return requestIdentity{}, errIdentityRefused |
| 142 | } |
| 143 | id.Actor = Actor{PersonID: p.ID, VerifiedAddress: p.VerifiedAddress} |
| 144 | if id.HomeSubject, err = v.linkedSubject(r.Context(), p.ID); err != nil { |
| 145 | return requestIdentity{}, err |
| 146 | } |
| 147 | } |
| 148 | return id, nil |
| 149 | } |
| 150 | |
| 151 | // linkedSubject is the Home subject a local person is linked to, for team |
| 152 | // standing, or "" for none. The link counts only if connect resolves it |
| 153 | // back to the same person: a link whose binding no longer matches the |
| 154 | // person's address signs nobody in, so it gives no standing either. |
| 155 | func (v identityResolver) linkedSubject(ctx context.Context, person int64) (string, error) { |
| 156 | var subject string |
| 157 | err := v.team.db.QueryRowContext(ctx, "SELECT subject FROM home_identity_links WHERE issuer=? AND person_id=?", v.team.bindings.Issuer, person).Scan(&subject) |
| 158 | if errors.Is(err, sql.ErrNoRows) { |
| 159 | return "", nil |
| 160 | } |
| 161 | if err != nil { |
| 162 | return "", errIdentityStorage |
| 163 | } |
| 164 | linked, err := v.homePerson(ctx, subject) |
| 165 | if errors.Is(err, errIdentityRefused) || (err == nil && linked.ID != person) { |
| 166 | return "", nil |
| 167 | } |
| 168 | if err != nil { |
| 169 | return "", err |
| 170 | } |
| 171 | return subject, nil |
| 172 | } |
| 173 | |
| 174 | // middleware belongs after RequireSession and before admission. A verified |
| 175 | // Home subject with no local link must never reach an app handler. |
| 176 | func (v identityResolver) middleware(signinPath string) func(http.Handler) http.Handler { |
| 177 | return func(next http.Handler) http.Handler { |
| 178 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 179 | id, err := v.resolve(r) |
| 180 | if err != nil { |
| 181 | if errors.Is(err, errIdentityStorage) { |
| 182 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 183 | } else { |
| 184 | refuseIdentity(w, r, signinPath, errors.Is(err, errSessionEnded)) |
| 185 | } |
| 186 | return |
| 187 | } |
| 188 | next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), identityContextKey{}, id))) |
| 189 | }) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | // refuseIdentity sends a page request to sign-in and answers anything else |
| 194 | // 403. A session that has ended says so as the session guard does |
| 195 | // (sessionEndedBody), so a native app re-mints it rather than reading a |
| 196 | // refused request: its outbox would otherwise hold the write as access |
| 197 | // lost. Any other refusal keeps the generic line. |
| 198 | func refuseIdentity(w http.ResponseWriter, r *http.Request, signinPath string, ended bool) { |
| 199 | if r.Method == http.MethodGet || r.Method == http.MethodHead { |
| 200 | http.Redirect(w, r, signinPath, http.StatusSeeOther) |
| 201 | return |
| 202 | } |
| 203 | body := rastrillo.T(r, "docs.error.generic") |
| 204 | if ended { |
| 205 | body = sessionEndedBody |
| 206 | } |
| 207 | http.Error(w, body, http.StatusForbidden) |
| 208 | } |
| 209 | |
| 210 | // requestActor supports standalone routes without the suite middleware too. |
| 211 | // The fallback resolver still refuses every Home session without a link. |
| 212 | func requestActor(r *http.Request, store *Store) (Actor, error) { |
| 213 | if id, ok := currentIdentity(r); ok { |
| 214 | return id.Actor, nil |
| 215 | } |
| 216 | if store.team != nil { |
| 217 | return Actor{}, errIdentityRefused |
| 218 | } |
| 219 | id, err := (identityResolver{store: store}).resolve(r) |
| 220 | return id.Actor, err |
| 221 | } |
| 222 | |
| 223 | // resolveHome is the agent identity boundary. Unlike browser resolution, this |
| 224 | // first integration admits only an existing linked local account. ResolveOn |
| 225 | // verifies the complete keyed binding on the supplied connection and never |
| 226 | // invokes addressless-person hooks outside a caller transaction. |
| 227 | func (v identityResolver) resolveHome(ctx context.Context, subject string) (requestIdentity, error) { |
| 228 | if v.store == nil { |
| 229 | return requestIdentity{}, errIdentityRefused |
| 230 | } |
| 231 | return v.resolveHomeOn(ctx, v.store.db.Statement.ConnPool, subject) |
| 232 | } |
| 233 | |
| 234 | func (v identityResolver) resolveHomeOn(ctx context.Context, q linkstore.Queryer, subject string) (requestIdentity, error) { |
| 235 | links, ok := v.links.(interface { |
| 236 | ResolveOn(context.Context, linkstore.Queryer, string) (connect.Person, error) |
| 237 | }) |
| 238 | if !ok || subject == "" || v.store == nil || v.store.team != nil && v.team == nil { |
| 239 | return requestIdentity{}, errIdentityRefused |
| 240 | } |
| 241 | p, err := links.ResolveOn(ctx, q, subject) |
| 242 | if errors.Is(err, linkstore.ErrRefused) { |
| 243 | return requestIdentity{}, errIdentityRefused |
| 244 | } |
| 245 | if err != nil { |
| 246 | return requestIdentity{}, errIdentityStorage |
| 247 | } |
| 248 | address := subjectOf(p.Label) |
| 249 | if p.ID <= 0 || address == "" { |
| 250 | return requestIdentity{}, errIdentityRefused |
| 251 | } |
| 252 | return requestIdentity{Actor: localActor(p.ID, address), HomeSubject: subject}, nil |
| 253 | } |
| 254 | |