| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "crypto/subtle" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "mime" |
| 9 | "net/http" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/home/handoff" |
| 13 | "amadan.net/oficina/home/internal/home/directorydata" |
| 14 | "amadan.net/rastrillo/rastrillo/sessions" |
| 15 | ) |
| 16 | |
| 17 | // The directory's half of native sign-in (§9). The directory is a consumer |
| 18 | // like any team instance: the app asks the credential origin for an |
| 19 | // assertion with aud = the directory, redeems it here for a directory |
| 20 | // session, and reads its teams with that session. Nothing here renders, sets |
| 21 | // a cookie, or answers a browser. |
| 22 | const ( |
| 23 | nativeExchangePath = "/native/oficina-id" |
| 24 | nativeTeamsPath = "/api/native/teams" |
| 25 | nativeDirectorySignout = "/native/signout" |
| 26 | noTeamsHelpPath = "/help/teams" |
| 27 | |
| 28 | // nativeSessionMethod marks a session minted for a native app. It lives |
| 29 | // seven days, absolute (§7); the app re-mints after a day and on a 401. |
| 30 | nativeSessionMethod = "home-assertion-native" |
| 31 | nativeSessionLife = 7 * day |
| 32 | ) |
| 33 | |
| 34 | // nativeTeamApps are the native apps; the list is filtered to them (§9). |
| 35 | var nativeTeamApps = map[string]bool{"calls": true, "docs": true, "sheets": true, "calendar": true, "memoria": true, "equipo": true, "base": true} |
| 36 | |
| 37 | // directoryNativeExchange is POST /native/oficina-id {assertion, verifier, |
| 38 | // target?, choice?}. It verifies the assertion against the pinned keys with |
| 39 | // the exact issuer and the directory as audience, recomputes the native |
| 40 | // nonce from the verifier, reserves the jti, and mints a seven-day directory |
| 41 | // session whose token goes back in the body, never in a cookie. |
| 42 | // |
| 43 | // The request and every answer are connect.Bridge.NativeExchange's, so one |
| 44 | // client speaks to the directory and to every team instance alike: JSON |
| 45 | // {"state": …}, ok / invalid / failed / unavailable. choice is accepted and |
| 46 | // ignored and target is echoed: the directory links nobody and allocates |
| 47 | // nothing, so a person ref is the whole answer, and the unknown and choose |
| 48 | // states never arise here. |
| 49 | func (a *App) directoryNativeExchange(w http.ResponseWriter, r *http.Request) { |
| 50 | answer := func(status int, state string) { nativeReply(w, status, map[string]string{"state": state}) } |
| 51 | if _, ok := r.Header["Origin"]; ok { |
| 52 | answer(http.StatusBadRequest, "invalid") |
| 53 | return |
| 54 | } |
| 55 | if _, ok := r.Header["Sec-Fetch-Site"]; ok { |
| 56 | answer(http.StatusBadRequest, "invalid") |
| 57 | return |
| 58 | } |
| 59 | media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 60 | if err != nil || media != "application/json" || r.URL.RawQuery != "" { |
| 61 | answer(http.StatusBadRequest, "invalid") |
| 62 | return |
| 63 | } |
| 64 | body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024)) |
| 65 | if err != nil { |
| 66 | answer(http.StatusBadRequest, "invalid") |
| 67 | return |
| 68 | } |
| 69 | var in struct { |
| 70 | Assertion string `json:"assertion"` |
| 71 | Verifier string `json:"verifier"` |
| 72 | Target string `json:"target,omitzero"` |
| 73 | Choice string `json:"choice,omitzero"` |
| 74 | } |
| 75 | if !decodeNative(body, &in) || in.Assertion == "" || (in.Choice != "" && in.Choice != "new") || (in.Target != "" && !handoff.SafePath(in.Target)) { |
| 76 | answer(http.StatusBadRequest, "invalid") |
| 77 | return |
| 78 | } |
| 79 | challenge, ok := handoff.NativeChallenge(in.Verifier) |
| 80 | if !ok { |
| 81 | answer(http.StatusBadRequest, "invalid") |
| 82 | return |
| 83 | } |
| 84 | nonce, _ := handoff.NativeNonce(challenge) |
| 85 | now := time.Now() |
| 86 | claims, err := a.handoffStore.Verify(in.Assertion, now) |
| 87 | if err != nil || subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(nonce)) != 1 || !ValidPersonRef(claims.Subject) { |
| 88 | answer(http.StatusUnauthorized, "failed") |
| 89 | return |
| 90 | } |
| 91 | if a.directorySigninAllowed(r.Context(), claims) != nil { |
| 92 | answer(http.StatusUnauthorized, "failed") |
| 93 | return |
| 94 | } |
| 95 | afterMarkCheck() |
| 96 | // The jti is reserved in handoff's own committed transaction, as |
| 97 | // connect's NativeExchange does; a reserved jti that then mints nothing |
| 98 | // costs the app one fresh assertion (spec §7, accepted non-atomicity). |
| 99 | if _, err = a.handoffStore.Reserve(r.Context(), in.Assertion, now); err != nil { |
| 100 | if errors.Is(err, handoff.ErrRefused) { |
| 101 | answer(http.StatusUnauthorized, "failed") |
| 102 | } else { |
| 103 | answer(http.StatusServiceUnavailable, "unavailable") |
| 104 | } |
| 105 | return |
| 106 | } |
| 107 | tx, err := a.db.Writer().BeginTx(r.Context(), nil) |
| 108 | if err != nil { |
| 109 | answer(http.StatusServiceUnavailable, "unavailable") |
| 110 | return |
| 111 | } |
| 112 | defer tx.Rollback() |
| 113 | // The mark again, inside the transaction that inserts the session: the |
| 114 | // directory's writer is one connection, so a receipt cannot commit |
| 115 | // between this check and the insert. The check above only saves a jti. |
| 116 | if before, err := signedOutBefore(r.Context(), tx, "home_directory_signed_out_all", claims.Subject, claims.IssuedAt); err != nil || before { |
| 117 | if err != nil { |
| 118 | answer(http.StatusServiceUnavailable, "unavailable") |
| 119 | } else { |
| 120 | answer(http.StatusUnauthorized, "failed") |
| 121 | } |
| 122 | return |
| 123 | } |
| 124 | token, hash, err := sessions.NewToken() |
| 125 | if err != nil { |
| 126 | answer(http.StatusServiceUnavailable, "unavailable") |
| 127 | return |
| 128 | } |
| 129 | expires := now.Unix() + nativeSessionLife |
| 130 | if _, err = tx.Exec("INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", |
| 131 | hash, claims.Subject, nativeSessionMethod, time.Unix(claims.AuthTime, 0).UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339), time.Unix(expires, 0).UTC().Format(time.RFC3339)); err != nil { |
| 132 | answer(http.StatusServiceUnavailable, "unavailable") |
| 133 | return |
| 134 | } |
| 135 | if tx.Commit() != nil { |
| 136 | answer(http.StatusServiceUnavailable, "unavailable") |
| 137 | return |
| 138 | } |
| 139 | reply := map[string]any{"state": "ok", "name": a.sessions.CookieName(), "value": token, "expires_at": expires} |
| 140 | if in.Target != "" { |
| 141 | reply["target"] = in.Target |
| 142 | } |
| 143 | nativeReply(w, http.StatusOK, reply) |
| 144 | } |
| 145 | |
| 146 | type nativeTeamApp struct { |
| 147 | App string `json:"app"` |
| 148 | Origin string `json:"origin"` |
| 149 | ConsumerID string `json:"consumer_id"` |
| 150 | } |
| 151 | type nativeTeam struct { |
| 152 | SQID string `json:"sqid"` |
| 153 | Label string `json:"label"` |
| 154 | Name string `json:"name"` |
| 155 | Role string `json:"role"` |
| 156 | Apps []nativeTeamApp `json:"apps"` |
| 157 | } |
| 158 | |
| 159 | // directoryNativeTeams is GET /api/native/teams: the person's teams with |
| 160 | // live instances of the seven native apps, from Store.AgentChoices. Zero |
| 161 | // teams is an empty list, never an error; the app then shows its help and |
| 162 | // may link noTeamsHelpPath. |
| 163 | func (a *App) directoryNativeTeams(w http.ResponseWriter, r *http.Request) { |
| 164 | if _, ok := r.Header["Origin"]; ok { |
| 165 | nativeFail(w, http.StatusForbidden, "browser") |
| 166 | return |
| 167 | } |
| 168 | if _, ok := r.Header["Sec-Fetch-Site"]; ok { |
| 169 | nativeFail(w, http.StatusForbidden, "browser") |
| 170 | return |
| 171 | } |
| 172 | s, ok := sessions.Current(r) |
| 173 | if !ok || s.Method != nativeSessionMethod { |
| 174 | nativeUnauthorized(w, "session") |
| 175 | return |
| 176 | } |
| 177 | choices, err := a.directory.store.AgentChoices(r.Context(), s.Subject) |
| 178 | if errors.Is(err, directorydata.ErrInvalid) { |
| 179 | nativeUnauthorized(w, "session") |
| 180 | return |
| 181 | } |
| 182 | if err != nil { |
| 183 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 184 | return |
| 185 | } |
| 186 | teams := []nativeTeam{} |
| 187 | for _, c := range choices { |
| 188 | if !nativeTeamApps[c.App] { |
| 189 | continue |
| 190 | } |
| 191 | if len(teams) == 0 || teams[len(teams)-1].SQID != c.SQID { |
| 192 | teams = append(teams, nativeTeam{SQID: c.SQID, Label: c.Label, Name: c.Name, Role: c.Role, Apps: []nativeTeamApp{}}) |
| 193 | } |
| 194 | last := &teams[len(teams)-1] |
| 195 | last.Apps = append(last.Apps, nativeTeamApp{App: c.App, Origin: c.Origin, ConsumerID: c.ConsumerID}) |
| 196 | } |
| 197 | nativeReply(w, http.StatusOK, teams) |
| 198 | } |
| 199 | |
| 200 | // directoryNativeSignout is POST /native/signout {}: the app's directory |
| 201 | // session ends (§10 step 3). Outside csrf.Protect, because a native call |
| 202 | // carries no origin evidence; it refuses any that a browser would send, and |
| 203 | // it can end only a native session. |
| 204 | func (a *App) directoryNativeSignout(w http.ResponseWriter, r *http.Request) { |
| 205 | body, ok := nativeIntake(w, r) |
| 206 | if !ok { |
| 207 | return |
| 208 | } |
| 209 | var in struct{} |
| 210 | if !decodeNative(body, &in) { |
| 211 | nativeFail(w, http.StatusBadRequest, "request") |
| 212 | return |
| 213 | } |
| 214 | if token := cookieValue(r, a.sessions.CookieName()); token != "" { |
| 215 | if _, err := a.db.Writer().ExecContext(r.Context(), "DELETE FROM sessions WHERE token_hash=? AND method=?", sessions.HashToken(token), nativeSessionMethod); err != nil { |
| 216 | nativeFail(w, http.StatusServiceUnavailable, "unavailable") |
| 217 | return |
| 218 | } |
| 219 | } |
| 220 | nativeReply(w, http.StatusOK, map[string]string{}) |
| 221 | } |
| 222 | |
| 223 | func (a *App) handleNoTeamsHelp(w http.ResponseWriter, r *http.Request) { |
| 224 | a.render(w, r, http.StatusOK, "directory_no_teams.html", nil) |
| 225 | } |
| 226 | |
| 227 | // nativeSessionsStayNative confines a home-assertion-native directory |
| 228 | // session to the routes a native app uses: the teams list and its own |
| 229 | // sign-out. On any other route its cookie is removed from the request |
| 230 | // before the session middleware runs, so a native session copied into a |
| 231 | // browser — or carried by a forged same-origin POST — is simply signed out: |
| 232 | // it sees the front page, passes no freshness check and makes no roster or |
| 233 | // operator write. Its auth_time is a sign-in's, possibly code-only, and the |
| 234 | // directory's browser routes trust auth_time for freshness. |
| 235 | func (a *App) nativeSessionsStayNative(next http.Handler) http.Handler { |
| 236 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 237 | name := a.sessions.CookieName() |
| 238 | var tokens []string |
| 239 | for _, c := range r.Cookies() { |
| 240 | if c.Name == name { |
| 241 | tokens = append(tokens, c.Value) |
| 242 | } |
| 243 | } |
| 244 | if len(tokens) == 0 || r.URL.Path == nativeTeamsPath || r.URL.Path == nativeDirectorySignout { |
| 245 | next.ServeHTTP(w, r) |
| 246 | return |
| 247 | } |
| 248 | // Every cookie of the session name is looked up, not just a lone |
| 249 | // one: the session middleware takes the first of several, so a |
| 250 | // native token hidden among duplicates must not get through. If any |
| 251 | // is native, all of that name go; otherwise the request is untouched |
| 252 | // and the existing ambiguous-session refusals still see it. |
| 253 | native := len(tokens) > 8 // more than that is not a browser; strip without looking |
| 254 | for _, token := range tokens[:min(len(tokens), 8)] { |
| 255 | var method string |
| 256 | err := a.db.Writer().QueryRowContext(r.Context(), "SELECT method FROM sessions WHERE token_hash=?", sessions.HashToken(token)).Scan(&method) |
| 257 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 258 | http.Error(w, "Directory unavailable", http.StatusServiceUnavailable) |
| 259 | return |
| 260 | } |
| 261 | native = native || method == nativeSessionMethod |
| 262 | } |
| 263 | if !native { |
| 264 | next.ServeHTTP(w, r) |
| 265 | return |
| 266 | } |
| 267 | stripped := r.Clone(r.Context()) |
| 268 | stripped.Header.Del("Cookie") |
| 269 | for _, c := range r.Cookies() { |
| 270 | if c.Name != name { |
| 271 | stripped.AddCookie(c) |
| 272 | } |
| 273 | } |
| 274 | next.ServeHTTP(w, stripped) |
| 275 | }) |
| 276 | } |
| 277 | |