| 1 | package teammode |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "embed" |
| 7 | "encoding/base64" |
| 8 | "errors" |
| 9 | "regexp" |
| 10 | "strings" |
| 11 | |
| 12 | "amadan.net/oficina/home/roster" |
| 13 | "amadan.net/rastrillo/rastrillo/migrate" |
| 14 | ) |
| 15 | |
| 16 | // The marker and evidence tables, with the namespace a parameter. With |
| 17 | // "docs" this is byte-for-byte Docs' teamstate/migrations/0001_team.sql, |
| 18 | // and with "sheets" the first ten lines of Sheets' — so either app keeps its |
| 19 | // applied migration (rastrillo checksums it) and its tables when it |
| 20 | // re-points here (testdata, TestSchemaIsDocsAndSheetsMarker). |
| 21 | // |
| 22 | //go:embed schema/0001_team.sql.tmpl |
| 23 | var schemaTemplate string |
| 24 | |
| 25 | var namespacePattern = regexp.MustCompile(`^[a-z][a-z0-9]{0,30}$`) |
| 26 | |
| 27 | // State is team mode's durable state for one app: the activation marker and |
| 28 | // the roster evidence, in tables named <namespace>_team_required and |
| 29 | // <namespace>_team_roster_evidence. The zero State refuses everything. |
| 30 | type State struct{ ns string } |
| 31 | |
| 32 | // NewState names an app's team state: lower-case letters and digits, |
| 33 | // conventionally the app ("docs", "sheets", "slides"). |
| 34 | func NewState(namespace string) (State, error) { |
| 35 | if !namespacePattern.MatchString(namespace) { |
| 36 | return State{}, ErrConfig |
| 37 | } |
| 38 | return State{ns: namespace}, nil |
| 39 | } |
| 40 | |
| 41 | // MustState is NewState for a package-level constant. |
| 42 | func MustState(namespace string) State { |
| 43 | s, err := NewState(namespace) |
| 44 | if err != nil { |
| 45 | panic("teammode: invalid state namespace") |
| 46 | } |
| 47 | return s |
| 48 | } |
| 49 | |
| 50 | func (s State) Namespace() string { return s.ns } |
| 51 | func (s State) valid() bool { return namespacePattern.MatchString(s.ns) } |
| 52 | func (s State) required() string { return s.ns + "_team_required" } |
| 53 | func (s State) evidence() string { return s.ns + "_team_roster_evidence" } |
| 54 | |
| 55 | // SQL is the marker and evidence migration for this namespace. |
| 56 | func (s State) SQL() string { return strings.ReplaceAll(schemaTemplate, "{{ns}}", s.ns) } |
| 57 | |
| 58 | // Schema is the migration set "<namespace>_team" holding SQL as |
| 59 | // 0001_team. An app merges it after its own schema (and after any table its |
| 60 | // own team migrations' triggers name) and applies it only in team mode; |
| 61 | // once applied it stays, because the marker in it is what keeps the |
| 62 | // database in team mode. An app whose existing team set already carries |
| 63 | // these tables (Sheets) keeps its own set and uses State over it. |
| 64 | func (s State) Schema() *migrate.Set { |
| 65 | if !s.valid() { |
| 66 | panic("teammode: invalid state namespace") |
| 67 | } |
| 68 | return migrate.MustFromFS(noFiles, s.ns+"_team").Add(migrate.Migration{ID: "0001_team", SQL: s.SQL()}) |
| 69 | } |
| 70 | |
| 71 | // noFiles names a set with no files, so the one migration is SQL built here. |
| 72 | var noFiles embed.FS |
| 73 | |
| 74 | func validFingerprint(v string) bool { |
| 75 | b, err := base64.RawURLEncoding.DecodeString(v) |
| 76 | return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == v |
| 77 | } |
| 78 | |
| 79 | // Required reads the marker. It reads sqlite_master first, so it is safe on |
| 80 | // a database that has never had the team schema applied — which is what |
| 81 | // lets BootSchema run before any migration. activated is false for a |
| 82 | // never-activated database; ErrUnavailable is a read failure; ErrConfig a |
| 83 | // marker that is not a fingerprint. |
| 84 | func (s State) Required(ctx context.Context, db *sql.DB) (fingerprint string, activated bool, err error) { |
| 85 | if !s.valid() || db == nil { |
| 86 | return "", false, ErrConfig |
| 87 | } |
| 88 | var count int |
| 89 | if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?", s.required()).Scan(&count); err != nil { |
| 90 | return "", false, ErrUnavailable |
| 91 | } |
| 92 | if count == 0 { |
| 93 | return "", false, nil |
| 94 | } |
| 95 | var value string |
| 96 | err = db.QueryRowContext(ctx, "SELECT bindings FROM "+s.required()+" WHERE id=1").Scan(&value) |
| 97 | if errors.Is(err, sql.ErrNoRows) { |
| 98 | return "", false, nil |
| 99 | } |
| 100 | if err != nil { |
| 101 | return "", false, ErrUnavailable |
| 102 | } |
| 103 | if !validFingerprint(value) { |
| 104 | return "", false, ErrConfig |
| 105 | } |
| 106 | return value, true, nil |
| 107 | } |
| 108 | |
| 109 | // BootSchema is the schema an app applies, chosen before anything is |
| 110 | // migrated, from the marker and the verified settings (nil: team mode off). |
| 111 | // A database activated in team mode refuses to boot without team |
| 112 | // configuration — an environment variable dropped in a redeploy must not |
| 113 | // quietly hand standing back to an allowlist — and refuses a configuration |
| 114 | // with a different binding. base is the app's schema; team is base plus its |
| 115 | // team sets (State.Schema among them), applied only when settings is set. |
| 116 | func (s State) BootSchema(ctx context.Context, db *sql.DB, settings *Settings, base, team *migrate.Set) (*migrate.Set, error) { |
| 117 | fingerprint, activated, err := s.Required(ctx, db) |
| 118 | if err != nil { |
| 119 | return nil, err |
| 120 | } |
| 121 | if activated && (settings == nil || fingerprint != settings.fingerprint) { |
| 122 | return nil, ErrConfig |
| 123 | } |
| 124 | if settings == nil { |
| 125 | return base, nil |
| 126 | } |
| 127 | return team, nil |
| 128 | } |
| 129 | |
| 130 | // Activate records the verified fingerprint, and commits, before the app |
| 131 | // serves a request or allocates an identity. It records a deployment |
| 132 | // binding, never an owner or a roster. A database already bound to another |
| 133 | // binding is refused, and the marker's triggers refuse any rewrite. |
| 134 | func (s State) Activate(ctx context.Context, db *sql.DB, fingerprint string) error { |
| 135 | if !s.valid() || db == nil || !validFingerprint(fingerprint) { |
| 136 | return ErrConfig |
| 137 | } |
| 138 | tx, err := db.BeginTx(ctx, nil) |
| 139 | if err != nil { |
| 140 | return ErrUnavailable |
| 141 | } |
| 142 | defer tx.Rollback() |
| 143 | if _, err = tx.ExecContext(ctx, "INSERT INTO "+s.required()+"(id,bindings) VALUES(1,?) ON CONFLICT(id) DO NOTHING", fingerprint); err != nil { |
| 144 | return ErrUnavailable |
| 145 | } |
| 146 | var got string |
| 147 | if err = tx.QueryRowContext(ctx, "SELECT bindings FROM "+s.required()+" WHERE id=1").Scan(&got); err != nil { |
| 148 | return ErrUnavailable |
| 149 | } |
| 150 | if got != fingerprint { |
| 151 | return ErrConfig |
| 152 | } |
| 153 | if tx.Commit() != nil { |
| 154 | return ErrUnavailable |
| 155 | } |
| 156 | return nil |
| 157 | } |
| 158 | |
| 159 | // Evidence is roster.Durable over the app's replicated SQLite file: one |
| 160 | // bounded atomic replacement and one bounded load of the cache's sealed |
| 161 | // envelope, never decoded here. |
| 162 | func (s State) Evidence(db *sql.DB) roster.Durable { return evidence{s, db} } |
| 163 | |
| 164 | type evidence struct { |
| 165 | s State |
| 166 | db *sql.DB |
| 167 | } |
| 168 | |
| 169 | func (e evidence) Load(ctx context.Context) ([]byte, error) { |
| 170 | if !e.s.valid() || e.db == nil { |
| 171 | return nil, ErrUnavailable |
| 172 | } |
| 173 | var b []byte |
| 174 | err := e.db.QueryRowContext(ctx, "SELECT payload FROM "+e.s.evidence()+" WHERE id=1").Scan(&b) |
| 175 | if errors.Is(err, sql.ErrNoRows) { |
| 176 | return nil, roster.ErrNoEvidence |
| 177 | } |
| 178 | if err != nil || len(b) > roster.EvidenceLimit+128 { |
| 179 | return nil, ErrUnavailable |
| 180 | } |
| 181 | return b, nil |
| 182 | } |
| 183 | |
| 184 | func (e evidence) Save(ctx context.Context, b []byte) error { |
| 185 | if !e.s.valid() || e.db == nil || len(b) == 0 || len(b) > roster.EvidenceLimit+128 { |
| 186 | return ErrUnavailable |
| 187 | } |
| 188 | if _, err := e.db.ExecContext(ctx, "INSERT INTO "+e.s.evidence()+"(id,payload) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload", b); err != nil { |
| 189 | return ErrUnavailable |
| 190 | } |
| 191 | return nil |
| 192 | } |
| 193 | |