package teammode import ( "context" "database/sql" "embed" "encoding/base64" "errors" "regexp" "strings" "amadan.net/oficina/home/roster" "amadan.net/rastrillo/rastrillo/migrate" ) // The marker and evidence tables, with the namespace a parameter. With // "docs" this is byte-for-byte Docs' teamstate/migrations/0001_team.sql, // and with "sheets" the first ten lines of Sheets' — so either app keeps its // applied migration (rastrillo checksums it) and its tables when it // re-points here (testdata, TestSchemaIsDocsAndSheetsMarker). // //go:embed schema/0001_team.sql.tmpl var schemaTemplate string var namespacePattern = regexp.MustCompile(`^[a-z][a-z0-9]{0,30}$`) // State is team mode's durable state for one app: the activation marker and // the roster evidence, in tables named _team_required and // _team_roster_evidence. The zero State refuses everything. type State struct{ ns string } // NewState names an app's team state: lower-case letters and digits, // conventionally the app ("docs", "sheets", "slides"). func NewState(namespace string) (State, error) { if !namespacePattern.MatchString(namespace) { return State{}, ErrConfig } return State{ns: namespace}, nil } // MustState is NewState for a package-level constant. func MustState(namespace string) State { s, err := NewState(namespace) if err != nil { panic("teammode: invalid state namespace") } return s } func (s State) Namespace() string { return s.ns } func (s State) valid() bool { return namespacePattern.MatchString(s.ns) } func (s State) required() string { return s.ns + "_team_required" } func (s State) evidence() string { return s.ns + "_team_roster_evidence" } // SQL is the marker and evidence migration for this namespace. func (s State) SQL() string { return strings.ReplaceAll(schemaTemplate, "{{ns}}", s.ns) } // Schema is the migration set "_team" holding SQL as // 0001_team. An app merges it after its own schema (and after any table its // own team migrations' triggers name) and applies it only in team mode; // once applied it stays, because the marker in it is what keeps the // database in team mode. An app whose existing team set already carries // these tables (Sheets) keeps its own set and uses State over it. func (s State) Schema() *migrate.Set { if !s.valid() { panic("teammode: invalid state namespace") } return migrate.MustFromFS(noFiles, s.ns+"_team").Add(migrate.Migration{ID: "0001_team", SQL: s.SQL()}) } // noFiles names a set with no files, so the one migration is SQL built here. var noFiles embed.FS func validFingerprint(v string) bool { b, err := base64.RawURLEncoding.DecodeString(v) return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == v } // Required reads the marker. It reads sqlite_master first, so it is safe on // a database that has never had the team schema applied — which is what // lets BootSchema run before any migration. activated is false for a // never-activated database; ErrUnavailable is a read failure; ErrConfig a // marker that is not a fingerprint. func (s State) Required(ctx context.Context, db *sql.DB) (fingerprint string, activated bool, err error) { if !s.valid() || db == nil { return "", false, ErrConfig } var count int if err := db.QueryRowContext(ctx, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?", s.required()).Scan(&count); err != nil { return "", false, ErrUnavailable } if count == 0 { return "", false, nil } var value string err = db.QueryRowContext(ctx, "SELECT bindings FROM "+s.required()+" WHERE id=1").Scan(&value) if errors.Is(err, sql.ErrNoRows) { return "", false, nil } if err != nil { return "", false, ErrUnavailable } if !validFingerprint(value) { return "", false, ErrConfig } return value, true, nil } // BootSchema is the schema an app applies, chosen before anything is // migrated, from the marker and the verified settings (nil: team mode off). // A database activated in team mode refuses to boot without team // configuration — an environment variable dropped in a redeploy must not // quietly hand standing back to an allowlist — and refuses a configuration // with a different binding. base is the app's schema; team is base plus its // team sets (State.Schema among them), applied only when settings is set. func (s State) BootSchema(ctx context.Context, db *sql.DB, settings *Settings, base, team *migrate.Set) (*migrate.Set, error) { fingerprint, activated, err := s.Required(ctx, db) if err != nil { return nil, err } if activated && (settings == nil || fingerprint != settings.fingerprint) { return nil, ErrConfig } if settings == nil { return base, nil } return team, nil } // Activate records the verified fingerprint, and commits, before the app // serves a request or allocates an identity. It records a deployment // binding, never an owner or a roster. A database already bound to another // binding is refused, and the marker's triggers refuse any rewrite. func (s State) Activate(ctx context.Context, db *sql.DB, fingerprint string) error { if !s.valid() || db == nil || !validFingerprint(fingerprint) { return ErrConfig } tx, err := db.BeginTx(ctx, nil) if err != nil { return ErrUnavailable } defer tx.Rollback() if _, err = tx.ExecContext(ctx, "INSERT INTO "+s.required()+"(id,bindings) VALUES(1,?) ON CONFLICT(id) DO NOTHING", fingerprint); err != nil { return ErrUnavailable } var got string if err = tx.QueryRowContext(ctx, "SELECT bindings FROM "+s.required()+" WHERE id=1").Scan(&got); err != nil { return ErrUnavailable } if got != fingerprint { return ErrConfig } if tx.Commit() != nil { return ErrUnavailable } return nil } // Evidence is roster.Durable over the app's replicated SQLite file: one // bounded atomic replacement and one bounded load of the cache's sealed // envelope, never decoded here. func (s State) Evidence(db *sql.DB) roster.Durable { return evidence{s, db} } type evidence struct { s State db *sql.DB } func (e evidence) Load(ctx context.Context) ([]byte, error) { if !e.s.valid() || e.db == nil { return nil, ErrUnavailable } var b []byte err := e.db.QueryRowContext(ctx, "SELECT payload FROM "+e.s.evidence()+" WHERE id=1").Scan(&b) if errors.Is(err, sql.ErrNoRows) { return nil, roster.ErrNoEvidence } if err != nil || len(b) > roster.EvidenceLimit+128 { return nil, ErrUnavailable } return b, nil } func (e evidence) Save(ctx context.Context, b []byte) error { if !e.s.valid() || e.db == nil || len(b) == 0 || len(b) > roster.EvidenceLimit+128 { return ErrUnavailable } 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 { return ErrUnavailable } return nil }