oficina / alta Public

adopt: live checks proving revocation

RunLive drives the eight live checks against connect with the
agent-access client at e4ea914 over an in-memory MemoryStore. The
member's and the owner's free/busy requests are recorded under the
client and replayed byte for byte, same bearer, by a plain client that
follows no redirect; only agent-access's 401 challenge or forbidden 403
passes. A replay after the bearer expired is inconclusive, and the
owner's step repeats with a fresh connection, at most three times.

SaveCheck now records passed, inconclusive or failed:<code>; LiveGate
ignores inconclusive and still treats any failure as final.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 4f492abbfded4ba4f73233de08070f64e293330f parent 1caccfb
9 files changed, +1,748 −12
  • adopt/live.go +604 −0
  • adopt/live_test.go +1,007 −0
  • adopt/migrations/0001_adopt.sql +3 −2
  • adopt/observer_test.go +1 −1
  • adopt/store.go +8 −4
  • adopt/store_test.go +34 −2
  • adopt/words.go +35 −3
  • go.mod +14 −0
  • go.sum +42 −0
diff --git a/adopt/live.go b/adopt/live.go
new file mode 100644
index 0000000..21dbec0
--- /dev/null
+++ b/adopt/live.go
@@ -0,0 +1,604 @@
+// This file runs the live checks: against oficina-connect, with a
+// throwaway test account and Paul's own, it proves that a non-member is
+// refused, that a member lacking local permission is refused, and that
+// removing a member or revoking a connection refuses the very request
+// that worked before, while local access stays. Plan C waits on them.
+package adopt
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "regexp"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/agent-access.git/client"
+)
+
+// Variables only so tests can reach the fake connect, move the clock and
+// read what is printed.
+var (
+ liveTransport http.RoundTripper // nil: http.DefaultTransport
+ liveNow = time.Now
+ liveOut io.Writer = os.Stdout
+ liveOwnerAttempts = 3
+)
+
+// The live checks' outcomes as SaveCheck records them.
+const (
+ livePassed = "passed"
+ liveInconclusive = "inconclusive"
+)
+
+// liveScope is the one scope the checks ask connect for.
+const liveScope = "calendar:read"
+
+// Prompter asks Paul to type sentence once he has done what it says. It
+// returns nil only when he typed it exactly.
+type Prompter interface {
+ Ask(ctx context.Context, sentence string) error
+}
+
+// MemoryStore is a client.Store that keeps one connection's credentials
+// in memory only: nothing is written to disk or to a keyring. Load and
+// Save copy the token, so the store's own copy is never shared.
+type MemoryStore struct {
+ mu sync.Mutex
+ creds client.Credentials
+ ok bool
+}
+
+func copyCreds(c client.Credentials) client.Credentials {
+ if c.Token != nil {
+ t := *c.Token
+ c.Token = &t
+ }
+ return c
+}
+
+// Load returns a copy of the stored credentials.
+func (m *MemoryStore) Load() (client.Credentials, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.ok {
+ return client.Credentials{}, errors.New("adopt: not connected")
+ }
+ return copyCreds(m.creds), nil
+}
+
+// Save keeps a copy of c.
+func (m *MemoryStore) Save(c client.Credentials) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.creds, m.ok = copyCreds(c), true
+ return nil
+}
+
+// Delete forgets the credentials.
+func (m *MemoryStore) Delete() error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.creds, m.ok = client.Credentials{}, false
+ return nil
+}
+
+// expiry is the stored access token's expiry, zero when there is none.
+func (m *MemoryStore) expiry() time.Time {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.ok || m.creds.Token == nil {
+ return time.Time{}
+ }
+ return m.creds.Token.Expiry
+}
+
+// savedRequest is one authenticated operations request exactly as it was
+// sent, kept to be replayed, and the expiry of its bearer.
+type savedRequest struct {
+ method, url string
+ body []byte
+ bearer []byte
+ expiry time.Time
+}
+
+// zero overwrites the saved body and bearer.
+func (r *savedRequest) zero() {
+ if r == nil {
+ return
+ }
+ clear(r.body)
+ clear(r.bearer)
+ *r = savedRequest{}
+}
+
+// exchange is one operations call: the request as sent, and the answer
+// (status 0 when none came).
+type exchange struct {
+ req savedRequest
+ status int
+ header http.Header
+ body []byte
+}
+
+// recorder sits under a client's HTTP and keeps the last operations
+// request it sent and the answer, so the request can be replayed byte for
+// byte. Nothing else is kept.
+type recorder struct {
+ base http.RoundTripper
+ last *exchange
+}
+
+func (r *recorder) RoundTrip(req *http.Request) (*http.Response, error) {
+ if req.Method != http.MethodPost || !strings.HasPrefix(req.URL.Path, "/api/v1/operations/") {
+ return r.base.RoundTrip(req)
+ }
+ ex := &exchange{req: savedRequest{method: req.Method, url: req.URL.String()}}
+ if req.GetBody != nil {
+ b, err := req.GetBody()
+ if err != nil {
+ return nil, errors.New("adopt: live request unreadable")
+ }
+ ex.req.body, err = io.ReadAll(b)
+ b.Close()
+ if err != nil {
+ return nil, errors.New("adopt: live request unreadable")
+ }
+ }
+ bearer, ok := strings.CutPrefix(req.Header.Get("Authorization"), "Bearer ")
+ if !ok || bearer == "" || len(req.Header.Values("Authorization")) != 1 {
+ return nil, errors.New("adopt: live request not authenticated")
+ }
+ ex.req.bearer = []byte(bearer)
+ r.last = ex
+ resp, err := r.base.RoundTrip(req)
+ if err != nil {
+ return nil, err
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, client.MaxResponse+1))
+ resp.Body.Close()
+ if err != nil {
+ return nil, errors.New("adopt: live answer unreadable")
+ }
+ ex.status, ex.header, ex.body = resp.StatusCode, resp.Header.Clone(), body
+ resp.Body = io.NopCloser(bytes.NewReader(body))
+ return resp, nil
+}
+
+// liveConn is one connection to connect: a client over a MemoryStore,
+// with the recorder under it.
+type liveConn struct {
+ c *client.Client
+ store *MemoryStore
+ rec *recorder
+ out bool // signed out: connect revoked it and the store is empty
+}
+
+func liveBase() http.RoundTripper {
+ if liveTransport != nil {
+ return liveTransport
+ }
+ return http.DefaultTransport
+}
+
+func newLiveConn() *liveConn {
+ store := &MemoryStore{}
+ rec := &recorder{base: liveBase()}
+ c := client.New(store)
+ c.HTTP = &http.Client{Transport: rec, Timeout: 30 * time.Second,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ return &liveConn{c: c, store: store, rec: rec}
+}
+
+// call makes one operation call and returns the exchange, nil when no
+// request was sent. The bearer's expiry is taken from the store as the
+// call left it.
+func (l *liveConn) call(ctx context.Context, op string, input []byte) *exchange {
+ l.rec.last = nil
+ _, _ = l.c.Call(ctx, op, input)
+ ex := l.rec.last
+ l.rec.last = nil
+ if ex != nil {
+ ex.req.expiry = l.store.expiry()
+ }
+ return ex
+}
+
+// The answers a check can see, as fixed codes.
+const (
+ ansAllowed = "allowed" // 2xx
+ ansUnauthenticated = "unauthenticated" // 401 with agent-access's challenge
+ ansForbidden = "forbidden" // 403 with agent-access's forbidden body
+ ansNotFound = "not_found" // 404 with agent-access's not_found body
+ ansOther = "other" // anything else: no answer, 3xx, 5xx, another 4xx or body
+)
+
+// answerOf classifies a status, header and body. A refusal counts only in
+// agent-access's own shape: the 401 is the Bearer challenge Probe calls
+// agent-401, and a 403 or 404 carries {"error":{"code":…}} with the
+// matching code.
+func answerOf(status int, h http.Header, body []byte) string {
+ switch {
+ case status >= 200 && status < 300:
+ return ansAllowed
+ case status == http.StatusUnauthorized:
+ if shape(status, h, body) == OpsAgent401 {
+ return ansUnauthenticated
+ }
+ case status == http.StatusForbidden:
+ if agentCode(body) == "forbidden" {
+ return ansForbidden
+ }
+ case status == http.StatusNotFound:
+ if agentCode(body) == "not_found" {
+ return ansNotFound
+ }
+ }
+ return ansOther
+}
+
+func agentCode(body []byte) string {
+ var b struct {
+ Error struct {
+ Code string `json:"code"`
+ } `json:"error"`
+ }
+ if access.DecodeJSON(body, &b) != nil {
+ return ""
+ }
+ return b.Error.Code
+}
+
+func answerOfExchange(ex *exchange) string {
+ if ex == nil || ex.status == 0 {
+ return ansOther
+ }
+ return answerOf(ex.status, ex.header, ex.body)
+}
+
+// mustRefuse is the outcome of a call that must be refused: passed on one
+// of refusals, failed:allowed on success, inconclusive otherwise.
+func mustRefuse(answer string, refusals ...string) string {
+ switch {
+ case answer == ansAllowed:
+ return "failed:" + ansAllowed
+ case slices.Contains(refusals, answer):
+ return livePassed
+ }
+ return liveInconclusive
+}
+
+// mustSucceed is the outcome of a call that must succeed: passed on
+// success, failed:<code> on an agent-access refusal, inconclusive when
+// nothing was proved either way.
+func mustSucceed(answer string) string {
+ switch answer {
+ case ansAllowed:
+ return livePassed
+ case ansUnauthenticated, ansForbidden, ansNotFound:
+ return "failed:" + answer
+ }
+ return liveInconclusive
+}
+
+// liveOutcome is what SaveCheck accepts: passed, inconclusive, or
+// failed:<code> with a fixed lower-case code.
+var liveOutcome = regexp.MustCompile(`^(passed|inconclusive|failed:[a-z][a-z_-]*)$`)
+
+// errLiveSignOut is a connection connect did not revoke.
+var errLiveSignOut = errors.New("adopt: live-sign-out-failed")
+
+// RunLive runs the live checks against connect at server for the team
+// sqid, recording each outcome with SaveCheck: passed, failed:<code> or
+// inconclusive. It stops at the first check that does not pass; a
+// failure keeps Plan C refused for good, an inconclusive check only until
+// it passes on a later run. Only the owner's revocation check repeats on
+// its own, with a fresh connection, up to liveOwnerAttempts times.
+//
+// The test account must have signed in to calendar.oficina.works once,
+// and foreignEventID names one of Paul's own events it cannot see.
+//
+// Every connection RunLive makes is signed out (connect revokes it)
+// before it returns, whatever happened, and the saved requests and
+// tokens are zeroed. Without apply it prints the steps and contacts
+// nothing: no browser, no prompt, no request, no record.
+func RunLive(ctx context.Context, server, sqid string, p Prompter, s *Store, open func(string) error, foreignEventID string, apply bool) (err error) {
+ u, perr := url.Parse(server)
+ switch {
+ case perr != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" && u.Path != "/":
+ return errors.New("adopt: the live checks need connect's https origin")
+ case sqid == "":
+ return errors.New("adopt: the live checks need the team")
+ }
+ event, perr := strconv.ParseInt(foreignEventID, 10, 64)
+ if perr != nil || event < 1 || strconv.FormatInt(event, 10) != foreignEventID {
+ return errors.New("adopt: the foreign event is not an event id")
+ }
+ if !apply {
+ for _, line := range LiveSteps {
+ fmt.Fprintln(liveOut, line)
+ }
+ return nil
+ }
+ if s == nil || p == nil || open == nil {
+ return errors.New("adopt: the live checks need the journal, a prompter and a browser")
+ }
+ r := &liveRun{server: u.Scheme + "://" + u.Host, sqid: sqid, event: event, p: p, s: s, open: open}
+ defer func() { err = errors.Join(err, r.close()) }()
+ return r.run(ctx)
+}
+
+type liveRun struct {
+ server, sqid string
+ event int64
+ p Prompter
+ s *Store
+ open func(string) error
+ conns []*liveConn
+ saved []*savedRequest
+}
+
+func (r *liveRun) say(line string) { fmt.Fprintln(liveOut, line) }
+
+// record saves name's outcome. Anything but passed stops the run, with an
+// error naming the check and the outcome only.
+func (r *liveRun) record(ctx context.Context, name, outcome string) error {
+ if err := r.s.SaveCheck(ctx, name, outcome); err != nil {
+ return err
+ }
+ if outcome != livePassed {
+ return errors.New("adopt: live-" + name + " " + outcome)
+ }
+ return nil
+}
+
+// connect signs a new connection in through the browser, asking connect
+// for liveScope alone. It is kept for close whatever happens.
+func (r *liveRun) connect(ctx context.Context) (*liveConn, error) {
+ l := newLiveConn()
+ r.conns = append(r.conns, l)
+ if err := l.c.Login(ctx, r.server, []string{liveScope}, r.open); err != nil {
+ return nil, errors.New("adopt: live-sign-in-failed")
+ }
+ return l, nil
+}
+
+// teamed reports whether l's connection lists the team; ok is false when
+// connect did not answer.
+func (r *liveRun) teamed(ctx context.Context, l *liveConn) (in, ok bool) {
+ info, err := l.c.Connection(ctx)
+ if err != nil {
+ return false, false
+ }
+ return slices.Contains(info.Teams, r.sqid), true
+}
+
+// signOut has connect revoke l and empties its store.
+func (r *liveRun) signOut(ctx context.Context, l *liveConn) error {
+ if l.out {
+ return nil
+ }
+ if err := l.c.Logout(ctx); err != nil {
+ return errLiveSignOut
+ }
+ l.out = true
+ return nil
+}
+
+// keep saves ex's request for replay and for zeroing.
+func (r *liveRun) keep(ex *exchange) *savedRequest {
+ c := ex.req
+ r.saved = append(r.saved, &c)
+ ex.req = savedRequest{}
+ return &c
+}
+
+func (r *liveRun) busyInput() []byte {
+ start := liveNow().UTC().Truncate(time.Minute)
+ b, _ := json.Marshal(map[string]string{
+ "team": r.sqid, "start": start.Format(time.RFC3339), "end": start.Add(7 * 24 * time.Hour).Format(time.RFC3339),
+ })
+ return b
+}
+
+func (r *liveRun) eventInput() []byte {
+ b, _ := json.Marshal(map[string]any{"team": r.sqid, "id": r.event})
+ return b
+}
+
+// replay sends c again exactly, with a plain client that follows no
+// redirect, and requires an authorization refusal: agent-access's 401
+// challenge or its 403. A bearer that had expired before the answer came
+// back proves nothing, and is inconclusive without being sent if it
+// already had.
+func (r *liveRun) replay(ctx context.Context, c *savedRequest) string {
+ if c.expiry.IsZero() || !liveNow().Before(c.expiry) {
+ return liveInconclusive
+ }
+ req, err := http.NewRequestWithContext(ctx, c.method, c.url, bytes.NewReader(c.body))
+ if err != nil {
+ return liveInconclusive
+ }
+ req.Header.Set("Authorization", "Bearer "+string(c.bearer))
+ req.Header.Set("Content-Type", "application/json")
+ h := &http.Client{Transport: liveBase(), Timeout: 30 * time.Second,
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ resp, err := h.Do(req)
+ if err != nil {
+ return liveInconclusive
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, client.MaxResponse+1))
+ resp.Body.Close()
+ if err != nil || !liveNow().Before(c.expiry) {
+ return liveInconclusive
+ }
+ return mustRefuse(answerOf(resp.StatusCode, resp.Header, body), ansUnauthenticated, ansForbidden)
+}
+
+func (r *liveRun) run(ctx context.Context) error {
+ // 1. non-member-refused: the test account, not yet a member, is
+ // refused a call to the team.
+ r.say(LiveSayTestSignIn)
+ a, err := r.connect(ctx)
+ if err != nil {
+ return errors.Join(err, r.record(ctx, "non-member-refused", liveInconclusive))
+ }
+ if in, ok := r.teamed(ctx, a); !ok || in {
+ return r.record(ctx, "non-member-refused", liveInconclusive)
+ }
+ ex := a.call(ctx, "calendar_free_busy", r.busyInput())
+ if err := r.record(ctx, "non-member-refused", mustRefuse(answerOfExchange(ex), ansUnauthenticated, ansForbidden, ansNotFound)); err != nil {
+ return err
+ }
+ if err := r.signOut(ctx, a); err != nil {
+ return err
+ }
+
+ // 2. Paul adds the member; the test account connects again and
+ // ticks the team.
+ if err := r.p.Ask(ctx, LiveAddedMember); err != nil {
+ return err
+ }
+ r.say(LiveSayTestTeam)
+ b, err := r.connect(ctx)
+ if err != nil {
+ return errors.Join(err, r.record(ctx, "member-allowed", liveInconclusive))
+ }
+ if in, ok := r.teamed(ctx, b); !ok || !in {
+ return r.record(ctx, "member-allowed", liveInconclusive)
+ }
+
+ // 3. member-allowed: the member's call succeeds, and is kept.
+ ex = b.call(ctx, "calendar_free_busy", r.busyInput())
+ if err := r.record(ctx, "member-allowed", mustSucceed(answerOfExchange(ex))); err != nil {
+ return err
+ }
+ c := r.keep(ex)
+
+ // 4. member-no-local-permission-refused: membership grants no local
+ // permission, so Paul's event stays out of reach.
+ ex = b.call(ctx, "calendar_get_event", r.eventInput())
+ if err := r.record(ctx, "member-no-local-permission-refused", mustRefuse(answerOfExchange(ex), ansForbidden, ansNotFound)); err != nil {
+ return err
+ }
+
+ // 5. revoked-membership-refused: once Paul removes the member, the
+ // same request, the same bearer, is refused.
+ if err := r.p.Ask(ctx, LiveRemovedMember); err != nil {
+ return err
+ }
+ if err := r.record(ctx, "revoked-membership-refused", r.replay(ctx, c)); err != nil {
+ return err
+ }
+ if err := r.signOut(ctx, b); err != nil {
+ return err
+ }
+
+ // 6. local-access-kept.
+ if err := r.p.Ask(ctx, LiveLocalAccessKept); err != nil {
+ return err
+ }
+ if err := r.record(ctx, "local-access-kept", livePassed); err != nil {
+ return err
+ }
+
+ // 7. owner-allowed and owner-revoked-refused, repeated with a fresh
+ // connection while the answer proves nothing either way.
+ for attempt := 1; ; attempt++ {
+ outcome, err := r.owner(ctx)
+ if err != nil {
+ return err
+ }
+ if outcome == livePassed {
+ break
+ }
+ if !strings.HasPrefix(outcome, "failed:") && attempt < liveOwnerAttempts {
+ continue
+ }
+ return errors.New("adopt: live-owner-revoked-refused " + outcome)
+ }
+
+ // owner-local-access-kept.
+ if err := r.p.Ask(ctx, LiveOwnerLocalAccessKept); err != nil {
+ return err
+ }
+ return r.record(ctx, "owner-local-access-kept", livePassed)
+}
+
+// owner is one attempt at step 7. It returns owner-revoked-refused's
+// outcome once recorded, or an error when the attempt stopped before it:
+// owner-allowed did not pass, or connect would not revoke.
+func (r *liveRun) owner(ctx context.Context) (string, error) {
+ r.say(LiveSayOwnerSignIn)
+ o, err := r.connect(ctx)
+ if err != nil {
+ return "", errors.Join(err, r.record(ctx, "owner-allowed", liveInconclusive))
+ }
+ if in, ok := r.teamed(ctx, o); !ok || !in {
+ return "", r.record(ctx, "owner-allowed", liveInconclusive)
+ }
+ ex := o.call(ctx, "calendar_free_busy", r.busyInput())
+ if err := r.record(ctx, "owner-allowed", mustSucceed(answerOfExchange(ex))); err != nil {
+ return "", err
+ }
+ c := r.keep(ex)
+ // At e4ea914 Logout revokes at connect, then deletes the store.
+ if err := r.signOut(ctx, o); err != nil {
+ return "", err
+ }
+ outcome := r.replay(ctx, c)
+ if err := r.s.SaveCheck(ctx, "owner-revoked-refused", outcome); err != nil {
+ return "", err
+ }
+ return outcome, nil
+}
+
+// close signs out every connection still open, on a context of its own so
+// a cancelled run still revokes, then zeroes every saved request and
+// token. A connection connect would not revoke is errLiveSignOut.
+func (r *liveRun) close() error {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ var failed bool
+ for _, l := range r.conns {
+ if l.out {
+ continue
+ }
+ if _, err := l.store.Load(); err != nil {
+ // Never connected: nothing to revoke.
+ l.out = true
+ continue
+ }
+ if r.signOut(ctx, l) != nil {
+ failed = true
+ }
+ l.store.Delete()
+ }
+ for _, c := range r.saved {
+ c.zero()
+ }
+ for _, l := range r.conns {
+ if l.rec.last != nil {
+ l.rec.last.req.zero()
+ l.rec.last = nil
+ }
+ l.store.Delete()
+ }
+ r.conns, r.saved = nil, nil
+ if failed {
+ return errLiveSignOut
+ }
+ return nil
+}
+
+var _ client.Store = (*MemoryStore)(nil)
diff --git a/adopt/live_test.go b/adopt/live_test.go
new file mode 100644
index 0000000..7244ce6
--- /dev/null
+++ b/adopt/live_test.go
@@ -0,0 +1,1007 @@
+package adopt
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/agent-access.git/client"
+ "golang.org/x/oauth2"
+)
+
+const (
+ liveSQID = "tsqidcanary7x"
+ liveEvent = "424242"
+ subjTest = "test-account"
+ subjOwner = "owner"
+ freeBusy = "calendar_free_busy"
+ getEvent = "calendar_get_event"
+)
+
+// liveOp is one operations request as the fake connect received it.
+type liveOp struct {
+ name, method, path, bearer string
+ body []byte
+ token int // index of the bearer in issued, -1 unknown
+}
+
+type fakeToken struct {
+ index int
+ subject string
+ teams []string
+ revoked bool
+}
+
+// fakeConnect is oficina-connect as the live checks meet it: OAuth
+// metadata, the token and revoke endpoints, the connection and the
+// operations, and membership of the one team, changed by Paul's prompts.
+type fakeConnect struct {
+ t *testing.T
+ srv *httptest.Server
+ mu sync.Mutex
+
+ members map[string]bool
+ logins []string // who signs in at each successive browser open
+ codes map[string]string
+ tokens map[string]*fakeToken
+ issued []string
+ ops []liveOp
+ events []string
+ paths []string
+ skew atomic.Int64
+
+ // Breaks.
+ nonMemberAllowed, foreignReadable, membershipNotEnforced, revokeNotEnforced, memberRefused bool
+ // answer, when it returns a status, answers an operation instead
+ // with that status and agent-access error code. It runs under mu.
+ answer func(op liveOp) (int, string)
+ onRevoke func(index int)
+ onToken func(index int, subject string)
+ revokeOK func(index int) bool
+}
+
+func newFakeConnect(t *testing.T) *fakeConnect {
+ f := &fakeConnect{
+ t: t,
+ members: map[string]bool{subjOwner: true},
+ logins: []string{subjTest, subjTest, subjOwner},
+ codes: map[string]string{},
+ tokens: map[string]*fakeToken{},
+ }
+ f.srv = httptest.NewTLSServer(f)
+ t.Cleanup(f.srv.Close)
+ return f
+}
+
+func randHex() string {
+ var b [16]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ panic(err)
+ }
+ return hex.EncodeToString(b[:])
+}
+
+func writeJSONTest(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+// agentFail answers as agent-access does: no-store, the Bearer challenge
+// on a 401, and {"error":{"code":…}}.
+func (f *fakeConnect) agentFail(w http.ResponseWriter, status int, code string) {
+ w.Header().Set("Cache-Control", "no-store")
+ if status == http.StatusUnauthorized {
+ w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="`+f.srv.URL+`/.well-known/oauth-protected-resource"`)
+ }
+ writeJSONTest(w, status, map[string]any{"error": map[string]string{"code": code, "message": "message-canary"}})
+}
+
+func (f *fakeConnect) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.paths = append(f.paths, r.Method+" "+r.URL.Path)
+ switch {
+ case r.Method == "GET" && r.URL.Path == "/.well-known/oauth-authorization-server":
+ writeJSONTest(w, 200, map[string]any{
+ "issuer": f.srv.URL, "authorization_endpoint": f.srv.URL + "/oauth/authorize",
+ "token_endpoint": f.srv.URL + "/oauth/token", "code_challenge_methods_supported": []string{"S256"},
+ "scopes_supported": []string{"calendar:read", "docs:read"},
+ })
+ case r.Method == "POST" && r.URL.Path == "/oauth/token":
+ _ = r.ParseForm()
+ subject, ok := f.codes[r.PostForm.Get("code")]
+ delete(f.codes, r.PostForm.Get("code"))
+ if !ok || r.PostForm.Get("code_verifier") == "" {
+ writeJSONTest(w, 400, map[string]string{"error": "invalid_grant"})
+ return
+ }
+ teams := []string{"team-other"}
+ if f.members[subject] {
+ teams = append(teams, liveSQID)
+ }
+ tok := "bearer-canary-" + randHex()
+ ft := &fakeToken{index: len(f.issued), subject: subject, teams: teams}
+ f.tokens[tok] = ft
+ f.issued = append(f.issued, tok)
+ f.events = append(f.events, "token:"+subject)
+ if f.onToken != nil {
+ f.onToken(ft.index, subject)
+ }
+ writeJSONTest(w, 200, map[string]any{"access_token": tok, "token_type": "Bearer", "expires_in": 300, "scope": "calendar:read"})
+ case r.Method == "POST" && r.URL.Path == "/oauth/revoke":
+ _ = r.ParseForm()
+ ft := f.tokens[r.PostForm.Get("token")]
+ if ft == nil || r.PostForm.Get("client_id") != "oficina-cli" {
+ writeJSONTest(w, 400, map[string]string{"error": "invalid_request"})
+ return
+ }
+ if f.revokeOK != nil && !f.revokeOK(ft.index) {
+ writeJSONTest(w, 503, map[string]string{"error": "temporarily_unavailable"})
+ return
+ }
+ ft.revoked = true
+ f.events = append(f.events, "revoke:"+strconv.Itoa(ft.index))
+ if f.onRevoke != nil {
+ f.onRevoke(ft.index)
+ }
+ w.WriteHeader(200)
+ case r.Method == "GET" && r.URL.Path == "/api/v1/connection":
+ p := f.verify(w, r)
+ if p == nil {
+ return
+ }
+ writeJSONTest(w, 200, map[string]any{"teams": f.teamsOf(p), "scopes": []string{"calendar:read"}})
+ case r.Method == "POST" && strings.HasPrefix(r.URL.Path, "/api/v1/operations/"):
+ body, _ := io.ReadAll(r.Body)
+ op := liveOp{name: strings.TrimPrefix(r.URL.Path, "/api/v1/operations/"), method: r.Method, path: r.URL.String(),
+ bearer: r.Header.Get("Authorization"), body: body, token: -1}
+ if ft := f.tokens[strings.TrimPrefix(op.bearer, "Bearer ")]; ft != nil {
+ op.token = ft.index
+ }
+ f.ops = append(f.ops, op)
+ f.events = append(f.events, "op:"+op.name+":"+strconv.Itoa(op.token))
+ if f.answer != nil {
+ if status, code := f.answer(op); status != 0 {
+ switch {
+ case status >= 300 && status < 400:
+ w.Header().Set("Location", f.srv.URL+"/followed")
+ w.WriteHeader(status)
+ case code == "plain":
+ // An app's own refusal: no challenge, no agent body.
+ w.WriteHeader(status)
+ io.WriteString(w, "Unauthorized\n")
+ default:
+ f.agentFail(w, status, code)
+ }
+ return
+ }
+ }
+ p := f.verify(w, r)
+ if p == nil {
+ return
+ }
+ var in struct {
+ Team string `json:"team"`
+ ID json.Number
+ }
+ if json.Unmarshal(body, &in) != nil || r.Header.Get("Content-Type") != "application/json" {
+ f.agentFail(w, 422, "invalid")
+ return
+ }
+ if !slices.Contains(f.teamsOf(p), in.Team) && !f.nonMemberAllowed {
+ f.agentFail(w, 403, "forbidden")
+ return
+ }
+ switch op.name {
+ case freeBusy:
+ if f.memberRefused && p.subject == subjTest {
+ f.agentFail(w, 403, "forbidden")
+ return
+ }
+ writeJSONTest(w, 200, map[string]any{"tz": "tz-canary", "busy": []any{}})
+ case getEvent:
+ if in.ID.String() == liveEvent && !f.foreignReadable {
+ f.agentFail(w, 404, "not_found")
+ return
+ }
+ writeJSONTest(w, 200, map[string]any{"id": in.ID, "title": "title-canary"})
+ default:
+ f.agentFail(w, 404, "not_found")
+ }
+ default:
+ http.NotFound(w, r)
+ }
+}
+
+// verify is connect's grant check: a known, unrevoked bearer whose
+// person still belongs to one of the teams it ticked.
+func (f *fakeConnect) verify(w http.ResponseWriter, r *http.Request) *fakeToken {
+ ft := f.tokens[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
+ if ft == nil || ft.revoked && !f.revokeNotEnforced || len(f.teamsOf(ft)) == 0 {
+ f.agentFail(w, 401, "unauthenticated")
+ return nil
+ }
+ return ft
+}
+
+func (f *fakeConnect) teamsOf(ft *fakeToken) []string {
+ out := []string{}
+ for _, team := range ft.teams {
+ if team == liveSQID && !f.members[ft.subject] && !f.membershipNotEnforced {
+ continue
+ }
+ out = append(out, team)
+ }
+ return out
+}
+
+// open is the system browser: whoever the script says signs in, ticks
+// every team they belong to, and is sent back to the CLI's callback.
+func (f *fakeConnect) open(raw string) error {
+ u, err := url.Parse(raw)
+ if err != nil {
+ return err
+ }
+ q := u.Query()
+ f.mu.Lock()
+ if len(f.logins) == 0 {
+ f.mu.Unlock()
+ f.t.Errorf("unscripted sign-in")
+ return errors.New("no one to sign in")
+ }
+ subject := f.logins[0]
+ f.logins = f.logins[1:]
+ code := randHex()
+ f.codes[code] = subject
+ f.events = append(f.events, "login:"+subject)
+ f.mu.Unlock()
+ if q.Get("code_challenge") == "" || q.Get("scope") != "calendar:read" {
+ f.t.Errorf("sign-in asked for %q without PKCE or with other scopes", q.Get("scope"))
+ }
+ cb := q.Get("redirect_uri") + "?" + url.Values{"code": {code}, "state": {q.Get("state")}, "iss": {f.srv.URL}}.Encode()
+ resp, err := http.Get(cb)
+ if err != nil {
+ return err
+ }
+ resp.Body.Close()
+ if resp.StatusCode != 200 {
+ return errors.New("callback refused")
+ }
+ return nil
+}
+
+func (f *fakeConnect) setMember(subject string, in bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.members[subject] = in
+ f.events = append(f.events, "member:"+subject+":"+map[bool]string{true: "added", false: "removed"}[in])
+}
+
+// state copies what the fake saw.
+func (f *fakeConnect) state() (ops []liveOp, events, issued, paths []string, revoked map[int]bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ revoked = map[int]bool{}
+ for _, ft := range f.tokens {
+ if ft.revoked {
+ revoked[ft.index] = true
+ }
+ }
+ return slices.Clone(f.ops), slices.Clone(f.events), slices.Clone(f.issued), slices.Clone(f.paths), revoked
+}
+
+type fakePrompter struct {
+ f *fakeConnect
+ asked []string
+ failOn string
+ cancel context.CancelFunc
+ onAsk func(string)
+}
+
+func (p *fakePrompter) Ask(ctx context.Context, sentence string) error {
+ p.asked = append(p.asked, sentence)
+ if sentence == p.failOn {
+ if p.cancel != nil {
+ p.cancel()
+ return ctx.Err()
+ }
+ return errors.New("declined")
+ }
+ switch sentence {
+ case LiveAddedMember:
+ p.f.setMember(subjTest, true)
+ case LiveRemovedMember:
+ p.f.setMember(subjTest, false)
+ }
+ if p.onAsk != nil {
+ p.onAsk(sentence)
+ }
+ return nil
+}
+
+type liveFixture struct {
+ f *fakeConnect
+ p *fakePrompter
+ s *Store
+ out *bytes.Buffer
+}
+
+func newLive(t *testing.T) *liveFixture {
+ t.Helper()
+ f := newFakeConnect(t)
+ x := &liveFixture{f: f, p: &fakePrompter{f: f}, s: newJournal(t), out: &bytes.Buffer{}}
+ oldT, oldNow, oldOut := liveTransport, liveNow, liveOut
+ liveTransport = f.srv.Client().Transport
+ liveNow = func() time.Time { return time.Now().Add(time.Duration(f.skew.Load())) }
+ liveOut = x.out
+ t.Cleanup(func() { liveTransport, liveNow, liveOut = oldT, oldNow, oldOut })
+ return x
+}
+
+func (x *liveFixture) run(t *testing.T) error {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ x.p.cancel = nil
+ return RunLive(ctx, x.f.srv.URL, liveSQID, x.p, x.s, x.f.open, liveEvent, true)
+}
+
+// checks lists the journal's live checks in the order recorded.
+func checks(t *testing.T, s *Store) []string {
+ t.Helper()
+ rows, err := s.db.QueryContext(context.Background(), "SELECT name, outcome FROM adopt_checks ORDER BY id")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var n, o string
+ if err := rows.Scan(&n, &o); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, n+"="+o)
+ }
+ return out
+}
+
+func wantChecks(t *testing.T, s *Store, want ...string) {
+ t.Helper()
+ if got := checks(t, s); !slices.Equal(got, want) {
+ t.Fatalf("checks:\n got %q\nwant %q", got, want)
+ }
+}
+
+// allRevoked fails unless connect revoked every bearer it issued.
+func allRevoked(t *testing.T, f *fakeConnect) {
+ t.Helper()
+ _, _, issued, _, revoked := f.state()
+ if len(issued) == 0 {
+ t.Fatal("no connection was made")
+ }
+ for i := range issued {
+ if !revoked[i] {
+ t.Fatalf("connection %d of %d left connected", i+1, len(issued))
+ }
+ }
+}
+
+func gateClosed(t *testing.T, s *Store) {
+ t.Helper()
+ if err := s.LiveGate(context.Background(), "docs"); !errors.Is(err, ErrLiveChecksMissing) {
+ t.Fatalf("Plan C gate open: %v", err)
+ }
+}
+
+var everyCheckPassed = []string{
+ "non-member-refused=passed", "member-allowed=passed", "member-no-local-permission-refused=passed",
+ "revoked-membership-refused=passed", "local-access-kept=passed", "owner-allowed=passed",
+ "owner-revoked-refused=passed", "owner-local-access-kept=passed",
+}
+
+func TestLivePassesEveryCheck(t *testing.T) {
+ x := newLive(t)
+ if err := x.run(t); err != nil {
+ t.Fatal(err)
+ }
+ wantChecks(t, x.s, everyCheckPassed...)
+ if err := x.s.LiveGate(context.Background(), "docs"); err != nil {
+ t.Fatalf("gate after every check passed: %v", err)
+ }
+ want := []string{LiveAddedMember, LiveRemovedMember, LiveLocalAccessKept, LiveOwnerLocalAccessKept}
+ if !slices.Equal(x.p.asked, want) {
+ t.Fatalf("asked %q, want %q", x.p.asked, want)
+ }
+ allRevoked(t, x.f)
+}
+
+func TestLiveFailsWhenNonMemberSucceeds(t *testing.T) {
+ x := newLive(t)
+ x.f.nonMemberAllowed = true
+ if err := x.run(t); err == nil {
+ t.Fatal("a non-member's call succeeded and the run went on")
+ }
+ wantChecks(t, x.s, "non-member-refused=failed:allowed")
+ if len(x.p.asked) != 0 {
+ t.Fatalf("asked %q after the failure", x.p.asked)
+ }
+ gateClosed(t, x.s)
+ allRevoked(t, x.f)
+}
+
+func TestLiveRefusesNonMemberCheckWhenAlreadyMember(t *testing.T) {
+ x := newLive(t)
+ x.f.members[subjTest] = true
+ if err := x.run(t); err == nil {
+ t.Fatal("the non-member check ran on a member")
+ }
+ wantChecks(t, x.s, "non-member-refused=inconclusive")
+ ops, _, _, _, _ := x.f.state()
+ if len(ops) != 0 {
+ t.Fatalf("a member's call was made as the non-member check: %d", len(ops))
+ }
+ allRevoked(t, x.f)
+}
+
+func TestLiveFailsWhenMemberCannotCallBeforeRemoval(t *testing.T) {
+ x := newLive(t)
+ x.f.memberRefused = true
+ if err := x.run(t); err == nil {
+ t.Fatal("the member's refused call was not a failure")
+ }
+ wantChecks(t, x.s, "non-member-refused=passed", "member-allowed=failed:forbidden")
+ if !slices.Equal(x.p.asked, []string{LiveAddedMember}) {
+ t.Fatalf("later steps ran: asked %q", x.p.asked)
+ }
+ ops, _, _, _, _ := x.f.state()
+ for _, op := range ops[2:] {
+ t.Fatalf("a later step called %s", op.name)
+ }
+ gateClosed(t, x.s)
+ allRevoked(t, x.f)
+}
+
+func TestLiveFailsWhenForeignEventReadable(t *testing.T) {
+ x := newLive(t)
+ x.f.foreignReadable = true
+ if err := x.run(t); err == nil {
+ t.Fatal("a readable foreign event was not a failure")
+ }
+ wantChecks(t, x.s, "non-member-refused=passed", "member-allowed=passed", "member-no-local-permission-refused=failed:allowed")
+ if slices.Contains(x.p.asked, LiveRemovedMember) {
+ t.Fatal("went on to the removal")
+ }
+ gateClosed(t, x.s)
+ allRevoked(t, x.f)
+}
+
+// Only forbidden or not_found, in agent-access's own body, proves the
+// event refused; anything else is inconclusive and stops the run.
+func TestLiveForeignEventRefusalCodes(t *testing.T) {
+ for _, tc := range []struct {
+ status int
+ code, want string
+ }{
+ {403, "forbidden", "passed"}, {404, "not_found", "passed"},
+ {403, "invalid", "inconclusive"}, {401, "unauthenticated", "inconclusive"},
+ {503, "unavailable", "inconclusive"}, {422, "invalid", "inconclusive"},
+ } {
+ t.Run(strconv.Itoa(tc.status)+"-"+tc.code, func(t *testing.T) {
+ x := newLive(t)
+ x.f.answer = func(op liveOp) (int, string) {
+ if op.name == getEvent {
+ return tc.status, tc.code
+ }
+ return 0, ""
+ }
+ err := x.run(t)
+ got := checks(t, x.s)
+ if len(got) < 3 || got[2] != "member-no-local-permission-refused="+tc.want {
+ t.Fatalf("recorded %q, want %s", got, tc.want)
+ }
+ if tc.want == "passed" && err != nil {
+ t.Fatal(err)
+ }
+ if tc.want != "passed" && (err == nil || len(got) != 3) {
+ t.Fatalf("an inconclusive check did not stop the run: %v %q", err, got)
+ }
+ allRevoked(t, x.f)
+ })
+ }
+}
+
+func TestLiveFailsWhenRevocationNotEnforced(t *testing.T) {
+ x := newLive(t)
+ x.f.membershipNotEnforced = true
+ if err := x.run(t); err == nil {
+ t.Fatal("a removed member's connection still worked and the run went on")
+ }
+ wantChecks(t, x.s, "non-member-refused=passed", "member-allowed=passed",
+ "member-no-local-permission-refused=passed", "revoked-membership-refused=failed:allowed")
+ if slices.Contains(x.p.asked, LiveLocalAccessKept) {
+ t.Fatal("went on to the local access sentence")
+ }
+ gateClosed(t, x.s)
+ allRevoked(t, x.f)
+}
+
+// The membership check replays the member's own request, the same bearer
+// and body, after the removal; the owner check does the same after the
+// revoke.
+func TestLiveRepeatsExactRequest(t *testing.T) {
+ x := newLive(t)
+ if err := x.run(t); err != nil {
+ t.Fatal(err)
+ }
+ ops, events, issued, _, _ := x.f.state()
+ if len(issued) != 3 {
+ t.Fatalf("%d connections, want 3", len(issued))
+ }
+ for _, tok := range []int{1, 2} {
+ var same []liveOp
+ for _, op := range ops {
+ if op.token == tok && op.name == freeBusy {
+ same = append(same, op)
+ }
+ }
+ if len(same) != 2 {
+ t.Fatalf("connection %d: %d free/busy calls, want the call and its replay", tok, len(same))
+ }
+ a, b := same[0], same[1]
+ if a.method != b.method || a.path != b.path || a.bearer != b.bearer || !bytes.Equal(a.body, b.body) {
+ t.Fatalf("connection %d: the replay differs from the call", tok)
+ }
+ if a.bearer != "Bearer "+issued[tok] {
+ t.Fatalf("connection %d: the call was not made with its own bearer", tok)
+ }
+ var in map[string]any
+ if json.Unmarshal(a.body, &in) != nil || in["team"] != liveSQID || in["start"] == nil || in["end"] == nil {
+ t.Fatalf("connection %d: the call is not the team's free/busy", tok)
+ }
+ }
+ // The member's replay follows the removal.
+ removed := slices.Index(events, "member:"+subjTest+":removed")
+ var calls []int
+ for i, e := range events {
+ if e == "op:"+freeBusy+":1" {
+ calls = append(calls, i)
+ }
+ }
+ if removed < 0 || len(calls) != 2 || !(calls[0] < removed && removed < calls[1]) {
+ t.Fatalf("the member's replay is not after the removal: %q", events)
+ }
+}
+
+func TestLiveOwnerRevokeReplaysSavedRequest(t *testing.T) {
+ x := newLive(t)
+ // The first replay is redirected; the runner must not follow it, and
+ // repeats with a fresh connection.
+ x.f.answer = func(op liveOp) (int, string) {
+ if op.token == 2 && slices.Contains(x.f.events, "revoke:2") {
+ return http.StatusFound, ""
+ }
+ return 0, ""
+ }
+ x.f.logins = append(x.f.logins, subjOwner)
+ if err := x.run(t); err != nil {
+ t.Fatal(err)
+ }
+ wantChecks(t, x.s, append(everyCheckPassed[:6:6],
+ "owner-revoked-refused=inconclusive", "owner-allowed=passed",
+ "owner-revoked-refused=passed", "owner-local-access-kept=passed")...)
+ _, events, _, paths, _ := x.f.state()
+ if slices.Contains(paths, "GET /followed") || slices.Contains(paths, "POST /followed") {
+ t.Fatal("the replay followed a redirect")
+ }
+ // Each owner connection: its call, then the revoke, then the replay.
+ for _, tok := range []string{"2", "3"} {
+ i := slices.Index(events, "op:"+freeBusy+":"+tok)
+ r := slices.Index(events, "revoke:"+tok)
+ j := slices.Index(events[i+1:], "op:"+freeBusy+":"+tok)
+ if i < 0 || r < i || j < 0 || i+1+j < r {
+ t.Fatalf("owner connection %s: call, revoke and replay out of order: %q", tok, events)
+ }
+ }
+ allRevoked(t, x.f)
+}
+
+func TestLiveFailsWhenRevokeLeavesAccessValid(t *testing.T) {
+ x := newLive(t)
+ x.f.revokeNotEnforced = true
+ if err := x.run(t); err == nil {
+ t.Fatal("a revoked connection still worked and the run went on")
+ }
+ wantChecks(t, x.s, append(everyCheckPassed[:6:6], "owner-revoked-refused=failed:allowed")...)
+ if slices.Contains(x.p.asked, LiveOwnerLocalAccessKept) {
+ t.Fatal("went on to the owner's local access sentence")
+ }
+ gateClosed(t, x.s)
+}
+
+// A replay made after the bearer expired proves nothing: it is
+// inconclusive, and the owner's step repeats with a fresh connection.
+func TestLiveReplayAfterExpiryIsInconclusive(t *testing.T) {
+ t.Run("owner", func(t *testing.T) {
+ x := newLive(t)
+ x.f.logins = append(x.f.logins, subjOwner)
+ x.f.onRevoke = func(i int) {
+ if i == 2 {
+ x.f.skew.Store(int64(time.Hour))
+ }
+ }
+ x.f.onToken = func(i int, _ string) {
+ if i == 3 {
+ x.f.skew.Store(0)
+ }
+ }
+ if err := x.run(t); err != nil {
+ t.Fatal(err)
+ }
+ wantChecks(t, x.s, append(everyCheckPassed[:6:6],
+ "owner-revoked-refused=inconclusive", "owner-allowed=passed",
+ "owner-revoked-refused=passed", "owner-local-access-kept=passed")...)
+ ops, _, _, _, _ := x.f.state()
+ n := 0
+ for _, op := range ops {
+ if op.token == 2 {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Fatalf("the expired bearer was replayed: %d calls", n)
+ }
+ allRevoked(t, x.f)
+ })
+ t.Run("member", func(t *testing.T) {
+ x := newLive(t)
+ x.p.onAsk = func(s string) {
+ if s == LiveRemovedMember {
+ x.f.skew.Store(int64(time.Hour))
+ }
+ }
+ if err := x.run(t); err == nil {
+ t.Fatal("an expired replay did not stop the run")
+ }
+ wantChecks(t, x.s, "non-member-refused=passed", "member-allowed=passed",
+ "member-no-local-permission-refused=passed", "revoked-membership-refused=inconclusive")
+ ops, _, _, _, _ := x.f.state()
+ n := 0
+ for _, op := range ops {
+ if op.token == 1 && op.name == freeBusy {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Fatalf("the expired bearer was replayed: %d calls", n)
+ }
+ gateClosed(t, x.s)
+ allRevoked(t, x.f)
+ })
+ t.Run("unavailable", func(t *testing.T) {
+ x := newLive(t)
+ x.f.logins = append(x.f.logins, subjOwner)
+ x.f.answer = func(op liveOp) (int, string) {
+ if op.token == 2 && x.f.tokens[strings.TrimPrefix(op.bearer, "Bearer ")].revoked {
+ return 503, "unavailable"
+ }
+ return 0, ""
+ }
+ if err := x.run(t); err != nil {
+ t.Fatal(err)
+ }
+ wantChecks(t, x.s, append(everyCheckPassed[:6:6],
+ "owner-revoked-refused=inconclusive", "owner-allowed=passed",
+ "owner-revoked-refused=passed", "owner-local-access-kept=passed")...)
+ })
+ t.Run("bounded", func(t *testing.T) {
+ x := newLive(t)
+ for range liveOwnerAttempts {
+ x.f.logins = append(x.f.logins, subjOwner)
+ }
+ x.f.answer = func(op liveOp) (int, string) {
+ if op.token >= 2 && x.f.tokens[strings.TrimPrefix(op.bearer, "Bearer ")].revoked {
+ return 503, "unavailable"
+ }
+ return 0, ""
+ }
+ if err := x.run(t); err == nil {
+ t.Fatal("the owner step repeated without end")
+ }
+ got := checks(t, x.s)
+ n := 0
+ for _, c := range got {
+ if c == "owner-revoked-refused=inconclusive" {
+ n++
+ }
+ }
+ if n != liveOwnerAttempts || slices.Contains(got, "owner-revoked-refused=passed") {
+ t.Fatalf("checks %q", got)
+ }
+ _, _, issued, _, _ := x.f.state()
+ if len(issued) != 2+liveOwnerAttempts {
+ t.Fatalf("%d connections, want a fresh one per attempt", len(issued))
+ }
+ gateClosed(t, x.s)
+ allRevoked(t, x.f)
+ })
+}
+
+// The member's replay passes only on agent-access's own refusal: its 401
+// challenge or its forbidden 403. A 2xx fails; anything else proves
+// nothing, and so does an answer that came back after the bearer expired.
+func TestLiveReplayRefusalShape(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status int
+ code, want string
+ expireDuring bool
+ }{
+ {"challenge", 401, "unauthenticated", "passed", false},
+ {"forbidden", 403, "forbidden", "passed", false},
+ {"app 401", 401, "plain", "inconclusive", false},
+ {"401 other body", 401, "forbidden", "inconclusive", false},
+ {"403 other code", 403, "not_found", "inconclusive", false},
+ {"not found", 404, "not_found", "inconclusive", false},
+ {"unavailable", 503, "unavailable", "inconclusive", false},
+ {"expired while answering", 401, "unauthenticated", "inconclusive", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ x := newLive(t)
+ x.f.answer = func(op liveOp) (int, string) {
+ if op.token == 1 && op.name == freeBusy && !x.f.members[subjTest] {
+ if tc.expireDuring {
+ x.f.skew.Store(int64(time.Hour))
+ }
+ return tc.status, tc.code
+ }
+ return 0, ""
+ }
+ err := x.run(t)
+ got := checks(t, x.s)
+ if len(got) < 4 || got[3] != "revoked-membership-refused="+tc.want {
+ t.Fatalf("recorded %q, want %s", got, tc.want)
+ }
+ if tc.want != "passed" && (err == nil || len(got) != 4) {
+ t.Fatalf("an inconclusive replay did not stop the run: %v", err)
+ }
+ allRevoked(t, x.f)
+ })
+ }
+}
+
+// close zeroes every saved request and forgets every token, signed out
+// or not.
+func TestLiveCloseZeroes(t *testing.T) {
+ body, bearer := []byte("body-canary"), []byte("bearer-canary")
+ c := &savedRequest{method: "POST", url: "https://connect.oficina.works/api/v1/operations/x", body: body, bearer: bearer, expiry: time.Now()}
+ l := newLiveConn()
+ l.out = true
+ _ = l.store.Save(client.Credentials{Token: &oauth2.Token{AccessToken: "bearer-canary-2"}})
+ r := &liveRun{conns: []*liveConn{l}, saved: []*savedRequest{c}}
+ if err := r.close(); err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(body, make([]byte, len(body))) || !bytes.Equal(bearer, make([]byte, len(bearer))) {
+ t.Fatal("a saved request was not zeroed")
+ }
+ if c.method != "" || c.url != "" || !c.expiry.IsZero() {
+ t.Fatal("a saved request kept its target")
+ }
+ if _, err := l.store.Load(); err == nil {
+ t.Fatal("a token outlived the run")
+ }
+}
+
+var outcomeShape = regexp.MustCompile(`^(passed|inconclusive|failed:[a-z_-]+)$`)
+
+func TestLiveRecordsCodesOnly(t *testing.T) {
+ for name, brk := range map[string]func(*fakeConnect){
+ "pass": func(*fakeConnect) {},
+ "non-member": func(f *fakeConnect) { f.nonMemberAllowed = true },
+ "member-refused": func(f *fakeConnect) { f.memberRefused = true },
+ "foreign": func(f *fakeConnect) { f.foreignReadable = true },
+ "membership": func(f *fakeConnect) { f.membershipNotEnforced = true },
+ "revoke": func(f *fakeConnect) { f.revokeNotEnforced = true },
+ } {
+ t.Run(name, func(t *testing.T) {
+ x := newLive(t)
+ brk(x.f)
+ err := x.run(t)
+ var dump strings.Builder
+ rows, qerr := x.s.db.Query("SELECT * FROM adopt_checks")
+ if qerr != nil {
+ t.Fatal(qerr)
+ }
+ cols, _ := rows.Columns()
+ for rows.Next() {
+ vals := make([]any, len(cols))
+ ptrs := make([]any, len(cols))
+ for i := range vals {
+ ptrs[i] = &vals[i]
+ }
+ if err := rows.Scan(ptrs...); err != nil {
+ t.Fatal(err)
+ }
+ for _, v := range vals {
+ dump.WriteString(jsonAny(v) + " ")
+ }
+ }
+ rows.Close()
+ for _, c := range checks(t, x.s) {
+ if !outcomeShape.MatchString(strings.SplitN(c, "=", 2)[1]) {
+ t.Fatalf("outcome %q is not a fixed code", c)
+ }
+ }
+ everything := dump.String() + x.out.String()
+ if err != nil {
+ everything += err.Error()
+ }
+ _, _, issued, _, _ := x.f.state()
+ secrets := append([]string{liveSQID, liveEvent, x.f.srv.URL, "127.0.0.1", "bearer-canary", "message-canary", "tz-canary", "title-canary"}, issued...)
+ for _, s := range secrets {
+ if strings.Contains(everything, s) {
+ t.Fatalf("recorded or printed %q", s)
+ }
+ }
+ })
+ }
+}
+
+func jsonAny(v any) string {
+ if b, ok := v.([]byte); ok {
+ return string(b)
+ }
+ b, _ := json.Marshal(v)
+ return string(b)
+}
+
+func TestLiveAlwaysLogsOut(t *testing.T) {
+ t.Run("member refused", func(t *testing.T) {
+ x := newLive(t)
+ x.f.memberRefused = true
+ _ = x.run(t)
+ allRevoked(t, x.f)
+ })
+ t.Run("removal declined", func(t *testing.T) {
+ x := newLive(t)
+ x.p.failOn = LiveRemovedMember
+ if err := x.run(t); err == nil {
+ t.Fatal("a declined prompt went on")
+ }
+ allRevoked(t, x.f)
+ })
+ t.Run("cancelled at the removal", func(t *testing.T) {
+ x := newLive(t)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ x.p.failOn = LiveRemovedMember
+ x.p.cancel = cancel
+ if err := RunLive(ctx, x.f.srv.URL, liveSQID, x.p, x.s, x.f.open, liveEvent, true); err == nil {
+ t.Fatal("a cancelled run went on")
+ }
+ allRevoked(t, x.f)
+ })
+ t.Run("revoke fails once", func(t *testing.T) {
+ x := newLive(t)
+ var refused atomic.Bool
+ x.f.revokeOK = func(i int) bool {
+ if i == 0 && !refused.Load() {
+ refused.Store(true)
+ return false
+ }
+ return true
+ }
+ if err := x.run(t); err == nil {
+ t.Fatal("a failed revoke went unreported")
+ }
+ allRevoked(t, x.f)
+ })
+ t.Run("revoke never succeeds", func(t *testing.T) {
+ x := newLive(t)
+ x.f.revokeOK = func(i int) bool { return i != 0 }
+ err := x.run(t)
+ if err == nil || !strings.Contains(err.Error(), "live-sign-out-failed") {
+ t.Fatalf("an unrevoked connection was not reported: %v", err)
+ }
+ })
+}
+
+func TestLiveDryRunContactsNothing(t *testing.T) {
+ x := newLive(t)
+ open := func(string) error { t.Fatal("dry run opened a browser"); return nil }
+ p := askFunc(func(context.Context, string) error { t.Fatal("dry run asked Paul"); return nil })
+ if err := RunLive(context.Background(), x.f.srv.URL, liveSQID, p, x.s, open, liveEvent, false); err != nil {
+ t.Fatal(err)
+ }
+ if err := RunLive(context.Background(), x.f.srv.URL, liveSQID, p, nil, open, liveEvent, false); err != nil {
+ t.Fatalf("dry run needs the journal: %v", err)
+ }
+ _, _, _, paths, _ := x.f.state()
+ if len(paths) != 0 {
+ t.Fatalf("dry run contacted connect: %q", paths)
+ }
+ wantChecks(t, x.s)
+ want := strings.Join(LiveSteps, "\n") + "\n"
+ if x.out.String() != want+want {
+ t.Fatalf("dry run printed %q", x.out.String())
+ }
+}
+
+type askFunc func(context.Context, string) error
+
+func (f askFunc) Ask(ctx context.Context, s string) error { return f(ctx, s) }
+
+func TestLiveRefusesBadInputs(t *testing.T) {
+ x := newLive(t)
+ open := func(string) error { t.Fatal("opened a browser"); return nil }
+ for name, tc := range map[string]struct{ server, sqid, event string }{
+ "http server": {"http://connect.oficina.works", liveSQID, liveEvent},
+ "server path": {"https://connect.oficina.works/x", liveSQID, liveEvent},
+ "no server": {"", liveSQID, liveEvent},
+ "no sqid": {x.f.srv.URL, "", liveEvent},
+ "event zero": {x.f.srv.URL, liveSQID, "0"},
+ "event negative": {x.f.srv.URL, liveSQID, "-4"},
+ "event text": {x.f.srv.URL, liveSQID, "abc"},
+ "event spaced": {x.f.srv.URL, liveSQID, " 4"},
+ } {
+ for _, apply := range []bool{false, true} {
+ if err := RunLive(context.Background(), tc.server, tc.sqid, x.p, x.s, open, tc.event, apply); err == nil {
+ t.Fatalf("%s (apply %v) accepted", name, apply)
+ }
+ }
+ }
+ if err := RunLive(context.Background(), x.f.srv.URL, liveSQID, nil, x.s, open, liveEvent, true); err == nil {
+ t.Fatal("ran with no prompter")
+ }
+ if err := RunLive(context.Background(), x.f.srv.URL, liveSQID, x.p, nil, open, liveEvent, true); err == nil {
+ t.Fatal("ran with no journal")
+ }
+ _, _, _, paths, _ := x.f.state()
+ if len(paths) != 0 || x.out.Len() != 0 {
+ t.Fatalf("a refused run contacted connect or printed: %q %q", paths, x.out.String())
+ }
+}
+
+// MemoryStore keeps the credentials in memory only, hands out copies,
+// and forgets them on Delete.
+func TestLiveMemoryStore(t *testing.T) {
+ var m MemoryStore
+ if _, err := m.Load(); err == nil {
+ t.Fatal("an empty store loaded")
+ }
+ tok := &oauth2.Token{AccessToken: "bearer-canary-store", Expiry: time.Now().Add(time.Minute)}
+ if err := m.Save(client.Credentials{Server: "https://connect.oficina.works", Token: tok}); err != nil {
+ t.Fatal(err)
+ }
+ tok.AccessToken = "changed after save"
+ got, err := m.Load()
+ if err != nil || got.Token == nil || got.Token.AccessToken != "bearer-canary-store" {
+ t.Fatalf("load %v %v", got.Token, err)
+ }
+ got.Token.AccessToken = "changed after load"
+ if again, _ := m.Load(); again.Token.AccessToken != "bearer-canary-store" {
+ t.Fatal("a loaded copy shares the stored token")
+ }
+ if err := m.Delete(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := m.Load(); err == nil {
+ t.Fatal("loaded after Delete")
+ }
+}
diff --git a/adopt/migrations/0001_adopt.sql b/adopt/migrations/0001_adopt.sql
index e5ca39a..e83c6cd 100644
--- a/adopt/migrations/0001_adopt.sql
+++ b/adopt/migrations/0001_adopt.sql
@@ -54,9 +54,10 @@ CREATE TABLE adopt_witnesses (
) STRICT;
-- The live checks' outcomes, every one kept: a check that ever failed
--- keeps Plan C refused. Names and outcomes are fixed codes.
+-- keeps Plan C refused. Names and outcomes are fixed codes: passed,
+-- inconclusive, or failed:<code>.
CREATE TABLE adopt_checks (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
- outcome TEXT NOT NULL CHECK (outcome IN ('passed', 'failed'))
+ outcome TEXT NOT NULL CHECK (outcome IN ('passed', 'inconclusive') OR outcome GLOB 'failed:[a-z]*')
) STRICT;
diff --git a/adopt/observer_test.go b/adopt/observer_test.go
index 767675d..1dec345 100644
--- a/adopt/observer_test.go
+++ b/adopt/observer_test.go
@@ -269,7 +269,7 @@ func TestObserverRefusals(t *testing.T) {
for _, c := range RequiredLiveChecks {
setupOK(t, x.s.SaveCheck(ctx, c, "passed"))
}
- setupOK(t, x.s.SaveCheck(ctx, "member-no-local-permission-refused", "failed"))
+ setupOK(t, x.s.SaveCheck(ctx, "member-no-local-permission-refused", "failed:allowed"))
}, want: []string{"live-checks-missing"}, exact: true},
{name: "artifact not reviewed", edit: func(t *testing.T, x *observerFixture) { x.o.Artifacts = nil },
want: []string{"artifact-unreviewed"}, exact: true},
diff --git a/adopt/store.go b/adopt/store.go
index fc5a8c1..5f2ea61 100644
--- a/adopt/store.go
+++ b/adopt/store.go
@@ -291,13 +291,14 @@ func (s *Store) Witness(ctx context.Context, app string) (Witness, bool, error)
return w, ok, err
}
-// SaveCheck appends one live check's outcome, "passed" or "failed".
-// Every outcome is kept: a failure is never overwritten by a later pass.
+// SaveCheck appends one live check's outcome: "passed", "inconclusive",
+// or "failed:<code>" with a fixed lower-case code. Every outcome is kept:
+// a failure is never overwritten by a later pass.
func (s *Store) SaveCheck(ctx context.Context, name, outcome string) error {
if !slices.Contains(RequiredLiveChecks, name) {
return errors.New("adopt: not a live check")
}
- if outcome != "passed" && outcome != "failed" {
+ if !liveOutcome.MatchString(outcome) {
return errors.New("adopt: not a live check outcome")
}
_, err := s.exec(ctx, "INSERT INTO adopt_checks(name,outcome) VALUES(?,?)", name, outcome)
@@ -308,6 +309,8 @@ func (s *Store) SaveCheck(ctx context.Context, name, outcome string) error {
// canary app activates before the checks run, so it is never gated.
// Every other app is admitted only when each of RequiredLiveChecks has
// passed and no check has ever failed; otherwise ErrLiveChecksMissing.
+// An inconclusive outcome neither passes nor fails; any outcome not
+// known here counts as a failure.
func (s *Store) LiveGate(ctx context.Context, app string) error {
if app == CanaryApp {
return nil
@@ -325,8 +328,9 @@ func (s *Store) LiveGate(ctx context.Context, app string) error {
return err
}
switch outcome {
- case "passed":
+ case livePassed:
passed[name] = true
+ case liveInconclusive:
default:
failed = true
}
diff --git a/adopt/store_test.go b/adopt/store_test.go
index 846f468..74fd2a1 100644
--- a/adopt/store_test.go
+++ b/adopt/store_test.go
@@ -312,7 +312,7 @@ func TestLiveGateCanaryAndRest(t *testing.T) {
}
// A failure stays on the record: passing again later does not open
// the gate.
- if err := s.SaveCheck(ctx, "owner-revoked-refused", "failed"); err != nil {
+ if err := s.SaveCheck(ctx, "owner-revoked-refused", "failed:allowed"); err != nil {
t.Fatal(err)
}
gated("one failed")
@@ -326,13 +326,45 @@ func TestLiveGateCanaryAndRest(t *testing.T) {
if err := s.SaveCheck(ctx, "made-up", "passed"); err == nil {
t.Fatal("unknown check recorded")
}
- for _, outcome := range []string{"", "pass", "skipped"} {
+ for _, outcome := range []string{"", "pass", "skipped", "failed", "failed:", "failed:Allowed", "failed:a b", "failed:allowed\n", "inconclusive:x"} {
if err := s.SaveCheck(ctx, "member-allowed", outcome); err == nil {
t.Fatalf("outcome %q recorded", outcome)
}
}
}
+// An inconclusive check neither passes nor fails: it leaves the gate as
+// it was, and a later pass of the same check still counts.
+func TestLiveGateInconclusive(t *testing.T) {
+ ctx := context.Background()
+ s := newJournal(t)
+ for _, name := range RequiredLiveChecks {
+ if err := s.SaveCheck(ctx, name, "inconclusive"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.LiveGate(ctx, "docs"); !errors.Is(err, ErrLiveChecksMissing) {
+ t.Fatalf("inconclusive checks opened the gate: %v", err)
+ }
+ for _, name := range RequiredLiveChecks {
+ if err := s.SaveCheck(ctx, name, "passed"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.SaveCheck(ctx, "owner-revoked-refused", "inconclusive"); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.LiveGate(ctx, "docs"); err != nil {
+ t.Fatalf("an inconclusive repeat closed the gate: %v", err)
+ }
+ if err := s.SaveCheck(ctx, "member-allowed", "failed:forbidden"); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.LiveGate(ctx, "docs"); !errors.Is(err, ErrLiveChecksMissing) {
+ t.Fatalf("a failed:<code> check left the gate open: %v", err)
+ }
+}
+
// A sealed row opens only under its own table and key.
func TestAdoptRowsBoundToTheirKey(t *testing.T) {
ctx := context.Background()
diff --git a/adopt/words.go b/adopt/words.go
index e26e537..8398e1c 100644
--- a/adopt/words.go
+++ b/adopt/words.go
@@ -2,9 +2,10 @@
// go through the copy-review skill before merge (plan Task 14, step 5);
// a change here is a change of copy.
//
-// PENDING COPY REVIEW: WitnessSentence and WriteSummary are drafts, not
-// yet reviewed with Paul. They are reviewed in Task 14 step 5 with the
-// runner's other strings.
+// PENDING COPY REVIEW: WitnessSentence, WriteSummary and the live
+// checks' words (LiveSteps, the LiveSay lines and the four sentences)
+// are drafts, not yet reviewed with Paul. They are reviewed in Task 14
+// step 5 with the runner's other strings.
package adopt
import "amadan.net/oficina/alta/provision"
@@ -21,3 +22,34 @@ func WitnessSentence(app provision.App) string {
func WriteSummary(keys [2]string, bundle string) string {
return "set " + keys[0] + ", " + keys[1] + " on " + bundle
}
+
+// The live checks' sentences. Paul types each one, exactly, once he has
+// done what it says. None names a team, an address or an event.
+const (
+ LiveAddedMember = "I added the test account to the Oficina team"
+ LiveRemovedMember = "I removed the test account from the Oficina team"
+ LiveLocalAccessKept = "The test account still signs in to calendar.oficina.works and sees its own events"
+ LiveOwnerLocalAccessKept = "I still sign in to calendar.oficina.works and see my own events"
+)
+
+// What the live checks say before each sign-in to connect, so Paul knows
+// which account the browser should be signed in as.
+const (
+ LiveSayTestSignIn = "Sign in to connect as the test account."
+ LiveSayTestTeam = "Sign in to connect as the test account again, and tick the Oficina team."
+ LiveSayOwnerSignIn = "Sign in to connect as yourself, and tick the Oficina team."
+)
+
+// LiveSteps is what the live checks print without --apply: every step,
+// in order, and nothing contacted.
+var LiveSteps = []string{
+ "1. The test account signs in to connect; a call to the team is refused (non-member-refused).",
+ "2. You add the test account to the team; it signs in again and ticks the team.",
+ "3. Its free/busy call to the team succeeds (member-allowed).",
+ "4. It cannot read your chosen event (member-no-local-permission-refused).",
+ "5. You remove it from the team; the same call, repeated, is refused (revoked-membership-refused).",
+ "6. You confirm the test account still uses calendar directly (local-access-kept).",
+ "7. You connect, call and disconnect; your call, repeated, is refused (owner-allowed, owner-revoked-refused).",
+ "8. You confirm you still use calendar directly (owner-local-access-kept).",
+ "Every connection made is disconnected at the end.",
+}
diff --git a/go.mod b/go.mod
index 184c9d9..5b41090 100644
--- a/go.mod
+++ b/go.mod
@@ -5,6 +5,7 @@ go 1.26
toolchain go1.26.5
require (
+ amadan.net/oficina/agent-access.git v0.0.0-20261101215226-e4ea91480ce6
amadan.net/oficina/estilo.git v0.0.0-20261026221328-cca97df85b67
amadan.net/oficina/home/connect v0.0.0-20261028092646-82d938882ed3
amadan.net/oficina/home/handoff v0.0.0-20261028092646-82d938882ed3
@@ -12,21 +13,34 @@ require (
amadan.net/rastrillo/rastrillo v0.29.1-0.20261028004840-5bb38c0ab31b
github.com/go-chi/chi/v5 v5.3.2
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
+ golang.org/x/oauth2 v0.35.0
modernc.org/sqlite v1.55.0
)
require (
amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
github.com/carlosframework/rastrillo v0.23.0 // indirect
+ github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/godbus/dbus/v5 v5.2.2 // indirect
+ github.com/gofrs/flock v0.12.1 // indirect
+ github.com/google/jsonschema-go v0.4.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/modelcontextprotocol/go-sdk v1.7.0 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
+ github.com/segmentio/asm v1.1.3 // indirect
+ github.com/segmentio/encoding v0.5.4 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
+ github.com/zalando/go-keyring v0.2.8 // indirect
+ golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.39.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
gorm.io/gorm v1.31.2 // indirect
gorm.io/plugin/dbresolver v1.6.2 // indirect
modernc.org/libc v1.74.1 // indirect
diff --git a/go.sum b/go.sum
index 995fa6d..bb78cfb 100644
--- a/go.sum
+++ b/go.sum
@@ -1,3 +1,5 @@
+amadan.net/oficina/agent-access.git v0.0.0-20261101215226-e4ea91480ce6 h1:TsdiPHRgol+QhONgRWRlRc3dfn4ilnPJm5cmrWeXndA=
+amadan.net/oficina/agent-access.git v0.0.0-20261101215226-e4ea91480ce6/go.mod h1:IWNXkxXLhEbHocPN+qPD5z8ix4dT/wtHLR27Z5QPdRc=
amadan.net/oficina/estilo.git v0.0.0-20261026221328-cca97df85b67 h1:B0mReCGiVImozUwSVHhsvSYycEd8hxxAX8cU6nlEDWE=
amadan.net/oficina/estilo.git v0.0.0-20261026221328-cca97df85b67/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
amadan.net/oficina/home/connect v0.0.0-20261028092646-82d938882ed3 h1:ErD9M+ESc00+x8d8p3621bh4Ykoz9QWHvYiDtFPxGsQ=
@@ -18,6 +20,12 @@ github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZ
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
+github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
+github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
@@ -32,6 +40,16 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
+github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
+github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
+github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E=
+github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -48,14 +66,34 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
+github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
+github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
+github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
+github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
+github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
+github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
+github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
+golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -63,8 +101,12 @@ golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=