package teammode import ( "context" "database/sql" "net/http" "regexp" "strings" "sync/atomic" "amadan.net/oficina/home/handoff" "amadan.net/oficina/home/roster" ) // RuntimeConfig opens a Runtime. Settings, State, DB, Sealer and // IssuerTables are required. type RuntimeConfig struct { Settings *Settings State State // DB is the app's writer. Activation and evidence go through it. DB *sql.DB // Sealer seals the roster evidence: the app's Home DEK under its own // namespace, as Docs ("oficina/docs") and Sheets do. Sealer handoff.Sealer // IssuerTables are the app's tables holding Home identities in an // issuer column: connect's home_identity_links, the app's Home-only // people. Open refuses activation while any row names another issuer: // the marker pins one, and a row from another would be reinterpreted // under it. Lower-case SQL identifiers only. IssuerTables []string // Transport and Clock are for tests (teammodetest); nil in production. Transport http.RoundTripper Clock roster.Clock } var tablePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,62}$`) // Runtime is the process's roster cache and what acts on its answers. type Runtime struct { cache *roster.Cache bindings roster.Bindings // held: some Check since boot had a complete roster (the probe's // "stale" versus "unknown"). held atomic.Bool } // Open activates team mode and builds the roster cache, after the app has // applied its team schema and before it serves. It either returns a // verified, activated runtime or refuses: ErrConfig for configuration (a // foreign issuer, a different binding), ErrUnavailable for storage or // evidence the cache cannot use. func Open(ctx context.Context, c RuntimeConfig) (*Runtime, error) { if c.Settings == nil || !c.State.valid() || c.DB == nil || c.Sealer == nil || len(c.IssuerTables) == 0 { return nil, ErrConfig } b := c.Settings.Bindings() parts := make([]string, 0, len(c.IssuerTables)) args := make([]any, 0, len(c.IssuerTables)) for _, t := range c.IssuerTables { if !tablePattern.MatchString(t) { return nil, ErrConfig } parts = append(parts, "(SELECT COUNT(*) FROM "+t+" WHERE issuer!=?)") args = append(args, b.Issuer) } var foreign int if err := c.DB.QueryRowContext(ctx, "SELECT "+strings.Join(parts, "+"), args...).Scan(&foreign); err != nil { return nil, ErrUnavailable } if foreign != 0 { return nil, ErrConfig } if err := c.State.Activate(ctx, c.DB, c.Settings.fingerprint); err != nil { return nil, err } 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}) if err != nil { return nil, ErrUnavailable } return &Runtime{cache: cache, bindings: b}, nil } // Bindings are the verified bindings this runtime serves. func (t *Runtime) Bindings() roster.Bindings { return t.bindings } // Check is the only way to ask the roster cache that yields a decision // (Refresh yields none), so every definite answer — a request's, an // allocation's or the probe's — records that a complete roster has been // held since boot. It may wait for a refresh (at // most roster.FetchTimeout), and a refresh publishes through the SQLite // writer: never call it holding the writer. Inside a transaction, use // Access.State or Guard, which never ask. func (t *Runtime) Check(ctx context.Context, subject string) roster.Decision { d := t.cache.Check(ctx, t.bindings.Issuer, t.bindings.Team, subject) if d.State != roster.Unknown { t.held.Store(true) } return d } // Access decides one request's standing for the Home subject its session // resolved to. subject "" (a local account with no Home identity) is // NotMember without asking: no Home identity, no team standing. Call it per // request, before any transaction; never store the result. func (t *Runtime) Access(ctx context.Context, subject string) *Access { if subject == "" { return &Access{decision: roster.Decision{State: roster.NotMember}} } return &Access{subject: subject, decision: t.Check(ctx, subject)} } // AdmitUnlinked is the decision behind connect's Unlinked hook: nil only // when the roster says the subject is a Member now and the lease on that // answer is still valid, which is the one condition on which an app may // create a Home-only person. ErrNotMember for a subject the roster does not // list, or one that cannot be on this team (another issuer, not a person // ref); ErrUnavailable when it cannot be decided. It records identity's // precondition, not standing: every later request asks the roster again. func (t *Runtime) AdmitUnlinked(ctx context.Context, issuer, subject string) error { if issuer != t.bindings.Issuer || !roster.ValidSubject(subject) { return ErrNotMember } d := t.Check(ctx, subject) switch { case d.State == roster.Member && d.Lease.Valid(): return nil case d.State == roster.NotMember: return ErrNotMember } return ErrUnavailable } // Refresh joins (or starts) the cache's refresh flight and waits for it. // Ordinary requests never need it; Check refreshes when due. func (t *Runtime) Refresh(ctx context.Context) error { return t.cache.Refresh(ctx) } // probeSubject is a well-formed person ref the probe asks about. Its answer // is never used, only whether there was one. var probeSubject = "pr_" + strings.Repeat("2", 26) // RosterState is the probe's roster field: // // - "ok": a complete roster, fetched within roster.MaximumAge, decides // standing now; // - "stale": one was held since this process started, but it has aged out // and could not be refreshed, so standing is Unknown; // - "unknown": no complete roster has been held since boot. // // Asking starts a refresh when one is due and waits for it, exactly as a // signed-in request does, which is what lets Alta's polling pull the first // roster. The cache's single flight and RetryAfter backoff bound how often // an unauthenticated caller can make this instance ask the directory. func (t *Runtime) RosterState(ctx context.Context) string { if t.Check(ctx, probeSubject).State != roster.Unknown { return "ok" } if t.held.Load() { return "stale" } return "unknown" }