diff --git a/README.md b/README.md index 1f4ebba..f342e35 100644 --- a/README.md +++ b/README.md @@ -676,7 +676,7 @@ A consent link lets the owner of an account connect it themselves: "tap here to - A change to `consent` needs a restart; `SIGHUP` refuses it. API: -- `POST /links` `{"service": "gmail", "ttl_seconds": 900, "label": "Alice"}` returns `{"url", "expires_at"}` (201). `ttl_seconds` is 60 to 3600 (default 900); the label (at most 100 characters) is shown on the page. Scopes, paths and keys cannot be set here: they come from the access file. Only `bearer`, `header` and `query` services, and `oauth2` services with an `auth_url`, can get a link; signing keys stay with the owner. +- `POST /links` `{"service": "gmail", "ttl_seconds": 900, "label": "Alice"}` returns `{"url", "expires_at"}` (201). `ttl_seconds` is 60 to 3600 (default 900); the label (at most 100 characters) is shown on the page. An optional `return_url` (https, at most 512 characters, on one of the consent block's `return_origins`, e.g. `"return_origins": ["https://app.example.com"]`) makes the done page say "Taking you back…" and go there after 3 seconds, with a button to go at once; without it the page says the person can close it. Scopes, paths and keys cannot be set here: they come from the access file. Only `bearer`, `header` and `query` services, and `oauth2` services with an `auth_url`, can get a link; signing keys stay with the owner. - `DELETE /keys/` deletes the service's stored key. For an `oauth2` service with a `revoke_url`, the provider is asked to revoke the refresh token first (RFC 7009); the key is deleted even if that fails, and the reply says `"revoked": false`. The link: diff --git a/deploy/cloudflare/README.md b/deploy/cloudflare/README.md index e824caa..bc52b0b 100644 --- a/deploy/cloudflare/README.md +++ b/deploy/cloudflare/README.md @@ -72,6 +72,7 @@ Inputs: |---|---|---| | `PUBLIC_BASE` | var in `wrangler.jsonc` | https origin of the Worker, e.g. `https://keyring.example.com`; may change, see [Changing `PUBLIC_BASE`](#changing-public_base) | | `SERVICES_TEMPLATE` | var in `wrangler.jsonc` | services each keyring starts with, and the router role's access | +| `RETURN_ORIGINS` | var in `wrangler.jsonc` (optional) | comma-separated https origins, e.g. `https://app.example.com`, that a link's `return_url` may point to; sent as consent `return_origins` on each keyring's next start, like a `PUBLIC_BASE` change | | `MASTER_KEY` | secret | `head -c32 /dev/urandom \| base64`. Losing it makes every keyring unreadable; rotating it needs a re-seal (not built yet) | | `CALLER_SECRET` | secret | the router's `X-Keyring-Caller` value, one per Phobos server | | `ADMIN_TOKEN` | secret | the router's admin bearer token | diff --git a/deploy/cloudflare/src/index.ts b/deploy/cloudflare/src/index.ts index 5ee78e2..e3c2cdd 100644 --- a/deploy/cloudflare/src/index.ts +++ b/deploy/cloudflare/src/index.ts @@ -23,6 +23,12 @@ export interface Env { PUBLIC_BASE: string; /** The services every new instance starts with (a JSON var). */ SERVICES_TEMPLATE: Template | string; + /** + * Optional, comma-separated https origins a connection link may send the + * person back to once connected (the link's return_url), e.g. + * https://app.example.com. Each keyring gets them on its next start. + */ + RETURN_ORIGINS?: string; /** Secret: base64 of 32 random bytes; derives every instance's data key. */ MASTER_KEY: string; /** Secret: the router's proof, sent as X-Keyring-Caller. */ @@ -268,13 +274,25 @@ const K_USAGE = "usage"; const K_OPEN_UNTIL = "openUntil"; const K_SECRETS = "clientSecretsHash"; const K_LAST_USED = "lastUsed"; -/** The consent public_url last sent to the keyring and saved in its sealed state. */ -const K_CONSENT_URL = "consentPublicUrl"; +/** + * What of the consent settings was last sent to the keyring and saved in its + * sealed state (consentStamp; before return origins, the bare public_url). + */ +const K_CONSENT = "consentPublicUrl"; /** lastUsed is written to storage at most this often. */ const LAST_USED_WRITE_MS = 30 * 1000; class Deleted extends Error {} +/** + * The part of the consent settings that can change between starts. Without + * return origins it is the bare public_url, the value kept before them, so + * existing keyrings are not sent the same settings again. + */ +function consentStamp(c: { public_url: string; return_origins?: string[] }): string { + return c.return_origins ? JSON.stringify([c.public_url, c.return_origins]) : c.public_url; +} + export class KeyringInstance extends DurableObject { /** The one start in progress or done; null when the container is stopped. */ @@ -435,26 +453,30 @@ export class KeyringInstance extends DurableObject { /** The keyring's consent settings; public_url follows PUBLIC_BASE. */ private async consentSettings(m: Identity) { + const origins = (this.env.RETURN_ORIGINS ?? "").split(",").map((o) => o.trim()).filter(Boolean); return { listen: `0.0.0.0:${PORT_PAGES}`, public_url: `${this.env.PUBLIC_BASE}/connect`, api_listen: `0.0.0.0:${PORT_CONSENT_API}`, api_token_sha256: await sha256Hex(m.consentToken), + // Left out when empty, as the keyring omits it. + ...(origins.length ? { return_origins: origins } : {}), }; } /** - * Sends the consent settings again when PUBLIC_BASE changed since they - * were last sent. The keyring builds link, Google page and callback URLs - * from its own public_url, kept in its sealed state; publishLink and the - * page route expect them under PUBLIC_BASE. Open links and accounts stay. + * Sends the consent settings again when PUBLIC_BASE or RETURN_ORIGINS + * changed since they were last sent. The keyring builds link, Google page + * and callback URLs from its own public_url, kept in its sealed state; + * publishLink and the page route expect them under PUBLIC_BASE. Open + * links and accounts stay. */ private async pushConsent(m: Identity): Promise { const consent = await this.consentSettings(m); - if (consent.public_url === (await this.ctx.storage.get(K_CONSENT_URL))) return; + if (consentStamp(consent) === (await this.ctx.storage.get(K_CONSENT))) return; await this.adminJSON(m, "PUT", "/consent", consent); await this.sync(m); - await this.put(K_CONSENT_URL, consent.public_url); + await this.put(K_CONSENT, consentStamp(consent)); } private async pushClientSecrets(m: Identity): Promise { @@ -508,7 +530,7 @@ export class KeyringInstance extends DurableObject { } await this.pushClientSecrets(m); await this.sync(m); - await this.put(K_CONSENT_URL, consent.public_url); + await this.put(K_CONSENT, consentStamp(consent)); if (!role.token) throw new KeyringError(502, "the keyring returned no role token"); return { role_token: role.token }; } catch (e) { diff --git a/deploy/cloudflare/wrangler.jsonc b/deploy/cloudflare/wrangler.jsonc index ab0d876..6b336b6 100644 --- a/deploy/cloudflare/wrangler.jsonc +++ b/deploy/cloudflare/wrangler.jsonc @@ -20,6 +20,9 @@ "vars": { // Set to the Worker's https origin, e.g. https://keyring.example.com "PUBLIC_BASE": "https://keyring.example.com", + // Optional, comma-separated https origins a link's return_url may point + // to: the done page sends the person back there after a few seconds. + "RETURN_ORIGINS": "", // The services every new keyring starts with, and the router's access. "SERVICES_TEMPLATE": { "services": { diff --git a/internal/consent/consent.go b/internal/consent/consent.go index 605dace..a228d6d 100644 --- a/internal/consent/consent.go +++ b/internal/consent/consent.go @@ -86,6 +86,9 @@ type link struct { google bool googleEpoch uint64 workspace *workspace.ConsentBinding + // returnURL, if set, is where the done page sends the person back + // (an allowed return origin, checked when the link was made). + returnURL string } type signIn struct { @@ -101,6 +104,7 @@ type signIn struct { google bool googleEpoch uint64 workspace *workspace.ConsentBinding + returnURL string // the link's } // New builds a consent server. config returns the settings in use (the @@ -318,6 +322,9 @@ func (s *Server) createLink(w http.ResponseWriter, r *http.Request) { Service string `json:"service"` TTLSeconds int `json:"ttl_seconds"` Label string `json:"label"` + // ReturnURL, optional, is where the person goes back after + // connecting: https on one of consent.return_origins. + ReturnURL string `json:"return_url"` } dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)) dec.DisallowUnknownFields() @@ -368,6 +375,13 @@ func (s *Server) createLink(w http.ResponseWriter, r *http.Request) { apiError(w, http.StatusBadRequest, "label must be at most 100 characters without control characters") return } + if req.ReturnURL != "" { + u, err := url.Parse(req.ReturnURL) + if err != nil || len(req.ReturnURL) > maxReturnURL || !cfg.Consent.ReturnAllowed(u) || strings.ContainsAny(req.ReturnURL, " \t\r\n;") { + apiError(w, http.StatusBadRequest, "return_url must be an https URL on one of consent return_origins") + return + } + } id := randomToken() h := hashOf(id) now := s.now() @@ -396,7 +410,7 @@ func (s *Server) createLink(w http.ResponseWriter, r *http.Request) { } } } - s.links[h] = &link{service: req.Service, key: svc.Key, extraHeaders: maps.Clone(svc.ExtraHeaders), label: req.Label, expires: expires, workspace: binding} + s.links[h] = &link{service: req.Service, key: svc.Key, extraHeaders: maps.Clone(svc.ExtraHeaders), label: req.Label, expires: expires, workspace: binding, returnURL: req.ReturnURL} if svc.Auth == policy.AuthGcloudLogin { s.links[h].google = true s.links[h].googleEpoch = s.google.Epoch() @@ -675,7 +689,7 @@ func (s *Server) linkSubmit(w http.ResponseWriter, r *http.Request, id string, p s.startGoogle(w, r, l, h, public) return } - service, label := l.service, l.label + service, label, back := l.service, l.label, l.returnURL if svc.Auth != policy.AuthOAuth2 { var value string var err error @@ -715,7 +729,7 @@ func (s *Server) linkSubmit(w http.ResponseWriter, r *http.Request, id string, p return } s.writeAudit("connected", map[string]any{"service": service, "key": svc.Key, "link": ref(h), "kind": "value"}) - render(w, http.StatusOK, pageData{Service: service, Label: label, Message: "Saved. You can close this page."}) + render(w, http.StatusOK, done(pageData{Service: service, Label: label}, "Saved.", back)) return } if len(s.signIns) >= maxPending { @@ -736,6 +750,7 @@ func (s *Server) linkSubmit(w http.ResponseWriter, r *http.Request, id string, p browser: hashOf(browser), expires: now.Add(signInTTL), workspace: l.workspace, + returnURL: back, } s.mu.Unlock() @@ -876,7 +891,23 @@ func (s *Server) callback(w http.ResponseWriter, r *http.Request, public *url.UR return } s.writeAudit("connected", map[string]any{"service": f.service, "key": svc.Key, "kind": "oauth2"}) - render(w, http.StatusOK, pageData{Service: f.service, Message: "Connected. You can close this page."}) + render(w, http.StatusOK, done(pageData{Service: f.service}, "Connected.", f.returnURL)) +} + +// maxReturnURL bounds a link's return_url. +const maxReturnURL = 512 + +// done is a success page: with a return URL it says it goes back and does +// so after a few seconds (a plain refresh: the pages run no scripts), with +// a button for doing it at once; without one, the person closes the page. +func done(data pageData, said, back string) pageData { + if back == "" { + data.Message = said + " You can close this page." + return data + } + data.Message = said + " Taking you back…" + data.Return = back + return data } // exchange trades the authorization code for tokens (RFC 6749 4.1.3, RFC @@ -1002,6 +1033,8 @@ type pageData struct { // GoogleStep is the Google connection's current step while it runs // (1 sign-in, 2 project setup), shown as a list; 0 shows none. GoogleStep int + // Return, on a success page, is where it sends the person back. + Return string } type credentialField struct { @@ -1026,7 +1059,7 @@ func credentialForm(data *pageData, svc policy.Service) { var page = template.Must(template.New("page").Parse(` -{{if .Refresh}}{{end}} +{{if .Refresh}}{{else if .Return}}{{end}} {{if .Label}}Connect {{.Label}}{{else if .Service}}Connect {{.Service}}{{else}}Private connection page{{end}}