| 1 | package sheets |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/sheets/internal/sheets/store" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "strings" |
| 8 | |
| 9 | "gorm.io/gorm" |
| 10 | "gorm.io/gorm/clause" |
| 11 | ) |
| 12 | |
| 13 | // errNoAccess is what every read answers when the viewer may not see a |
| 14 | // sheet. |
| 15 | // |
| 16 | // Callers turn it into a 404, never a 403 (AGENTS.md). A 403 confirms |
| 17 | // the row exists, which is a fact about somebody else's data — and on |
| 18 | // an instance where guests hold single-sheet grants, the set of ids |
| 19 | // that 403 is a map of the team's sheets. |
| 20 | var errNoAccess = errors.New("sheets: no grant") |
| 21 | |
| 22 | // roleFor returns a member's effective role on a sheet, and whether |
| 23 | // they have any access at all. |
| 24 | // |
| 25 | // Two sources, in order: |
| 26 | // |
| 27 | // 1. An explicit Grant row. This is the authority for everyone, and |
| 28 | // the only source for a guest. |
| 29 | // 2. Team standing. An owner or member of the team can reach every |
| 30 | // sheet on the instance — that is what "one instance per team" |
| 31 | // means, and it is why the previous instance-wide list was right |
| 32 | // for a single-team instance and wrong the moment guests existed. |
| 33 | // |
| 34 | // A guest gets NOTHING from step 2. That is the whole distinction in |
| 35 | // §8.2: a guest sees exactly the sheets granted to them. |
| 36 | func (a *App) roleFor(sheetID uint64, m Member) (SheetRole, bool) { |
| 37 | role, ok := a.grantOrTeamRole(sheetID, m) |
| 38 | if ok && role != SheetOwner && a.orphanedForRosterOwner(sheetID, m) { |
| 39 | // Team mode: a roster owner holds every sheet nobody live owns |
| 40 | // (team_owner.go; Paul, 2026-10-28). |
| 41 | return SheetOwner, true |
| 42 | } |
| 43 | return role, ok |
| 44 | } |
| 45 | |
| 46 | // grantOrTeamRole is roleFor's two sources, before team mode's |
| 47 | // roster-owner rule. |
| 48 | func (a *App) grantOrTeamRole(sheetID uint64, m Member) (SheetRole, bool) { |
| 49 | if a.db == nil { |
| 50 | return "", false |
| 51 | } |
| 52 | // FIRST, covering both sources below. This check used to sit in the |
| 53 | // team-standing branch alone, which made an explicit Grant row a |
| 54 | // way round it: a grant holder kept their role on a soft-deleted |
| 55 | // sheet, and — once import existed — on one still being filled. |
| 56 | // openTab and the stream gate on roleFor and nothing else, so that |
| 57 | // was read and WRITE access to a sheet no list would show, for the |
| 58 | // one person every import gives an owner grant to. |
| 59 | if !a.sheetExists(sheetID) { |
| 60 | return "", false |
| 61 | } |
| 62 | var g Grant |
| 63 | err := a.db.Where("sheet_id = ? AND member_id = ?", sheetID, m.ID).First(&g).Error |
| 64 | if err == nil && a.ownGrantIgnored(g, m) { |
| 65 | // Team mode, and the creator's own grant on a sheet whose creator |
| 66 | // the roster no longer says is on the team (team_access.go). |
| 67 | return "", false |
| 68 | } |
| 69 | if err == nil { |
| 70 | if role := SheetRole(g.Role); role.Valid() { |
| 71 | return role, true |
| 72 | } |
| 73 | // A row whose role this build does not recognise grants |
| 74 | // nothing. Falling through to team standing would be worse: it |
| 75 | // would silently upgrade an unreadable grant to full access. |
| 76 | return "", false |
| 77 | } |
| 78 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 79 | return "", false |
| 80 | } |
| 81 | |
| 82 | switch a.teamRole(m) { |
| 83 | case TeamOwner, TeamMember: |
| 84 | // Team standing reaches every sheet, as an editor. Not as |
| 85 | // owner: sheet ownership is about who may change sharing, and |
| 86 | // handing that to every colleague by default makes the grant |
| 87 | // table decorative. |
| 88 | // |
| 89 | // The sheet is already known to exist — that is checked at the |
| 90 | // top, for both sources. It was checked here instead, once, and |
| 91 | // the grant path above went unguarded as a result. |
| 92 | return SheetEditor, true |
| 93 | } |
| 94 | return "", false |
| 95 | } |
| 96 | |
| 97 | // mayRead is the gate every read route uses. |
| 98 | func (a *App) mayRead(sheetID uint64, m Member) bool { |
| 99 | role, ok := a.roleFor(sheetID, m) |
| 100 | return ok && role.Allows(SheetViewer) |
| 101 | } |
| 102 | |
| 103 | // mayWrite is the gate every cell-writing route uses. |
| 104 | func (a *App) mayWrite(sheetID uint64, m Member) bool { |
| 105 | role, ok := a.roleFor(sheetID, m) |
| 106 | return ok && role.Allows(SheetEditor) |
| 107 | } |
| 108 | |
| 109 | // mayShare is the gate the share routes use. Sheet owners only: a |
| 110 | // person who can change who else can read a sheet is exercising the |
| 111 | // one power that cannot be undone by the people it affects. |
| 112 | func (a *App) mayShare(sheetID uint64, m Member) bool { |
| 113 | role, ok := a.roleFor(sheetID, m) |
| 114 | return ok && role.Allows(SheetOwner) |
| 115 | } |
| 116 | |
| 117 | func (a *App) sheetExists(id uint64) bool { |
| 118 | var n int64 |
| 119 | if err := a.db.Model(&store.Sheet{}). |
| 120 | Where("id = ? AND deleted_at IS NULL AND filling_since IS NULL", id).Count(&n).Error; err != nil { |
| 121 | return false |
| 122 | } |
| 123 | return n == 1 |
| 124 | } |
| 125 | |
| 126 | // grantsOn lists who can reach a sheet, for the share screen. |
| 127 | type sharedWith struct { |
| 128 | Member Member |
| 129 | Role SheetRole |
| 130 | } |
| 131 | |
| 132 | func (a *App) grantsOn(ctx context.Context, sheetID uint64) ([]sharedWith, error) { |
| 133 | if a.db == nil { |
| 134 | return nil, errNoDB |
| 135 | } |
| 136 | var rows []Grant |
| 137 | if err := a.db.Where("sheet_id = ?", sheetID).Order("id ASC").Find(&rows).Error; err != nil { |
| 138 | return nil, err |
| 139 | } |
| 140 | out := make([]sharedWith, 0, len(rows)) |
| 141 | for _, g := range rows { |
| 142 | var m Member |
| 143 | if err := a.db.Where("id = ?", g.MemberID).First(&m).Error; err != nil { |
| 144 | continue // a grant whose member vanished names nobody |
| 145 | } |
| 146 | out = append(out, sharedWith{Member: a.withStanding(ctx, m), Role: SheetRole(g.Role)}) |
| 147 | } |
| 148 | return out, nil |
| 149 | } |
| 150 | |
| 151 | // grant gives an address a role on a sheet, creating the member as a |
| 152 | // guest if this is the first time the instance has seen them. |
| 153 | // |
| 154 | // Guest is the default for a new person, and the direction matters: |
| 155 | // a guest wrongly made a member sees every sheet on the instance, while |
| 156 | // a member wrongly left a guest sees one sheet too few and says so. |
| 157 | // Only SHEETS_OWNERS promotes beyond guest, at sign-in. |
| 158 | // |
| 159 | // g is the request's write guard (team_guard.go), run inside the |
| 160 | // transaction; nil outside team mode. |
| 161 | func (a *App) grant(g store.Guard, sheetID uint64, address string, role SheetRole, by Member) (Member, error) { |
| 162 | if a.db == nil { |
| 163 | return Member{}, errNoDB |
| 164 | } |
| 165 | if !role.Valid() { |
| 166 | return Member{}, errors.New("sheets: unknown role") |
| 167 | } |
| 168 | addr := strings.ToLower(strings.TrimSpace(address)) |
| 169 | if addr == "" { |
| 170 | return Member{}, errors.New("sheets: a share needs an address") |
| 171 | } |
| 172 | if !strings.Contains(addr, "@") { |
| 173 | return Member{}, errors.New("sheets: that does not look like an email address") |
| 174 | } |
| 175 | m, err := a.memberFor(addr) |
| 176 | if err != nil { |
| 177 | return Member{}, err |
| 178 | } |
| 179 | // Upsert: re-sharing with somebody who already has access changes |
| 180 | // their role rather than failing on the unique index, which is what |
| 181 | // a person doing it expects. |
| 182 | row := Grant{SheetID: sheetID, MemberID: m.ID, Role: string(role), GrantedBy: by.ID} |
| 183 | // One transaction, because the check and the write are the same |
| 184 | // decision. Scoped to tx throughout, never the outer handle |
| 185 | // (AGENTS.md) — the one-connection writer pool deadlocks otherwise. |
| 186 | if err := a.db.Transaction(func(tx *gorm.DB) error { |
| 187 | return g.Run(func() error { |
| 188 | going, err := lastOwnerGoing(tx, sheetID, m.ID, role) |
| 189 | if err != nil { |
| 190 | return err |
| 191 | } |
| 192 | if going { |
| 193 | return errLastOwner |
| 194 | } |
| 195 | return tx.Clauses(clause.OnConflict{ |
| 196 | Columns: []clause.Column{{Name: "sheet_id"}, {Name: "member_id"}}, |
| 197 | DoUpdates: clause.AssignmentColumns([]string{"role", "granted_by", "updated_at"}), |
| 198 | }).Create(&row).Error |
| 199 | }) |
| 200 | }); err != nil { |
| 201 | return Member{}, err |
| 202 | } |
| 203 | return m, nil |
| 204 | } |
| 205 | |
| 206 | // revoke removes a grant. Removing one that is not there is not an |
| 207 | // error: the caller wanted that person not to have access, and they do |
| 208 | // not. |
| 209 | func (a *App) revoke(g store.Guard, sheetID, memberID uint64) error { |
| 210 | if a.db == nil { |
| 211 | return errNoDB |
| 212 | } |
| 213 | // The orphan check lives in here, inside the transaction that does |
| 214 | // the delete, rather than in the handler above it. A handler-side |
| 215 | // check is a read separated from its write by a request's worth of |
| 216 | // time: two owners revoking each other at once both saw two owners |
| 217 | // and both deleted. |
| 218 | return a.db.Transaction(func(tx *gorm.DB) error { |
| 219 | return g.Run(func() error { |
| 220 | going, err := lastOwnerGoing(tx, sheetID, memberID, SheetViewer) |
| 221 | if err != nil { |
| 222 | return err |
| 223 | } |
| 224 | if going { |
| 225 | return errLastOwner |
| 226 | } |
| 227 | return tx.Where("sheet_id = ? AND member_id = ?", sheetID, memberID). |
| 228 | Delete(&Grant{}).Error |
| 229 | }) |
| 230 | }) |
| 231 | } |
| 232 | |
| 233 | // Admits is the instance's admission gate: who may hold a session here. |
| 234 | // |
| 235 | // Two ways in, and the second is what makes sharing mean anything: |
| 236 | // |
| 237 | // 1. The SHEETS_OWNERS allowlist — the team. |
| 238 | // 2. Holding at least one grant — a guest somebody shared a sheet |
| 239 | // with. |
| 240 | // |
| 241 | // Without the second, `grant` would happily create a Grant row and a |
| 242 | // guest Member for somebody who could then never sign in to use it: |
| 243 | // auth refuses an address its Authorize does not admit, so the share |
| 244 | // would be a row nobody could ever exercise. That is not a |
| 245 | // hypothetical — it is what this app did between the grants table |
| 246 | // landing and this function existing. |
| 247 | // |
| 248 | // It stays fail-closed. An address with no allowlist entry and no grant |
| 249 | // is refused, and a database error is refused rather than admitted: |
| 250 | // "we could not check" is not "yes". |
| 251 | func (a *App) Admits(address string) bool { |
| 252 | addr := strings.ToLower(strings.TrimSpace(address)) |
| 253 | if addr == "" { |
| 254 | return false |
| 255 | } |
| 256 | if a.admit != nil && a.admit(addr) { |
| 257 | return true |
| 258 | } |
| 259 | if a.db == nil { |
| 260 | return false |
| 261 | } |
| 262 | // The sheets join is load-bearing, not decoration. Without it this |
| 263 | // counts grants to sheets that no longer exist, so a guest whose |
| 264 | // every live grant has been revoked still signs in on the strength |
| 265 | // of a deleted one — and a sheet still being filled by an import |
| 266 | // would admit somebody before the import it belongs to had even |
| 267 | // succeeded. Admission has to rest on a sheet they could actually |
| 268 | // open. |
| 269 | var n int64 |
| 270 | if err := a.db.Model(&Grant{}). |
| 271 | Joins("JOIN members ON members.id = grants.member_id"). |
| 272 | Joins("JOIN sheets ON sheets.id = grants.sheet_id"). |
| 273 | Where("members.address = ? AND sheets.deleted_at IS NULL AND sheets.filling_since IS NULL", addr). |
| 274 | Count(&n).Error; err != nil { |
| 275 | return false |
| 276 | } |
| 277 | return n > 0 |
| 278 | } |
| 279 | |