| 1 | // Package connection assembles the Oficina connection service. Home supplies |
| 2 | // identity and current directory facts; app content remains in app operations. |
| 3 | package connection |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/hkdf" |
| 8 | "crypto/sha256" |
| 9 | "encoding/base64" |
| 10 | "errors" |
| 11 | "log/slog" |
| 12 | "net/http" |
| 13 | "net/url" |
| 14 | "time" |
| 15 | |
| 16 | access "amadan.net/oficina/agent-access.git" |
| 17 | "amadan.net/oficina/agent-access.git/client" |
| 18 | "amadan.net/oficina/agent-access.git/grant" |
| 19 | "amadan.net/oficina/home/handoff" |
| 20 | "amadan.net/oficina/home/handoff/seal" |
| 21 | "amadan.net/rastrillo/rastrillo/assertion" |
| 22 | "amadan.net/rastrillo/rastrillo/db" |
| 23 | "amadan.net/rastrillo/rastrillo/migrate" |
| 24 | "amadan.net/rastrillo/rastrillo/sessions" |
| 25 | ) |
| 26 | |
| 27 | type Config struct { |
| 28 | Origin string `json:"origin"` |
| 29 | HomeIssuer string `json:"home_issuer"` |
| 30 | ConsumerID string `json:"consumer_id"` |
| 31 | HomeKeys map[string]string `json:"home_keys"` |
| 32 | Directory string `json:"directory"` |
| 33 | Clients []grant.Client `json:"clients"` |
| 34 | Routes []access.Route `json:"routes"` |
| 35 | // Secrets come from deployment secret configuration, never the config file. |
| 36 | DEK []byte `json:"-"` |
| 37 | DirectoryToken string `json:"-"` |
| 38 | Transport http.RoundTripper `json:"-"` |
| 39 | } |
| 40 | |
| 41 | type Server struct { |
| 42 | Handler http.Handler |
| 43 | Grants *grant.Store |
| 44 | Registry *access.Registry |
| 45 | } |
| 46 | |
| 47 | func New(ctx context.Context, cfg Config, d *db.DB, logger *slog.Logger) (*Server, error) { |
| 48 | if !validOrigin(cfg.Origin) || !validOrigin(cfg.HomeIssuer) || cfg.Origin == cfg.HomeIssuer || cfg.Origin == cfg.Directory || cfg.Directory == cfg.HomeIssuer || d == nil || len(cfg.HomeKeys) == 0 || len(cfg.HomeKeys) > 8 { |
| 49 | return nil, errors.New("invalid connection service configuration") |
| 50 | } |
| 51 | if logger == nil { |
| 52 | logger = slog.Default() |
| 53 | } |
| 54 | directory, err := NewDirectory(cfg.Directory, cfg.DirectoryToken, cfg.Transport) |
| 55 | if err != nil { |
| 56 | return nil, err |
| 57 | } |
| 58 | sealer, err := seal.New(cfg.DEK, "oficina/agent-access") |
| 59 | if err != nil { |
| 60 | return nil, errors.New("invalid connection encryption key") |
| 61 | } |
| 62 | keys := map[string][]byte{} |
| 63 | for name, encoded := range cfg.HomeKeys { |
| 64 | value, err := base64.StdEncoding.DecodeString(encoded) |
| 65 | if err != nil { |
| 66 | return nil, errors.New("invalid Home public keys") |
| 67 | } |
| 68 | keys[name] = value |
| 69 | } |
| 70 | if _, err = assertion.NewVerifier(cfg.HomeIssuer, cfg.Origin, keys); err != nil { |
| 71 | return nil, errors.New("invalid Home identity configuration") |
| 72 | } |
| 73 | if _, err = migrate.Apply(ctx, d, migrate.Merge(sessions.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"))); err != nil { |
| 74 | return nil, errors.New("connection database migration failed") |
| 75 | } |
| 76 | sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, TTL: time.Hour, SigninPath: handoff.StartPath, Logger: logger}) |
| 77 | if err != nil { |
| 78 | return nil, err |
| 79 | } |
| 80 | identity, err := handoff.NewStore(d.Writer(), sealer, cfg.HomeIssuer, cfg.Origin, keys) |
| 81 | if err != nil { |
| 82 | return nil, err |
| 83 | } |
| 84 | if err = identity.Sweep(ctx, time.Now()); err != nil { |
| 85 | return nil, err |
| 86 | } |
| 87 | current := func(r *http.Request) string { |
| 88 | s, ok := sess.From(r) |
| 89 | if !ok || s.Method != "home-assertion" { |
| 90 | return "" |
| 91 | } |
| 92 | return s.Subject |
| 93 | } |
| 94 | fresh := func(r *http.Request) string { |
| 95 | s, ok := sess.From(r) |
| 96 | if !ok || s.Method != "home-assertion" || s.AuthTime.IsZero() || s.AuthTime.After(time.Now()) || time.Since(s.AuthTime) > 5*time.Minute { |
| 97 | return "" |
| 98 | } |
| 99 | return s.Subject |
| 100 | } |
| 101 | signIn := handoff.ConsumerConfig{Store: identity, ConsumerID: cfg.ConsumerID, RequireFreshAuth: true, CurrentSubject: current, Complete: func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error { |
| 102 | return sess.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "home-assertion", AuthTime: time.Unix(c.AuthTime, 0)}) |
| 103 | }} |
| 104 | consumer, err := handoff.NewConsumer(signIn) |
| 105 | if err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | // Connecting a first-party client reuses the person's Home session. The |
| 109 | // session still records the real AuthTime, so it never passes as fresh. |
| 110 | signIn.RequireFreshAuth = false |
| 111 | reuse, err := handoff.NewConsumer(signIn) |
| 112 | if err != nil { |
| 113 | return nil, err |
| 114 | } |
| 115 | store, err := grant.NewStore(ctx, d.Writer()) |
| 116 | if err != nil { |
| 117 | return nil, err |
| 118 | } |
| 119 | if err = store.Sweep(ctx); err != nil { |
| 120 | return nil, err |
| 121 | } |
| 122 | provider := &credentials{directory, store, cfg.Routes} |
| 123 | registry, err := access.Gateway(cfg.Routes, provider, cfg.Transport) |
| 124 | if err != nil { |
| 125 | return nil, err |
| 126 | } |
| 127 | scopes := map[string]string{"offline_access": "Keep this connection until it expires or you revoke it"} |
| 128 | for _, route := range cfg.Routes { |
| 129 | for _, op := range route.Operations { |
| 130 | label, ok := scopeDescriptions[op.Scope] |
| 131 | if !ok { |
| 132 | return nil, errors.New("operation has an unsupported consent scope") |
| 133 | } |
| 134 | scopes[op.Scope] = label |
| 135 | } |
| 136 | } |
| 137 | clients := append([]grant.Client{{ID: client.ClientID, Name: "Oficina CLI", Loopback: true}}, cfg.Clients...) |
| 138 | consentKey, err := hkdf.Key(sha256.New, cfg.DEK, nil, "oficina/agent-access/consent-v1", 32) |
| 139 | if err != nil { |
| 140 | return nil, err |
| 141 | } |
| 142 | grants, err := grant.NewServer(grant.Config{IdentityIssuer: cfg.HomeIssuer, Origin: cfg.Origin, Resource: cfg.Origin + "/mcp", Store: store, ConsentKey: consentKey, Clients: clients, Scopes: scopes, Subject: fresh, SessionSubject: current, Teams: provider.teams, ResourceTeams: provider.resourceTeams, SignInPath: handoff.StartPath}) |
| 143 | if err != nil { |
| 144 | return nil, err |
| 145 | } |
| 146 | mux := http.NewServeMux() |
| 147 | mux.HandleFunc(handoff.StartPath, func(w http.ResponseWriter, r *http.Request) { |
| 148 | q, err := url.ParseQuery(r.URL.RawQuery) |
| 149 | if err == nil && len(q) == 1 && len(q["return_to"]) == 1 && grants.ReusesSession(q["return_to"][0]) { |
| 150 | reuse.Start(w, r) |
| 151 | return |
| 152 | } |
| 153 | consumer.Start(w, r) |
| 154 | }) |
| 155 | mux.HandleFunc(handoff.CallbackPath, consumer.Callback) |
| 156 | mux.HandleFunc(handoff.FinishPath, consumer.Finish) |
| 157 | mcpHandler, err := registry.MCPAtOrigin(grants, cfg.Origin) |
| 158 | if err != nil { |
| 159 | return nil, err |
| 160 | } |
| 161 | mux.Handle("/mcp", grants.ResourceHandler(mcpHandler)) |
| 162 | api := registry.HTTPGuarded(grants, grants, registry.ScheduleResponseGuard) |
| 163 | mux.Handle("/api/v1/connection", grants.ResourceHandler(api)) |
| 164 | mux.Handle("/api/v1/operations", grants.ResourceHandler(api)) |
| 165 | mux.Handle("/api/v1/operations/", grants.ResourceHandler(api)) |
| 166 | mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) }) |
| 167 | mux.Handle("/", grants.Handler()) |
| 168 | u, _ := url.Parse(cfg.Origin) |
| 169 | handler := sess.Middleware(mux) |
| 170 | guard := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 171 | w.Header().Set("Cache-Control", "no-store") |
| 172 | w.Header().Set("Referrer-Policy", "no-referrer") |
| 173 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 174 | if r.Host != u.Host { |
| 175 | http.NotFound(w, r) |
| 176 | return |
| 177 | } |
| 178 | defer func() { |
| 179 | if recover() != nil { |
| 180 | logger.Error("connection request failed") |
| 181 | http.Error(w, "Request unavailable", 500) |
| 182 | } |
| 183 | }() |
| 184 | handler.ServeHTTP(w, r) |
| 185 | }) |
| 186 | return &Server{guard, store, registry}, nil |
| 187 | } |
| 188 | |
| 189 | var scopeDescriptions = map[string]string{ |
| 190 | "docs:read": "Read documents", "docs:write": "Create and edit documents", |
| 191 | "sheets:read": "Read spreadsheets", "sheets:write": "Create and edit spreadsheets", |
| 192 | "notes:read": "Search and read visible notes and passages", "notes:write": "Create and edit team notes", |
| 193 | "calendar:read": "Read calendars and events", "calendar:write": "Create and edit calendar events", |
| 194 | "calls:read": "Read call details", "calls:write": "Create and manage calls", |
| 195 | "slides:read": "Read presentations", "slides:write": "Create and edit presentations", |
| 196 | "fichas:read": "Read records", "fichas:write": "Create and edit records", |
| 197 | } |
| 198 | |