| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "strings" |
| 8 | |
| 9 | "amadan.net/oficina/home/connect" |
| 10 | "amadan.net/oficina/home/roster" |
| 11 | "amadan.net/oficina/home/teammode" |
| 12 | "amadan.net/rastrillo/rastrillo" |
| 13 | "gorm.io/gorm" |
| 14 | ) |
| 15 | |
| 16 | type accessContextKey struct{} |
| 17 | |
| 18 | // requestAccess is one request's standing (teammode.Access: Member, |
| 19 | // NotMember or Unknown, the lease re-checked whenever it is asked and |
| 20 | // Unknown latched) and the actor it was decided for. |
| 21 | type requestAccess struct { |
| 22 | extraCheck func(context.Context) error |
| 23 | delegationCheck func(context.Context) error |
| 24 | agentList bool |
| 25 | *teammode.Access |
| 26 | responseStore *Store |
| 27 | responseDocs map[int64]permission |
| 28 | runtime *teamRuntime |
| 29 | actor Actor |
| 30 | // partialNotice: this response renders the partial notice, so a list |
| 31 | // built under Unknown may be empty (acceptPartial). |
| 32 | partialNotice bool |
| 33 | } |
| 34 | type permission uint8 |
| 35 | |
| 36 | const ( |
| 37 | permissionRead permission = iota |
| 38 | permissionWrite |
| 39 | permissionOwner |
| 40 | ) |
| 41 | |
| 42 | var errTeamNotMember = teammode.ErrNotMember |
| 43 | |
| 44 | func sameActor(a, b Actor) bool { |
| 45 | if a.PersonID != b.PersonID || (a.VerifiedAddress == nil) != (b.VerifiedAddress == nil) { |
| 46 | return false |
| 47 | } |
| 48 | return a.VerifiedAddress == nil || *a.VerifiedAddress == *b.VerifiedAddress |
| 49 | } |
| 50 | func (a *requestAccess) state() roster.State { |
| 51 | if a == nil { |
| 52 | return roster.Unknown |
| 53 | } |
| 54 | return a.Access.State() |
| 55 | } |
| 56 | func (s *Store) access(ctx context.Context, actor Actor) (*requestAccess, bool) { |
| 57 | a, ok := ctx.Value(accessContextKey{}).(*requestAccess) |
| 58 | return a, ok && a != nil && a.runtime == s.team && sameActor(a.actor, actor) |
| 59 | } |
| 60 | |
| 61 | // withAccess carries a request's standing to the store: Docs' own key, for |
| 62 | // permissionScope and the emission checks, and teammode's, so Guard is |
| 63 | // handed the same latched Access rather than Unknown. |
| 64 | func withAccess(ctx context.Context, a *requestAccess) context.Context { |
| 65 | ctx = context.WithValue(ctx, accessContextKey{}, a) |
| 66 | if a != nil { |
| 67 | ctx = teammode.WithAccess(ctx, a.Access) |
| 68 | } |
| 69 | return ctx |
| 70 | } |
| 71 | func (t *teamRuntime) resolveAccess(ctx context.Context, id requestIdentity) *requestAccess { |
| 72 | return &requestAccess{Access: t.cache.Access(ctx, id.HomeSubject), runtime: t, actor: id.Actor} |
| 73 | } |
| 74 | func (t *teamRuntime) admission(next http.Handler) http.Handler { |
| 75 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 76 | id, ok := currentIdentity(r) |
| 77 | if !ok { |
| 78 | http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable) |
| 79 | return |
| 80 | } |
| 81 | a := t.resolveAccess(r.Context(), id) |
| 82 | next.ServeHTTP(w, r.WithContext(withAccess(r.Context(), a))) |
| 83 | }) |
| 84 | } |
| 85 | |
| 86 | // permissionScope is also usable under the SQLite writer. It never refreshes |
| 87 | // the roster, and checks a lease without waiting for a cache publisher. |
| 88 | // |
| 89 | // It is the one read predicate (spec §8.2.1, §8.2.2): ownership, an |
| 90 | // individual grant, and for reading only the team rung. A link is never one |
| 91 | // of its clauses — links are a separate table this never reads — so a |
| 92 | // link-shared document reaches nobody here by being link-shared. |
| 93 | // |
| 94 | // The team rung is read by an admitted member: in team mode a roster Member |
| 95 | // under the request's own lease (the same standing ownership needs), and in |
| 96 | // lone shape an address on the configured allowlist (Store.members). A guest |
| 97 | // admitted only by a grant is not a member. The rung needs no person row: |
| 98 | // S2 asks for members who have never opened Docs, and their first sign-in |
| 99 | // would show them the team's documents, so the answer is the same now. |
| 100 | // Ownership and every write still need a person. |
| 101 | func (s *Store) permissionScope(ctx context.Context, g *gorm.DB, actor Actor, p permission) *gorm.DB { |
| 102 | member := s.team == nil |
| 103 | if s.team != nil { |
| 104 | a, ok := s.access(ctx, actor) |
| 105 | if !ok { |
| 106 | return g.Where("1 = 0") |
| 107 | } |
| 108 | member = a.state() == roster.Member |
| 109 | } |
| 110 | if actor.PersonID <= 0 && p != permissionRead { |
| 111 | return g.Where("1 = 0") |
| 112 | } |
| 113 | owner := member && actor.PersonID > 0 |
| 114 | if p == permissionOwner { |
| 115 | if !owner { |
| 116 | return g.Where("1 = 0") |
| 117 | } |
| 118 | return owned(g, actor.PersonID) |
| 119 | } |
| 120 | grant := actor.VerifiedAddress != nil && *actor.VerifiedAddress != "" |
| 121 | team := p == permissionRead && s.teamReader(actor, member) |
| 122 | if !owner && !grant && !team { |
| 123 | return g.Where("1 = 0") |
| 124 | } |
| 125 | var clauses []string |
| 126 | args := []any{} |
| 127 | if owner { |
| 128 | clauses = append(clauses, "documents.owner_id = ?") |
| 129 | args = append(args, actor.PersonID) |
| 130 | } |
| 131 | if grant { |
| 132 | clause := "EXISTS (SELECT 1 FROM grants WHERE grants.doc_id = documents.id AND grants.subject = ?" |
| 133 | args = append(args, subjectOf(*actor.VerifiedAddress)) |
| 134 | if p == permissionWrite { |
| 135 | clause += " AND grants.role = ?" |
| 136 | args = append(args, RoleWriter) |
| 137 | } |
| 138 | clauses = append(clauses, clause+")") |
| 139 | } |
| 140 | if team { |
| 141 | clauses = append(clauses, "documents.visibility = ?") |
| 142 | args = append(args, VisibilityTeam) |
| 143 | } |
| 144 | return g.Where("documents.owner_id > 0 AND ("+strings.Join(clauses, " OR ")+")", args...) |
| 145 | } |
| 146 | |
| 147 | // teamReader is whether actor reads the team rung: member is the team-mode |
| 148 | // standing permissionScope already read (a Member under a current lease); |
| 149 | // in lone shape it is an address on the configured allowlist. A Store with |
| 150 | // no members predicate (one built without an allowlist) has no team readers |
| 151 | // in lone shape: the rung fails closed. |
| 152 | func (s *Store) teamReader(actor Actor, member bool) bool { |
| 153 | if s.team != nil { |
| 154 | return member |
| 155 | } |
| 156 | return actor.VerifiedAddress != nil && *actor.VerifiedAddress != "" && s.members != nil && s.members(*actor.VerifiedAddress) |
| 157 | } |
| 158 | func (s *Store) permissionError(ctx context.Context, actor Actor, err error) error { |
| 159 | if s.team == nil || err == nil { |
| 160 | return err |
| 161 | } |
| 162 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 163 | return errTeamUnavailable |
| 164 | } |
| 165 | a, ok := s.access(ctx, actor) |
| 166 | if !ok || a.state() == roster.Unknown { |
| 167 | return errTeamUnavailable |
| 168 | } |
| 169 | return gorm.ErrRecordNotFound |
| 170 | } |
| 171 | func (s *Store) requireMember(ctx context.Context, actor Actor) error { |
| 172 | if s.team == nil { |
| 173 | return nil |
| 174 | } |
| 175 | a, ok := s.access(ctx, actor) |
| 176 | if !ok { |
| 177 | return errTeamUnavailable |
| 178 | } |
| 179 | return teammode.RequireMember(a.state()) |
| 180 | } |
| 181 | |
| 182 | func (s *Store) ownerActor(ctx context.Context, owner int64) Actor { |
| 183 | if s.team == nil { |
| 184 | return Actor{PersonID: owner} |
| 185 | } |
| 186 | a, ok := ctx.Value(accessContextKey{}).(*requestAccess) |
| 187 | if !ok || a == nil || a.actor.PersonID != owner { |
| 188 | return Actor{PersonID: owner} |
| 189 | } |
| 190 | return a.actor |
| 191 | } |
| 192 | |
| 193 | func (s *Store) checkPermission(ctx context.Context, db *gorm.DB, actor Actor, docID int64, p permission) error { |
| 194 | var doc Document |
| 195 | err := s.permissionScope(ctx, db, actor, p).Where("documents.id = ? AND documents.deleted_at IS NULL", docID).First(&doc).Error |
| 196 | err = s.permissionError(ctx, actor, err) |
| 197 | if p == permissionWrite && errors.Is(err, gorm.ErrRecordNotFound) { |
| 198 | return ErrNotWritable |
| 199 | } |
| 200 | return err |
| 201 | } |
| 202 | func (s *Store) snapshotPermission(ctx context.Context, db *gorm.DB, docID int64) error { |
| 203 | if s.team == nil { |
| 204 | return nil |
| 205 | } |
| 206 | a, ok := ctx.Value(accessContextKey{}).(*requestAccess) |
| 207 | if !ok || a == nil { |
| 208 | return errTeamUnavailable |
| 209 | } |
| 210 | return s.checkPermission(ctx, db, a.actor, docID, permissionWrite) |
| 211 | } |
| 212 | |
| 213 | // ownerMutation authorizes, mutates and authorizes again inside one writer |
| 214 | // transaction, so it commits only if the standing that admitted it still |
| 215 | // holds. Guard is handed the request's standing (admission carries its |
| 216 | // Access with withAccess), and the rule, in permissionScope, reads that |
| 217 | // same latched Access matched to the actor; with team mode off it is |
| 218 | // ownership alone. |
| 219 | func (s *Store) ownerMutation(ctx context.Context, owner, docID int64, mutate func(*gorm.DB) error) error { |
| 220 | // Grants and visibility change who may read: no warm handle (and its |
| 221 | // decrypted state) outlives that (warm.go, rule 6). |
| 222 | defer s.warm.drop(ctx, docID) |
| 223 | actor := s.ownerActor(ctx, owner) |
| 224 | return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 225 | authorize := func(roster.State) error { return s.checkPermission(ctx, tx, actor, docID, permissionOwner) } |
| 226 | return teammode.Guard(ctx, authorize, func() error { |
| 227 | if err := mutate(tx); err != nil { |
| 228 | return s.permissionError(ctx, actor, err) |
| 229 | } |
| 230 | return nil |
| 231 | }) |
| 232 | }) |
| 233 | } |
| 234 | |
| 235 | func (h *handlers) internalFailureStatus() int { |
| 236 | if h.store.team != nil { |
| 237 | return http.StatusServiceUnavailable |
| 238 | } |
| 239 | return http.StatusInternalServerError |
| 240 | } |
| 241 | func (h *handlers) requireMemberRequest(w http.ResponseWriter, r *http.Request, item bool) bool { |
| 242 | if h.store.team == nil { |
| 243 | if h.member(r) { |
| 244 | return true |
| 245 | } |
| 246 | // A route about one document answers a guest as one about a |
| 247 | // document they cannot reach: 404, never 403, as team mode below |
| 248 | // always has (Astra, 2026-11-01). Create, which names no document, |
| 249 | // stays 403. |
| 250 | if item { |
| 251 | h.fail(w, r, http.StatusNotFound, failDocument) |
| 252 | } else { |
| 253 | h.fail(w, r, http.StatusForbidden, failStatus) |
| 254 | } |
| 255 | return false |
| 256 | } |
| 257 | actor, e := h.actor(r) |
| 258 | if e == nil { |
| 259 | e = h.store.requireMember(r.Context(), actor) |
| 260 | } |
| 261 | if e == nil { |
| 262 | return true |
| 263 | } |
| 264 | code, kind := http.StatusServiceUnavailable, failStatus |
| 265 | if errors.Is(e, errTeamNotMember) { |
| 266 | code = http.StatusForbidden |
| 267 | if item { |
| 268 | code, kind = http.StatusNotFound, failDocument |
| 269 | } |
| 270 | } |
| 271 | h.fail(w, r, code, kind) |
| 272 | return false |
| 273 | } |
| 274 | |
| 275 | // acceptPartial lets a list built under Unknown be empty, for a response |
| 276 | // that renders the partial notice: an empty partial list, not a 503 (Paul's |
| 277 | // ruling, 2026-10-28). A list nobody marks (the dashboard feed, the native |
| 278 | // list) keeps refusing an empty Unknown list as unavailable. |
| 279 | func (h *handlers) acceptPartial(r *http.Request) { |
| 280 | if a, ok := r.Context().Value(accessContextKey{}).(*requestAccess); ok && a != nil && a.runtime == h.store.team { |
| 281 | a.partialNotice = true |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // partialCatalog is the notice for a list built under Unknown: the person's |
| 286 | // shares, without the team rung (Paul's ruling, 2026-10-28). Ask it after |
| 287 | // the list is built, from the same Access, so a lease that lapsed while |
| 288 | // listing marks the page partial. NotMember is never partial. |
| 289 | func (h *handlers) partialCatalog(r *http.Request) string { |
| 290 | if h.store.team == nil { |
| 291 | return "" |
| 292 | } |
| 293 | a, ok := r.Context().Value(accessContextKey{}).(*requestAccess) |
| 294 | if !ok || a == nil || a.runtime != h.store.team || a.Partial() { |
| 295 | return rastrillo.T(r, "docs.team.partial") |
| 296 | } |
| 297 | return "" |
| 298 | } |
| 299 | |
| 300 | // The account group contains only local reauthentication and explicit linking. |
| 301 | // A known addressless Home account must be able to start that local gesture. |
| 302 | func requireTeamAccountAdmission(list allowlist) func(http.Handler) http.Handler { |
| 303 | return func(next http.Handler) http.Handler { |
| 304 | local := requireAdmission(list, "/signin/local")(next) |
| 305 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 306 | id, ok := currentIdentity(r) |
| 307 | if ok && id.Actor.VerifiedAddress == nil && connect.IsHomeDerived(id.Session.Method) { |
| 308 | next.ServeHTTP(w, r) |
| 309 | return |
| 310 | } |
| 311 | local.ServeHTTP(w, r) |
| 312 | }) |
| 313 | } |
| 314 | } |
| 315 | |