| 1 | package calls |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | "strconv" |
| 11 | |
| 12 | "amadan.net/oficina/home/connect" |
| 13 | "amadan.net/oficina/home/connect/linkstore" |
| 14 | "amadan.net/rastrillo/rastrillo/csrf" |
| 15 | "amadan.net/rastrillo/rastrillo/migrate" |
| 16 | "amadan.net/rastrillo/rastrillo/sessions" |
| 17 | ) |
| 18 | |
| 19 | var errHomeIdentity = errors.New("calls: Home identity refused") |
| 20 | |
| 21 | // errHomeRemoved is the definite subset of errHomeIdentity: the Home |
| 22 | // link is refused, the person row is gone, or the person is no longer a |
| 23 | // member. A database that could not be read is never either: it is |
| 24 | // errHomeUnavailable outside team mode and errTeamUnavailable in it, a |
| 25 | // retryable 503 that never ends a session. |
| 26 | var errHomeRemoved = fmt.Errorf("%w: removed", errHomeIdentity) |
| 27 | |
| 28 | // errHomeUnavailable is a Home session's identity storage that could not |
| 29 | // be read now, outside team mode (team mode answers errTeamUnavailable): |
| 30 | // it says nothing about who the session is, so requirePerson answers a |
| 31 | // retryable 503 for it, never errHomeIdentity's 404, which the sign-in |
| 32 | // door's admission probe would read as a refusal. |
| 33 | var errHomeUnavailable = errors.New("calls: Home identity storage unavailable") |
| 34 | |
| 35 | // homeUnavailable is the answer to errHomeUnavailable, wherever a |
| 36 | // handler meets it: a no-store 503, the page for a page request and plain |
| 37 | // text for anything else (ErrorPage decides). |
| 38 | func (a *app) homeUnavailable(w http.ResponseWriter, r *http.Request) { |
| 39 | w.Header().Set("Cache-Control", "no-store") |
| 40 | a.ErrorPage(w, r, http.StatusServiceUnavailable, "") |
| 41 | } |
| 42 | |
| 43 | type homeIntegration struct { |
| 44 | bridge *connect.Bridge |
| 45 | routes *connect.Routes |
| 46 | sessions *sessions.Sessions |
| 47 | } |
| 48 | |
| 49 | func (a *app) wireHome() error { |
| 50 | h := a.cfg.home |
| 51 | if h == nil { |
| 52 | return nil |
| 53 | } |
| 54 | if _, err := migrate.Apply(context.Background(), a.db, homeSchema()); err != nil { |
| 55 | return errHomeIdentity |
| 56 | } |
| 57 | sess, err := sessions.New(sessions.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, SigninPath: signinPath, Logger: a.logger}) |
| 58 | if err != nil || sess.CookieName() != a.auth.SessionCookie() { |
| 59 | return errHomeIdentity |
| 60 | } |
| 61 | read := func(r *http.Request) (*connect.Session, error) { |
| 62 | s, ok := sess.From(r) |
| 63 | if !ok { |
| 64 | return nil, nil |
| 65 | } |
| 66 | return &connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, nil |
| 67 | } |
| 68 | teamOn := a.cfg.team != nil |
| 69 | cfg := connect.Config{DB: a.db.Writer(), Origin: a.cfg.Origin, Issuer: h.Issuer, ConsumerID: h.ConsumerID, Namespace: homeNamespace, SessionCookie: sess.CookieName(), Keys: h.Keys, DEK: h.DEK, ReadSession: read, |
| 70 | MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error { |
| 71 | if err := sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime}); err != nil { |
| 72 | return err |
| 73 | } |
| 74 | // The smart door remembers Oficina ID, for an admitted session |
| 75 | // only (signin_admission.go's rememberOficina). It never fails |
| 76 | // the sign-in. |
| 77 | a.rememberOficina(w, r) |
| 78 | return nil |
| 79 | }, |
| 80 | LookupLocalSession: func(ctx context.Context, s connect.Session) (connect.Person, error) { |
| 81 | if s.Method != "magiclink" && s.Method != "keymail" { |
| 82 | return connect.Person{}, errHomeIdentity |
| 83 | } |
| 84 | p, err := a.store.existingHomePerson(ctx, s.Subject) |
| 85 | if err != nil { |
| 86 | return connect.Person{}, errHomeIdentity |
| 87 | } |
| 88 | // Team mode: the allowlist is the local door, and a local |
| 89 | // account it admits may link (team_access.go's linkable); |
| 90 | // standing is the roster's, asked on every request. |
| 91 | if teamOn && !a.allowNow().allows(p.Email) { |
| 92 | return connect.Person{}, errHomeIdentity |
| 93 | } |
| 94 | if !teamOn && !a.isMember(p) { |
| 95 | return connect.Person{}, errHomeIdentity |
| 96 | } |
| 97 | return connect.Person{ID: p.ID, Label: p.Email}, nil |
| 98 | }, |
| 99 | LookupPerson: func(ctx context.Context, q linkstore.Queryer, id int64) (string, error) { |
| 100 | p, err := a.store.homePersonByID(ctx, q, id) |
| 101 | if err != nil { |
| 102 | return "", err |
| 103 | } |
| 104 | // Team mode: a link names who somebody is, not whether they |
| 105 | // may enter. The roster decides that on every request |
| 106 | // (team_access.go), so a linked person needs no place on |
| 107 | // CALLS_ALLOWED_ADDRESSES to resolve. |
| 108 | if !teamOn && !a.isMember(p) { |
| 109 | return "", sql.ErrNoRows |
| 110 | } |
| 111 | return p.Email, nil |
| 112 | }, Render: a.renderHome} |
| 113 | if teamOn { |
| 114 | // Team mode only: with all three hooks nil connect is exactly what |
| 115 | // it was, and refuses a Home subject with no link as "unknown" |
| 116 | // (team_home_only.go). With them, a roster Member with no account |
| 117 | // here is asked to choose (connect.ChoosePath); connect.New |
| 118 | // refuses HomeOnly or Unlinked without Admit. |
| 119 | cfg.Admit, cfg.HomeOnly, cfg.Unlinked = a.teamAdmit, a.teamHomeOnly(a.db.Writer()), a.teamUnlinked(a.db.Writer()) |
| 120 | } |
| 121 | b, err := connect.New(cfg) |
| 122 | if err != nil { |
| 123 | return errHomeIdentity |
| 124 | } |
| 125 | // LocalSignin is the door connect's SigninDoor and SigninLocal hand to |
| 126 | // (signin.go); ForgetPath puts "Forget me on this device" on the |
| 127 | // signed-out page. A local sign-in lands on /continue, which takes a |
| 128 | // pending meeting join first and then the page the sign-in began from |
| 129 | // (signin_return.go). |
| 130 | routes, err := connect.NewRoutes(b, connect.RoutesConfig{LocalLandingPath: "/continue", Namespace: homeNamespace, Origin: a.cfg.Origin, Issuer: h.Issuer, FormPolicy: homeFormPolicy(h.Issuer), SessionCookie: sess.CookieName(), DEK: h.DEK, ReadSession: read, SignOut: sess.SignOut, LocalSignin: a.signinDoor, Protect: csrf.Protect(a.cfg.Origin), Render: a.renderHome, ForgetPath: signinForgetPath}) |
| 131 | if err != nil { |
| 132 | return errHomeIdentity |
| 133 | } |
| 134 | a.home = &homeIntegration{b, routes, sess} |
| 135 | return nil |
| 136 | } |
| 137 | |
| 138 | func (a *app) personForSession(ctx context.Context, s sessions.Session) (Person, error) { |
| 139 | if s.Method == "guest" { |
| 140 | id, err := strconv.ParseInt(s.Subject, 10, 64) |
| 141 | if err != nil { |
| 142 | return Person{}, errHomeIdentity |
| 143 | } |
| 144 | p, ok, err := a.store.personByID(ctx, id) |
| 145 | if err != nil || !ok || !p.Anonymous { |
| 146 | return Person{}, errHomeIdentity |
| 147 | } |
| 148 | return p, nil |
| 149 | } |
| 150 | if s.Method == connect.HomeMethod { |
| 151 | if a.home == nil { |
| 152 | return Person{}, errHomeIdentity |
| 153 | } |
| 154 | linked, err := a.home.bridge.Resolve(ctx, s.Subject) |
| 155 | if errors.Is(err, linkstore.ErrRefused) { |
| 156 | return Person{}, errHomeRemoved |
| 157 | } |
| 158 | if err != nil { |
| 159 | if a.team != nil { |
| 160 | // Storage, not a refusal: a retryable 503, never a |
| 161 | // sign-out (team_access.go). |
| 162 | return Person{}, errTeamUnavailable |
| 163 | } |
| 164 | return Person{}, errHomeUnavailable |
| 165 | } |
| 166 | p, err := a.store.homePersonByID(ctx, a.db.Writer(), linked.ID) |
| 167 | if errors.Is(err, sql.ErrNoRows) { |
| 168 | return Person{}, errHomeRemoved |
| 169 | } |
| 170 | if err != nil { |
| 171 | if a.team != nil { |
| 172 | return Person{}, errTeamUnavailable |
| 173 | } |
| 174 | return Person{}, errHomeUnavailable |
| 175 | } |
| 176 | if a.team != nil { |
| 177 | // Identity only: who this subject is here. Whether they may |
| 178 | // enter is the roster's, asked by the caller. |
| 179 | return p, nil |
| 180 | } |
| 181 | if !a.isMember(p) { |
| 182 | return Person{}, errHomeRemoved |
| 183 | } |
| 184 | return p, nil |
| 185 | } |
| 186 | if s.Method != "magiclink" && s.Method != "keymail" { |
| 187 | return Person{}, errHomeIdentity |
| 188 | } |
| 189 | return a.store.ensurePerson(ctx, s.Subject) |
| 190 | } |
| 191 | |
| 192 | // endRemovedSession ends this request's session and sends a page request |
| 193 | // to the sign-in door with the reason (the removal, in the door's |
| 194 | // app-problem slot); anything else gets the 403 a fetch reads as signed |
| 195 | // out (room.js's readRefusal). |
| 196 | // |
| 197 | // Under the door's admission probe (signin_admission.go) it only answers: |
| 198 | // the probe decides what to end, and must not revoke a session it was |
| 199 | // merely asked about, such as the one MintHomeSession has just stored, |
| 200 | // which then lands on its first page and is told why there. |
| 201 | func (a *app) endRemovedSession(w http.ResponseWriter, r *http.Request) { |
| 202 | if !probing(r.Context()) { |
| 203 | a.nativeAuth.sessions.SignOut(w, r) |
| 204 | } |
| 205 | if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| 206 | plainError(w, http.StatusForbidden) |
| 207 | return |
| 208 | } |
| 209 | w.Header().Set("Cache-Control", "no-store") |
| 210 | http.Redirect(w, r, a.signinAgain(r, removedQuery), http.StatusSeeOther) |
| 211 | } |
| 212 | |
| 213 | // removedQuery is endRemovedSession's problem on the door: the removal. |
| 214 | // The door's admission probe reads a redirect carrying it as "removed". |
| 215 | const removedQuery = "err=removed" |
| 216 | |
| 217 | // renderHome is connect's Render: the account-connection pages, the member |
| 218 | // choice, and the signed-out page. |
| 219 | func (a *app) renderHome(w http.ResponseWriter, r *http.Request, state, label string, status int) { |
| 220 | if state == "signedout" { |
| 221 | // Where Sign out lands: the Oficina door, in the door's words, |
| 222 | // with Forget (signin.go's renderSignedOut). |
| 223 | a.renderSignedOut(w, r, status) |
| 224 | return |
| 225 | } |
| 226 | view := homeLinkView{PageData: connect.PageFor(r, state, label)} |
| 227 | if state == "choose" { |
| 228 | // A roster member with no account here yet (Home spec |
| 229 | // 2026-11-14-oficina-id-native.md §8): connect an existing email |
| 230 | // account, or continue with Oficina ID as someone new. connect's |
| 231 | // Page knows no "choose", so the page is built here, in connect's |
| 232 | // own English. |
| 233 | if form, ok := connect.ChoiceFor(r); ok { |
| 234 | view.Title, view.Body = connect.English["choose_title"], connect.English["choose_body"] |
| 235 | view.Choice = &homeChoice{Action: form.Action, Token: form.Token, |
| 236 | ConnectLabel: connect.English["choose_connect_action"], NewLabel: connect.English["choose_new_action"]} |
| 237 | } else { |
| 238 | // No live choice to offer: "failed", with the way on to |
| 239 | // connecting an account, as Docs, Sheets and Calendar do. |
| 240 | view.PageData = connect.PageFor(r, "failed", label) |
| 241 | view.Action, view.ActionLabel = "/account/home", connect.English["menu_action"] |
| 242 | status = http.StatusForbidden |
| 243 | } |
| 244 | } |
| 245 | var body bytes.Buffer |
| 246 | if err := pages["home"].ExecuteTemplate(&body, "layout", a.page(r, titled(view.Title), map[string]any{"Home": view})); err != nil { |
| 247 | a.ErrorPage(w, r, 500, "") |
| 248 | return |
| 249 | } |
| 250 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 251 | w.Header().Set("Cache-Control", "no-store") |
| 252 | w.WriteHeader(status) |
| 253 | _, _ = w.Write(body.Bytes()) |
| 254 | } |
| 255 | |
| 256 | // homeLinkView is the account-connection pages' data: connect's page, or |
| 257 | // the member choice's two buttons when Choice is set. Both buttons POST |
| 258 | // connect.ChoosePath with the form token, inside the app-wide CSRF check. |
| 259 | type homeLinkView struct { |
| 260 | connect.PageData |
| 261 | Choice *homeChoice |
| 262 | } |
| 263 | |
| 264 | type homeChoice struct { |
| 265 | Action, Token, ConnectLabel, NewLabel string |
| 266 | } |
| 267 | |
| 268 | func (a *app) showHomeConnection(r *http.Request) bool { |
| 269 | s, ok := sessions.Current(r) |
| 270 | return a.home != nil && ok && (s.Method == "magiclink" || s.Method == "keymail") |
| 271 | } |
| 272 | |