| 1 | package teammode |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "net/http" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | "sync/atomic" |
| 10 | |
| 11 | "amadan.net/oficina/home/handoff" |
| 12 | "amadan.net/oficina/home/roster" |
| 13 | ) |
| 14 | |
| 15 | // RuntimeConfig opens a Runtime. Settings, State, DB, Sealer and |
| 16 | // IssuerTables are required. |
| 17 | type RuntimeConfig struct { |
| 18 | Settings *Settings |
| 19 | State State |
| 20 | // DB is the app's writer. Activation and evidence go through it. |
| 21 | DB *sql.DB |
| 22 | // Sealer seals the roster evidence: the app's Home DEK under its own |
| 23 | // namespace, as Docs ("oficina/docs") and Sheets do. |
| 24 | Sealer handoff.Sealer |
| 25 | // IssuerTables are the app's tables holding Home identities in an |
| 26 | // issuer column: connect's home_identity_links, the app's Home-only |
| 27 | // people. Open refuses activation while any row names another issuer: |
| 28 | // the marker pins one, and a row from another would be reinterpreted |
| 29 | // under it. Lower-case SQL identifiers only. |
| 30 | IssuerTables []string |
| 31 | // Transport and Clock are for tests (teammodetest); nil in production. |
| 32 | Transport http.RoundTripper |
| 33 | Clock roster.Clock |
| 34 | } |
| 35 | |
| 36 | var tablePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,62}$`) |
| 37 | |
| 38 | // Runtime is the process's roster cache and what acts on its answers. |
| 39 | type Runtime struct { |
| 40 | cache *roster.Cache |
| 41 | bindings roster.Bindings |
| 42 | // held: some Check since boot had a complete roster (the probe's |
| 43 | // "stale" versus "unknown"). |
| 44 | held atomic.Bool |
| 45 | } |
| 46 | |
| 47 | // Open activates team mode and builds the roster cache, after the app has |
| 48 | // applied its team schema and before it serves. It either returns a |
| 49 | // verified, activated runtime or refuses: ErrConfig for configuration (a |
| 50 | // foreign issuer, a different binding), ErrUnavailable for storage or |
| 51 | // evidence the cache cannot use. |
| 52 | func Open(ctx context.Context, c RuntimeConfig) (*Runtime, error) { |
| 53 | if c.Settings == nil || !c.State.valid() || c.DB == nil || c.Sealer == nil || len(c.IssuerTables) == 0 { |
| 54 | return nil, ErrConfig |
| 55 | } |
| 56 | b := c.Settings.Bindings() |
| 57 | parts := make([]string, 0, len(c.IssuerTables)) |
| 58 | args := make([]any, 0, len(c.IssuerTables)) |
| 59 | for _, t := range c.IssuerTables { |
| 60 | if !tablePattern.MatchString(t) { |
| 61 | return nil, ErrConfig |
| 62 | } |
| 63 | parts = append(parts, "(SELECT COUNT(*) FROM "+t+" WHERE issuer!=?)") |
| 64 | args = append(args, b.Issuer) |
| 65 | } |
| 66 | var foreign int |
| 67 | if err := c.DB.QueryRowContext(ctx, "SELECT "+strings.Join(parts, "+"), args...).Scan(&foreign); err != nil { |
| 68 | return nil, ErrUnavailable |
| 69 | } |
| 70 | if foreign != 0 { |
| 71 | return nil, ErrConfig |
| 72 | } |
| 73 | if err := c.State.Activate(ctx, c.DB, c.Settings.fingerprint); err != nil { |
| 74 | return nil, err |
| 75 | } |
| 76 | cache, err := roster.New(ctx, roster.Config{Record: c.Settings.record, Token: c.Settings.token, Transport: c.Transport, Clock: c.Clock, Durable: c.State.Evidence(c.DB), Sealer: c.Sealer}) |
| 77 | if err != nil { |
| 78 | return nil, ErrUnavailable |
| 79 | } |
| 80 | return &Runtime{cache: cache, bindings: b}, nil |
| 81 | } |
| 82 | |
| 83 | // Bindings are the verified bindings this runtime serves. |
| 84 | func (t *Runtime) Bindings() roster.Bindings { return t.bindings } |
| 85 | |
| 86 | // Check is the only way to ask the roster cache that yields a decision |
| 87 | // (Refresh yields none), so every definite answer — a request's, an |
| 88 | // allocation's or the probe's — records that a complete roster has been |
| 89 | // held since boot. It may wait for a refresh (at |
| 90 | // most roster.FetchTimeout), and a refresh publishes through the SQLite |
| 91 | // writer: never call it holding the writer. Inside a transaction, use |
| 92 | // Access.State or Guard, which never ask. |
| 93 | func (t *Runtime) Check(ctx context.Context, subject string) roster.Decision { |
| 94 | d := t.cache.Check(ctx, t.bindings.Issuer, t.bindings.Team, subject) |
| 95 | if d.State != roster.Unknown { |
| 96 | t.held.Store(true) |
| 97 | } |
| 98 | return d |
| 99 | } |
| 100 | |
| 101 | // Access decides one request's standing for the Home subject its session |
| 102 | // resolved to. subject "" (a local account with no Home identity) is |
| 103 | // NotMember without asking: no Home identity, no team standing. Call it per |
| 104 | // request, before any transaction; never store the result. |
| 105 | func (t *Runtime) Access(ctx context.Context, subject string) *Access { |
| 106 | if subject == "" { |
| 107 | return &Access{decision: roster.Decision{State: roster.NotMember}} |
| 108 | } |
| 109 | return &Access{subject: subject, decision: t.Check(ctx, subject)} |
| 110 | } |
| 111 | |
| 112 | // AdmitUnlinked is the decision behind connect's Unlinked hook: nil only |
| 113 | // when the roster says the subject is a Member now and the lease on that |
| 114 | // answer is still valid, which is the one condition on which an app may |
| 115 | // create a Home-only person. ErrNotMember for a subject the roster does not |
| 116 | // list, or one that cannot be on this team (another issuer, not a person |
| 117 | // ref); ErrUnavailable when it cannot be decided. It records identity's |
| 118 | // precondition, not standing: every later request asks the roster again. |
| 119 | func (t *Runtime) AdmitUnlinked(ctx context.Context, issuer, subject string) error { |
| 120 | if issuer != t.bindings.Issuer || !roster.ValidSubject(subject) { |
| 121 | return ErrNotMember |
| 122 | } |
| 123 | d := t.Check(ctx, subject) |
| 124 | switch { |
| 125 | case d.State == roster.Member && d.Lease.Valid(): |
| 126 | return nil |
| 127 | case d.State == roster.NotMember: |
| 128 | return ErrNotMember |
| 129 | } |
| 130 | return ErrUnavailable |
| 131 | } |
| 132 | |
| 133 | // Refresh joins (or starts) the cache's refresh flight and waits for it. |
| 134 | // Ordinary requests never need it; Check refreshes when due. |
| 135 | func (t *Runtime) Refresh(ctx context.Context) error { return t.cache.Refresh(ctx) } |
| 136 | |
| 137 | // probeSubject is a well-formed person ref the probe asks about. Its answer |
| 138 | // is never used, only whether there was one. |
| 139 | var probeSubject = "pr_" + strings.Repeat("2", 26) |
| 140 | |
| 141 | // RosterState is the probe's roster field: |
| 142 | // |
| 143 | // - "ok": a complete roster, fetched within roster.MaximumAge, decides |
| 144 | // standing now; |
| 145 | // - "stale": one was held since this process started, but it has aged out |
| 146 | // and could not be refreshed, so standing is Unknown; |
| 147 | // - "unknown": no complete roster has been held since boot. |
| 148 | // |
| 149 | // Asking starts a refresh when one is due and waits for it, exactly as a |
| 150 | // signed-in request does, which is what lets Alta's polling pull the first |
| 151 | // roster. The cache's single flight and RetryAfter backoff bound how often |
| 152 | // an unauthenticated caller can make this instance ask the directory. |
| 153 | func (t *Runtime) RosterState(ctx context.Context) string { |
| 154 | if t.Check(ctx, probeSubject).State != roster.Unknown { |
| 155 | return "ok" |
| 156 | } |
| 157 | if t.held.Load() { |
| 158 | return "stale" |
| 159 | } |
| 160 | return "unknown" |
| 161 | } |
| 162 | |