Add browser authorization, scoped app credentials and CLI

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev daa74b58979d0ccf5cfe2148574b44199014c656 parent cd915c4
12 files changed, +1,681 −19
  • README.md +19 −3
  • client/client.go +268 −0
  • client/keyring.go +60 −0
  • cmd/oficina/main.go +158 −0
  • go.mod +16 −3
  • go.sum +69 −6
  • grant/server.go +471 −0
  • grant/server_test.go +256 −0
  • grant/store.go +294 −0
  • http.go +6 −2
  • operation.go +5 −5
  • remote.go +59 −0
diff --git a/README.md b/README.md
index 4b609f5..9aae0c0 100644
--- a/README.md
+++ b/README.md
@@ -4,9 +4,11 @@ One operation contract for Oficina HTTP APIs, the `oficina` CLI, and MCP.
The transport and credential interfaces are independent of the app operations
so they can be replaced by Rastrillo implementations later.
-Status: implementation in progress. The shared registry, HTTP and MCP adapters
-exist. Browser authorization, app integration and the CLI are not yet complete.
-No production endpoint is deployed.
+Status: implementation in progress. Shared operations, HTTP/MCP adapters, the
+CLI, browser consent with PKCE, rotating refresh tokens and revocation are
+implemented. Tests exercise browser authorization through an HTTPS fixture,
+including real loopback callbacks. Home and application wiring remain in
+progress. No production endpoint is deployed.
Each request supplies a verified person, client, grant, selected teams and
scopes. The registry rejects unauthorized team/scope combinations before calling
@@ -23,3 +25,17 @@ through an already connected MCP client.
The JSON API framework landed at Rastrillo `2e833dd`; its MCP and OAuth packages
are separate ongoing work. This module will not wait on them, per Paul's
2026-10-24 direction.
+
+The `grant` package is mounted by the connection service with verified browser
+identity and current-team callbacks. The issuer and consent UI run separately
+from Home's credential origin. App tokens are restricted to one audience, team
+and scope set; `RemoteVerifier` checks them online before the app resolves the
+Home subject to an existing local account. Revoking the parent grant also
+invalidates every downstream token.
+
+`oficina auth login --server https://…` opens the system browser and stores the
+connection in the OS credential store. `oficina tools` lists operations;
+`oficina notes create --team acme --input note.json` calls one. `oficina mcp serve`
+provides a local stdio adapter backed by the same API. The server must have this
+integration mounted; these commands do not work against the current production
+apps yet. The CLI's local logout is not server-side revocation.
diff --git a/client/client.go b/client/client.go
new file mode 100644
index 0000000..bef0b0a
--- /dev/null
+++ b/client/client.go
@@ -0,0 +1,268 @@
+// Package client provides the credential boundary shared by the CLI and stdio MCP.
+package client
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ access "amadan.net/oficina/agent-access"
+ "golang.org/x/oauth2"
+)
+
+const ClientID = "oficina-cli"
+const MaxResponse = access.MaxPayload
+
+type Credentials struct {
+ Server string `json:"server"`
+ Resource string `json:"resource"`
+ TokenEndpoint string `json:"token_endpoint"`
+ Token *oauth2.Token `json:"token"`
+}
+type Store interface {
+ Load() (Credentials, error)
+ Save(Credentials) error
+ Delete() error
+}
+type Client struct {
+ mu sync.Mutex
+ Store Store
+ HTTP *http.Client
+}
+
+func New(store Store) *Client {
+ return &Client{Store: store, HTTP: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
+}
+func validServer(raw string) (*url.URL, error) {
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
+ return nil, errors.New("use an HTTPS Oficina server origin")
+ }
+ u.Path = ""
+ return u, nil
+}
+func nonce() string {
+ var b [32]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ panic(err)
+ }
+ return base64.RawURLEncoding.EncodeToString(b[:])
+}
+func (c *Client) readJSON(ctx context.Context, req *http.Request, out any) error {
+ resp, err := c.HTTP.Do(req.WithContext(ctx))
+ if err != nil {
+ return errors.New("Oficina could not be reached")
+ }
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, MaxResponse+1))
+ if err != nil || len(raw) > MaxResponse {
+ return errors.New("invalid or oversized Oficina response")
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return fmt.Errorf("Oficina returned HTTP %d", resp.StatusCode)
+ }
+ if json.Unmarshal(raw, out) != nil {
+ return errors.New("Oficina returned invalid JSON")
+ }
+ return nil
+}
+
+// Login binds the browser callback to a random state and an S256 PKCE verifier.
+// Credentials are persisted only after token exchange; no secret enters stdout.
+func (c *Client) Login(ctx context.Context, server string, scopes []string, open func(string) error) error {
+ origin, err := validServer(server)
+ if err != nil {
+ return err
+ }
+ server = origin.String()
+ var metadata struct {
+ Issuer string `json:"issuer"`
+ AuthorizationEndpoint string `json:"authorization_endpoint"`
+ TokenEndpoint string `json:"token_endpoint"`
+ Methods []string `json:"code_challenge_methods_supported"`
+ }
+ req, _ := http.NewRequestWithContext(ctx, "GET", server+"/.well-known/oauth-authorization-server", nil)
+ if err = c.readJSON(ctx, req, &metadata); err != nil {
+ return err
+ }
+ if metadata.Issuer != server {
+ return errors.New("authorization issuer does not match the configured server")
+ }
+ for _, endpoint := range []string{metadata.AuthorizationEndpoint, metadata.TokenEndpoint} {
+ u, e := url.Parse(endpoint)
+ if e != nil || u.Scheme != origin.Scheme || u.Host != origin.Host || u.User != nil || u.Fragment != "" || u.RawQuery != "" {
+ return errors.New("authorization endpoints must belong to the configured server")
+ }
+ }
+ pkce := false
+ for _, m := range metadata.Methods {
+ if m == "S256" {
+ pkce = true
+ }
+ }
+ if !pkce {
+ return errors.New("authorization server does not support S256 PKCE")
+ }
+ listener, err := net.Listen("tcp4", "127.0.0.1:0")
+ if err != nil {
+ return errors.New("could not open the login callback")
+ }
+ defer listener.Close()
+ state, verifier := nonce(), oauth2.GenerateVerifier()
+ redirect := "http://" + listener.Addr().String() + "/callback"
+ type answer struct {
+ code string
+ err error
+ }
+ answers := make(chan answer, 1)
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /callback", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ q := r.URL.Query()
+ if r.Host != listener.Addr().String() || len(q["state"]) != 1 || q.Get("state") != state || len(q["iss"]) != 1 || q.Get("iss") != metadata.Issuer {
+ http.Error(w, "Login response refused.", 400)
+ return
+ }
+ var a answer
+ if q.Get("error") != "" {
+ a.err = errors.New("Oficina authorization was declined")
+ } else if len(q["code"]) != 1 || q.Get("code") == "" {
+ http.Error(w, "Login response refused.", 400)
+ return
+ } else {
+ a.code = q.Get("code")
+ }
+ select {
+ case answers <- a:
+ fmt.Fprintln(w, "Return to Oficina in your terminal to check the connection.")
+ default:
+ http.Error(w, "Login response already received.", 409)
+ }
+ })
+ callback := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
+ defer callback.Close()
+ go callback.Serve(listener)
+ resource := server + "/mcp"
+ cfg := &oauth2.Config{ClientID: ClientID, RedirectURL: redirect, Scopes: scopes, Endpoint: oauth2.Endpoint{AuthURL: metadata.AuthorizationEndpoint, TokenURL: metadata.TokenEndpoint, AuthStyle: oauth2.AuthStyleInParams}}
+ authURL := cfg.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier), oauth2.SetAuthURLParam("resource", resource))
+ if err = open(authURL); err != nil {
+ return errors.New("could not open the authorization browser")
+ }
+ var a answer
+ select {
+ case <-ctx.Done():
+ return errors.New("authorization timed out or was cancelled")
+ case a = <-answers:
+ }
+ if a.err != nil {
+ return a.err
+ }
+ ctx = context.WithValue(ctx, oauth2.HTTPClient, c.HTTP)
+ token, err := cfg.Exchange(ctx, a.code, oauth2.VerifierOption(verifier), oauth2.SetAuthURLParam("resource", resource))
+ if err != nil {
+ return errors.New("authorization code exchange failed")
+ }
+ if token.AccessToken == "" || !strings.EqualFold(token.Type(), "Bearer") {
+ return errors.New("authorization server returned an invalid credential")
+ }
+ if err = c.Store.Save(Credentials{server, resource, metadata.TokenEndpoint, token}); err != nil {
+ return errors.New("could not save the connection in the credential store")
+ }
+ return nil
+}
+func (c *Client) request(ctx context.Context, method, path string, input any, out any) error {
+ var creds Credentials
+ var token *oauth2.Token
+ var origin *url.URL
+ c.mu.Lock()
+ unlock := func() {}
+ if locker, ok := c.Store.(interface {
+ Lock(context.Context) (func(), error)
+ }); ok {
+ var err error
+ unlock, err = locker.Lock(ctx)
+ if err != nil {
+ c.mu.Unlock()
+ return errors.New("could not lock the connection credentials")
+ }
+ }
+ err := func() error {
+ var err error
+ creds, err = c.Store.Load()
+ if err != nil {
+ return errors.New("connect first with oficina auth login")
+ }
+ origin, err = validServer(creds.Server)
+ if err != nil {
+ return err
+ }
+ endpoint, err := url.Parse(creds.TokenEndpoint)
+ if err != nil || endpoint.Scheme != origin.Scheme || endpoint.Host != origin.Host || endpoint.User != nil || endpoint.Fragment != "" || endpoint.RawQuery != "" || creds.Token == nil {
+ return errors.New("stored connection is invalid; sign in again")
+ }
+ cfg := &oauth2.Config{ClientID: ClientID, Endpoint: oauth2.Endpoint{TokenURL: creds.TokenEndpoint, AuthStyle: oauth2.AuthStyleInParams}}
+ token, err = cfg.TokenSource(context.WithValue(ctx, oauth2.HTTPClient, c.HTTP), creds.Token).Token()
+ if err != nil {
+ return errors.New("connection expired; sign in again")
+ }
+ if token.AccessToken != creds.Token.AccessToken || token.RefreshToken != creds.Token.RefreshToken || !token.Expiry.Equal(creds.Token.Expiry) {
+ creds.Token = token
+ if c.Store.Save(creds) != nil {
+ return errors.New("could not save refreshed credentials")
+ }
+ }
+ return nil
+ }()
+ unlock()
+ c.mu.Unlock()
+ if err != nil {
+ return err
+ }
+ var body io.Reader
+ if input != nil {
+ raw, err := json.Marshal(input)
+ if err != nil || len(raw) > MaxResponse {
+ return errors.New("invalid or oversized operation input")
+ }
+ body = bytes.NewReader(raw)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, origin.String()+path, body)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Authorization", "Bearer "+token.AccessToken)
+ if input != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ return c.readJSON(ctx, req, out)
+}
+func (c *Client) Operations(ctx context.Context) ([]access.Operation, error) {
+ var out struct {
+ Operations []access.Operation `json:"operations"`
+ }
+ err := c.request(ctx, "GET", "/api/v1/operations", nil, &out)
+ return out.Operations, err
+}
+func (c *Client) Call(ctx context.Context, name string, input json.RawMessage) (any, error) {
+ if name == "" || strings.IndexFunc(name, func(r rune) bool { return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_') }) >= 0 {
+ return nil, errors.New("invalid operation name")
+ }
+ if access.UniqueJSON(input) != nil {
+ return nil, errors.New("send valid JSON with unique field names")
+ }
+ var out any
+ err := c.request(ctx, "POST", "/api/v1/operations/"+name, input, &out)
+ return out, err
+}
diff --git a/client/keyring.go b/client/keyring.go
new file mode 100644
index 0000000..26ffdc3
--- /dev/null
+++ b/client/keyring.go
@@ -0,0 +1,60 @@
+package client
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "github.com/gofrs/flock"
+ "github.com/zalando/go-keyring"
+ "os"
+ "path/filepath"
+ "time"
+)
+
+type Keyring struct{ Profile string }
+
+func (k Keyring) profile() string {
+ if k.Profile == "" {
+ return "default"
+ }
+ return k.Profile
+}
+func (k Keyring) Load() (Credentials, error) {
+ raw, err := keyring.Get("Oficina", k.profile())
+ if err != nil {
+ return Credentials{}, err
+ }
+ var c Credentials
+ err = json.Unmarshal([]byte(raw), &c)
+ return c, err
+}
+func (k Keyring) Save(c Credentials) error {
+ raw, err := json.Marshal(c)
+ if err != nil {
+ return err
+ }
+ return keyring.Set("Oficina", k.profile(), string(raw))
+}
+func (k Keyring) Delete() error { return keyring.Delete("Oficina", k.profile()) }
+
+// Serialize refresh across CLI processes as well as concurrent MCP calls.
+// Reusing a rotated refresh token revokes the entire connection.
+func (k Keyring) Lock(ctx context.Context) (func(), error) {
+ root, err := os.UserCacheDir()
+ if err != nil {
+ return nil, err
+ }
+ dir := filepath.Join(root, "Oficina", "credential-locks")
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return nil, err
+ }
+ sum := sha256.Sum256([]byte(k.profile()))
+ lock := flock.New(filepath.Join(dir, hex.EncodeToString(sum[:])+".lock"))
+ ok, err := lock.TryLockContext(ctx, 25*time.Millisecond)
+ if err != nil || !ok {
+ return nil, errors.New("credential lock unavailable")
+ }
+ return func() { _ = lock.Unlock() }, nil
+}
diff --git a/cmd/oficina/main.go b/cmd/oficina/main.go
new file mode 100644
index 0000000..25ac97d
--- /dev/null
+++ b/cmd/oficina/main.go
@@ -0,0 +1,158 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "os/signal"
+ "runtime"
+ "time"
+
+ access "amadan.net/oficina/agent-access"
+ "amadan.net/oficina/agent-access/client"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+func main() {
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
+ defer stop()
+ if err := run(ctx, os.Args[1:], os.Stdout); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+func browser(raw string) error {
+ var cmd *exec.Cmd
+ switch runtime.GOOS {
+ case "darwin":
+ cmd = exec.Command("open", raw)
+ case "windows":
+ cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", raw)
+ default:
+ cmd = exec.Command("xdg-open", raw)
+ }
+ return cmd.Run()
+}
+func run(ctx context.Context, args []string, out io.Writer) error {
+ if len(args) < 1 {
+ return errors.New("usage: oficina auth login|status|logout, tools, call <operation>, <app> <action>, or mcp serve")
+ }
+ c := client.New(client.Keyring{})
+ print := func(v any) error { enc := json.NewEncoder(out); enc.SetIndent("", " "); return enc.Encode(v) }
+ switch args[0] {
+ case "auth":
+ if len(args) < 2 {
+ return errors.New("choose auth login, status or logout")
+ }
+ switch args[1] {
+ case "login":
+ fs := flag.NewFlagSet("auth login", flag.ContinueOnError)
+ server := fs.String("server", "", "Oficina connection server origin")
+ if err := fs.Parse(args[2:]); err != nil {
+ return err
+ }
+ if *server == "" {
+ return errors.New("supply --server https://your-oficina-connection-server")
+ }
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
+ defer cancel()
+ if err := c.Login(ctx, *server, []string{"offline_access", "docs:read", "docs:write", "sheets:read", "sheets:write", "notes:read", "notes:write", "calendar:read", "calendar:write", "calls:read", "calls:write", "slides:read", "slides:write"}, browser); err != nil {
+ return err
+ }
+ fmt.Fprintln(out, "Connected to Oficina.")
+ return nil
+ case "status":
+ creds, err := c.Store.Load()
+ if err != nil || creds.Token == nil {
+ return errors.New("not connected")
+ }
+ return print(map[string]any{"server": creds.Server, "expires_at": creds.Token.Expiry})
+ case "logout":
+ if err := c.Store.Delete(); err != nil {
+ return errors.New("could not remove the local connection")
+ }
+ fmt.Fprintln(out, "Local credentials removed. Revoke the connection on the server to end remote access.")
+ return nil
+ }
+ return errors.New("unknown auth command")
+ case "tools":
+ ops, err := c.Operations(ctx)
+ if err != nil {
+ return err
+ }
+ return print(ops)
+ case "mcp":
+ if len(args) != 2 || args[1] != "serve" {
+ return errors.New("usage: oficina mcp serve")
+ }
+ ops, err := c.Operations(ctx)
+ if err != nil {
+ return err
+ }
+ s := mcp.NewServer(&mcp.Implementation{Name: "oficina", Version: "0.1.0"}, nil)
+ for _, op := range ops {
+ s.AddTool(&mcp.Tool{Name: op.Name, Description: op.Description, InputSchema: op.Input, OutputSchema: op.Output}, func(ctx context.Context, r *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ result, err := c.Call(ctx, op.Name, r.Params.Arguments)
+ if err != nil {
+ return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}}}, nil
+ }
+ raw, _ := json.Marshal(result)
+ return &mcp.CallToolResult{StructuredContent: result, Content: []mcp.Content{&mcp.TextContent{Text: string(raw)}}}, nil
+ })
+ }
+ return s.Run(ctx, &mcp.StdioTransport{})
+ }
+ if len(args) < 2 {
+ return errors.New("supply an operation name or app action")
+ }
+ name := args[1]
+ if args[0] != "call" {
+ name = args[0] + "_" + args[1]
+ }
+ fs := flag.NewFlagSet("call", flag.ContinueOnError)
+ team := fs.String("team", "", "selected team")
+ file := fs.String("input", "-", "JSON input file or - for stdin")
+ if err := fs.Parse(args[2:]); err != nil {
+ return err
+ }
+ var in io.Reader = os.Stdin
+ if *file != "-" {
+ f, err := os.Open(*file)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ in = f
+ }
+ raw, err := io.ReadAll(io.LimitReader(in, access.MaxPayload+1))
+ if err != nil || len(raw) > access.MaxPayload {
+ return errors.New("could not read operation input within the size limit")
+ }
+ if access.UniqueJSON(raw) != nil {
+ return errors.New("send one JSON object with unique field names")
+ }
+ var input map[string]any
+ if json.Unmarshal(raw, &input) != nil || input == nil {
+ return errors.New("send one JSON object")
+ }
+ if *team != "" {
+ if existing, ok := input["team"]; ok && existing != *team {
+ return errors.New("--team disagrees with the input team")
+ }
+ input["team"] = *team
+ }
+ raw, err = json.Marshal(input)
+ if err != nil {
+ return err
+ }
+ result, err := c.Call(ctx, name, raw)
+ if err != nil {
+ return err
+ }
+ return print(result)
+}
diff --git a/go.mod b/go.mod
index 4f4f286..30c4f7c 100644
--- a/go.mod
+++ b/go.mod
@@ -3,16 +3,29 @@ module amadan.net/oficina/agent-access
go 1.25.0
require (
+ github.com/gofrs/flock v0.12.1
github.com/google/jsonschema-go v0.4.3
github.com/modelcontextprotocol/go-sdk v1.7.0
+ github.com/zalando/go-keyring v0.2.8
+ golang.org/x/oauth2 v0.35.0
+ modernc.org/sqlite v1.55.0
)
require (
+ 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/google/uuid v1.6.0 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/ncruces/go-strftime v1.0.0 // indirect
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // 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
- golang.org/x/oauth2 v0.35.0 // indirect
- golang.org/x/sync v0.20.0 // indirect
- golang.org/x/sys v0.41.0 // indirect
+ golang.org/x/sync v0.21.0 // indirect
+ golang.org/x/sys v0.46.0 // indirect
golang.org/x/time v0.15.0 // indirect
+ modernc.org/libc v1.74.1 // indirect
+ modernc.org/mathutil v1.7.1 // indirect
+ modernc.org/memory v1.11.0 // indirect
)
diff --git a/go.sum b/go.sum
index f93aba1..e337fb9 100644
--- a/go.sum
+++ b/go.sum
@@ -1,24 +1,87 @@
+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/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/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=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
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/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/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.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
-golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
-golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
-golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+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=
+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/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
-golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
-golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
+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=
+modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc=
+modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
+modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
+modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
+modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
+modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
+modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
+modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
+modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
+modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
+modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
+modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
+modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
diff --git a/grant/server.go b/grant/server.go
new file mode 100644
index 0000000..c5024f9
--- /dev/null
+++ b/grant/server.go
@@ -0,0 +1,471 @@
+package grant
+
+import (
+ "context"
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "html/template"
+ "io"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "time"
+
+ access "amadan.net/oficina/agent-access"
+)
+
+type Client struct {
+ ID, Name string
+ Redirects []string
+ Loopback bool
+}
+type Team struct{ ID, Name string }
+type Config struct {
+ Origin string
+ Resource string
+ Store *Store
+ ConsentKey []byte
+ Clients []Client
+ Scopes map[string]string
+ // Subject reads a verified browser session. Empty means sign-in is needed.
+ Subject func(*http.Request) string
+ // Teams reads CURRENT memberships, including on token verification.
+ Teams func(context.Context, string) ([]Team, error)
+ SignInPath string
+}
+type Server struct {
+ cfg Config
+ aead cipher.AEAD
+ clients map[string]Client
+}
+type ticket struct {
+ Client, Redirect, Resource, Challenge, State, Subject, Nonce string
+ Scopes []string
+ Expires int64
+}
+
+func NewServer(cfg Config) (*Server, error) {
+ u, err := url.Parse(cfg.Origin)
+ if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" {
+ return nil, errors.New("grant issuer must be an HTTPS origin")
+ }
+ if cfg.Resource != cfg.Origin+"/mcp" || cfg.Store == nil || cfg.Subject == nil || cfg.Teams == nil || len(cfg.Scopes) == 0 || !strings.HasPrefix(cfg.SignInPath, "/") || strings.HasPrefix(cfg.SignInPath, "//") {
+ return nil, errors.New("incomplete grant configuration")
+ }
+ if len(cfg.ConsentKey) != 32 {
+ return nil, errors.New("a 32-byte consent encryption key is required")
+ }
+ block, err := aes.NewCipher(cfg.ConsentKey)
+ if err != nil {
+ return nil, err
+ }
+ aead, err := cipher.NewGCM(block)
+ if err != nil {
+ return nil, err
+ }
+ s := &Server{cfg: cfg, aead: aead, clients: map[string]Client{}}
+ for _, client := range cfg.Clients {
+ if client.ID == "" || client.Name == "" {
+ return nil, errors.New("invalid OAuth client")
+ }
+ if _, ok := s.clients[client.ID]; ok {
+ return nil, errors.New("duplicate OAuth client")
+ }
+ for _, raw := range client.Redirects {
+ if !validRedirect(raw) {
+ return nil, errors.New("invalid client redirect")
+ }
+ }
+ if len(client.Redirects) == 0 && !client.Loopback {
+ return nil, errors.New("client needs a redirect")
+ }
+ s.clients[client.ID] = client
+ }
+ if _, err = cfg.Store.DB.Exec(`CREATE TABLE IF NOT EXISTS agent_pending(hash TEXT PRIMARY KEY, expires INTEGER NOT NULL)`); err != nil {
+ return nil, err
+ }
+ return s, nil
+}
+func validRedirect(raw string) bool {
+ u, e := url.Parse(raw)
+ return e == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.Fragment == ""
+}
+func (c Client) validRedirect(raw string) bool {
+ for _, allowed := range c.Redirects {
+ if raw == allowed {
+ return true
+ }
+ }
+ u, e := url.Parse(raw)
+ return c.Loopback && e == nil && u.Scheme == "http" && u.Hostname() == "127.0.0.1" && u.Port() != "" && u.Path == "/callback" && u.User == nil && u.RawQuery == "" && u.Fragment == ""
+}
+func (s *Server) seal(t ticket) (string, error) {
+ raw, err := json.Marshal(t)
+ if err != nil {
+ return "", err
+ }
+ nonce := make([]byte, s.aead.NonceSize())
+ if _, err = rand.Read(nonce); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(s.aead.Seal(nonce, nonce, raw, []byte(s.cfg.Origin))), nil
+}
+func (s *Server) open(raw string) (ticket, error) {
+ var t ticket
+ b, err := base64.RawURLEncoding.DecodeString(raw)
+ n := s.aead.NonceSize()
+ if err != nil || len(b) < n || len(b) > 16384 {
+ return t, ErrCredential
+ }
+ b, err = s.aead.Open(nil, b[:n], b[n:], []byte(s.cfg.Origin))
+ if err != nil || json.Unmarshal(b, &t) != nil || t.Expires <= s.cfg.Store.Now().Unix() {
+ return t, ErrCredential
+ }
+ return t, nil
+}
+func (s *Server) Handler() http.Handler {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /.well-known/oauth-authorization-server", s.metadata)
+ mux.HandleFunc("GET /.well-known/oauth-protected-resource", s.resourceMetadata)
+ mux.HandleFunc("GET /oauth/authorize", s.authorize)
+ mux.HandleFunc("POST /oauth/authorize", s.approve)
+ mux.HandleFunc("POST /oauth/token", s.token)
+ mux.HandleFunc("POST /oauth/revoke", s.revoke)
+ mux.HandleFunc("POST /api/v1/credential", s.credential)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ expected, _ := url.Parse(s.cfg.Origin)
+ if r.Host != expected.Host {
+ http.NotFound(w, r)
+ return
+ }
+ mux.ServeHTTP(w, r)
+ })
+}
+func write(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+func fail(w http.ResponseWriter, status int, code string) {
+ write(w, status, map[string]string{"error": code})
+}
+func (s *Server) metadata(w http.ResponseWriter, r *http.Request) {
+ scopes := []string{}
+ for scope := range s.cfg.Scopes {
+ scopes = append(scopes, scope)
+ }
+ sort.Strings(scopes)
+ write(w, 200, map[string]any{"issuer": s.cfg.Origin, "authorization_endpoint": s.cfg.Origin + "/oauth/authorize", "token_endpoint": s.cfg.Origin + "/oauth/token", "revocation_endpoint": s.cfg.Origin + "/oauth/revoke", "response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"}, "code_challenge_methods_supported": []string{"S256"}, "token_endpoint_auth_methods_supported": []string{"none"}, "scopes_supported": scopes, "authorization_response_iss_parameter_supported": true})
+}
+func (s *Server) resourceMetadata(w http.ResponseWriter, r *http.Request) {
+ write(w, 200, map[string]any{"resource": s.cfg.Resource, "authorization_servers": []string{s.cfg.Origin}, "scopes_supported": sortedScopes(s.cfg.Scopes), "bearer_methods_supported": []string{"header"}})
+}
+func single(values url.Values) bool {
+ for _, xs := range values {
+ if len(xs) != 1 {
+ return false
+ }
+ }
+ return true
+}
+func (s *Server) authorize(w http.ResponseWriter, r *http.Request) {
+ if len(r.URL.RawQuery) > 8192 {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ q, err := url.ParseQuery(r.URL.RawQuery)
+ if err != nil || !single(q) {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ client, ok := s.clients[q.Get("client_id")]
+ if !ok || !client.validRedirect(q.Get("redirect_uri")) {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ challenge, err := base64.RawURLEncoding.DecodeString(q.Get("code_challenge"))
+ if err != nil || len(challenge) != 32 || q.Get("code_challenge_method") != "S256" || q.Get("response_type") != "code" || q.Get("resource") != s.cfg.Resource || len(q.Get("state")) < 16 {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ scopes := strings.Fields(q.Get("scope"))
+ if len(scopes) == 0 {
+ fail(w, 400, "invalid_scope")
+ return
+ }
+ seen := map[string]bool{}
+ for _, scope := range scopes {
+ if _, ok := s.cfg.Scopes[scope]; !ok || seen[scope] {
+ fail(w, 400, "invalid_scope")
+ return
+ }
+ seen[scope] = true
+ }
+ subject := s.cfg.Subject(r)
+ if subject == "" {
+ dest, _ := url.Parse(s.cfg.SignInPath)
+ v := dest.Query()
+ v.Set("return_to", r.URL.RequestURI())
+ dest.RawQuery = v.Encode()
+ http.Redirect(w, r, dest.String(), 303)
+ return
+ }
+ teams, err := s.cfg.Teams(r.Context(), subject)
+ if err != nil {
+ fail(w, 503, "temporarily_unavailable")
+ return
+ }
+ if len(teams) == 0 {
+ fail(w, 403, "access_denied")
+ return
+ }
+ t := ticket{Client: client.ID, Redirect: q.Get("redirect_uri"), Resource: s.cfg.Resource, Challenge: q.Get("code_challenge"), State: q.Get("state"), Subject: subject, Nonce: random(), Scopes: scopes, Expires: s.cfg.Store.Now().Add(5 * time.Minute).Unix()}
+ encoded, err := s.seal(t)
+ if err != nil {
+ fail(w, 500, "server_error")
+ return
+ }
+ if _, err = s.cfg.Store.DB.ExecContext(r.Context(), `INSERT INTO agent_pending(hash,expires) VALUES(?,?)`, hash(t.Nonce), t.Expires); err != nil {
+ fail(w, 503, "temporarily_unavailable")
+ return
+ }
+ http.SetCookie(w, &http.Cookie{Name: "__Host-oficina-consent", Value: t.Nonce, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: 300})
+ labels := []string{}
+ for _, scope := range scopes {
+ labels = append(labels, s.cfg.Scopes[scope])
+ }
+ w.Header().Set("Content-Security-Policy", "default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'")
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _ = consent.Execute(w, map[string]any{"Client": client.Name, "Ticket": encoded, "Teams": teams, "Scopes": labels})
+}
+
+var consent = template.Must(template.New("consent").Parse(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Connect to Oficina</title><main><h1>Connect {{.Client}} to Oficina</h1><p>This client will receive the content it reads and can act within the permissions you approve.</p><ul>{{range .Scopes}}<li>{{.}}</li>{{end}}</ul><form method="post" action="/oauth/authorize"><input type="hidden" name="ticket" value="{{.Ticket}}"><fieldset><legend>Choose teams</legend>{{range .Teams}}<label><input type="checkbox" name="team" value="{{.ID}}">{{.Name}}</label><br>{{end}}</fieldset><button name="decision" value="approve">Allow access</button><button name="decision" value="deny">Cancel</button></form></main></html>`))
+
+func (s *Server) approve(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Origin") != s.cfg.Origin {
+ fail(w, 403, "access_denied")
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, 16384)
+ if r.ParseForm() != nil || len(r.PostForm["ticket"]) != 1 || len(r.PostForm["decision"]) != 1 {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ t, err := s.open(r.PostForm.Get("ticket"))
+ cookie, cerr := r.Cookie("__Host-oficina-consent")
+ if err != nil || cerr != nil || subtle.ConstantTimeCompare([]byte(cookie.Value), []byte(t.Nonce)) != 1 || s.cfg.Subject(r) != t.Subject {
+ fail(w, 403, "access_denied")
+ return
+ }
+ decision := r.PostForm.Get("decision")
+ if decision != "approve" && decision != "deny" {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ teams, err := s.cfg.Teams(r.Context(), t.Subject)
+ if err != nil {
+ fail(w, 503, "temporarily_unavailable")
+ return
+ }
+ allowed := map[string]bool{}
+ for _, team := range teams {
+ allowed[team.ID] = true
+ }
+ selected := r.PostForm["team"]
+ seen := map[string]bool{}
+ for _, team := range selected {
+ if !allowed[team] || seen[team] {
+ fail(w, 403, "access_denied")
+ return
+ }
+ seen[team] = true
+ }
+ if decision == "approve" && len(selected) == 0 {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ result, err := s.cfg.Store.DB.ExecContext(r.Context(), `DELETE FROM agent_pending WHERE hash=? AND expires>?`, hash(t.Nonce), s.cfg.Store.Now().Unix())
+ if err != nil {
+ fail(w, 503, "temporarily_unavailable")
+ return
+ }
+ n, _ := result.RowsAffected()
+ if n != 1 {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ http.SetCookie(w, &http.Cookie{Name: "__Host-oficina-consent", Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1})
+ dest, _ := url.Parse(t.Redirect)
+ q := dest.Query()
+ q.Set("state", t.State)
+ q.Set("iss", s.cfg.Origin)
+ if decision == "deny" {
+ q.Set("error", "access_denied")
+ } else {
+ code, err := s.cfg.Store.CreateCode(r.Context(), Grant{Subject: t.Subject, ClientID: t.Client, Teams: selected, Scopes: t.Scopes}, Code{t.Redirect, t.Challenge, t.Resource})
+ if err != nil {
+ fail(w, 503, "temporarily_unavailable")
+ return
+ }
+ q.Set("code", code)
+ }
+ dest.RawQuery = q.Encode()
+ http.Redirect(w, r, dest.String(), 303)
+}
+func form(w http.ResponseWriter, r *http.Request) bool {
+ r.Body = http.MaxBytesReader(w, r.Body, 16384)
+ if r.ParseForm() != nil || !single(r.PostForm) || len(r.URL.RawQuery) > 0 {
+ fail(w, 400, "invalid_request")
+ return false
+ }
+ return true
+}
+func (s *Server) token(w http.ResponseWriter, r *http.Request) {
+ if !form(w, r) {
+ return
+ }
+ if _, ok := s.clients[r.PostForm.Get("client_id")]; !ok {
+ fail(w, 400, "invalid_client")
+ return
+ }
+ var token TokenResponse
+ var err error
+ switch r.PostForm.Get("grant_type") {
+ case "authorization_code":
+ token, err = s.cfg.Store.Exchange(r.Context(), r.PostForm.Get("code"), r.PostForm.Get("client_id"), r.PostForm.Get("redirect_uri"), r.PostForm.Get("resource"), r.PostForm.Get("code_verifier"))
+ case "refresh_token":
+ token, err = s.cfg.Store.Refresh(r.Context(), r.PostForm.Get("refresh_token"), r.PostForm.Get("client_id"), r.PostForm.Get("resource"))
+ default:
+ fail(w, 400, "unsupported_grant_type")
+ return
+ }
+ if errors.Is(err, ErrCredential) {
+ fail(w, 400, "invalid_grant")
+ return
+ }
+ if err != nil {
+ fail(w, 503, "temporarily_unavailable")
+ return
+ }
+ write(w, 200, token)
+}
+func (s *Server) revoke(w http.ResponseWriter, r *http.Request) {
+ if !form(w, r) {
+ return
+ }
+ if _, ok := s.clients[r.PostForm.Get("client_id")]; !ok {
+ fail(w, 400, "invalid_client")
+ return
+ }
+ if err := s.cfg.Store.Revoke(r.Context(), r.PostForm.Get("token"), r.PostForm.Get("client_id")); err != nil {
+ fail(w, 503, "temporarily_unavailable")
+ return
+ }
+ w.WriteHeader(200)
+}
+func (s *Server) Verify(ctx context.Context, token string) (access.Principal, error) {
+ p, err := s.cfg.Store.Verify(ctx, token, s.cfg.Resource)
+ if err != nil {
+ return access.Principal{}, err
+ }
+ teams, err := s.cfg.Teams(ctx, p.Subject)
+ if err != nil {
+ return access.Principal{}, access.Fail("unavailable", "Authorization is temporarily unavailable.")
+ }
+ allowed := map[string]bool{}
+ for _, team := range teams {
+ allowed[team.ID] = true
+ }
+ filtered := []string{}
+ for _, team := range p.Teams {
+ if allowed[team] {
+ filtered = append(filtered, team)
+ }
+ }
+ p.Teams = filtered
+ if len(filtered) == 0 {
+ return access.Principal{}, access.Fail("unauthenticated", "This connection no longer has access.")
+ }
+ return p, nil
+}
+
+// ResourceHandler advertises discovery on failed MCP authentication, while the
+// registry still verifies the bearer on each request.
+func (s *Server) ResourceHandler(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="`+s.cfg.Origin+`/.well-known/oauth-protected-resource"`)
+ next.ServeHTTP(w, r)
+ })
+}
+
+func sortedScopes(scopes map[string]string) []string {
+ out := []string{}
+ for scope := range scopes {
+ if scope != "offline_access" {
+ out = append(out, scope)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+// The bearer proves possession; the supplied resource is checked against the
+// token's stored audience. Apps use their configured audience, never user input.
+func (s *Server) credential(w http.ResponseWriter, r *http.Request) {
+ parts := strings.Fields(r.Header.Get("Authorization"))
+ if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
+ fail(w, 401, "invalid_token")
+ return
+ }
+ body, err := io.ReadAll(io.LimitReader(r.Body, 8193))
+ if err != nil || len(body) > 8192 || access.UniqueJSON(body) != nil {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ var in struct {
+ Resource string `json:"resource"`
+ }
+ if json.Unmarshal(body, &in) != nil || in.Resource == "" {
+ fail(w, 400, "invalid_request")
+ return
+ }
+ p, err := s.cfg.Store.Verify(r.Context(), parts[1], in.Resource)
+ if err != nil {
+ if access.SafeFailure(err).Code == "unavailable" {
+ fail(w, 503, "temporarily_unavailable")
+ } else {
+ fail(w, 401, "invalid_token")
+ }
+ return
+ }
+ teams, err := s.cfg.Teams(r.Context(), p.Subject)
+ if err != nil {
+ fail(w, 503, "temporarily_unavailable")
+ return
+ }
+ allowed := map[string]bool{}
+ for _, team := range teams {
+ allowed[team.ID] = true
+ }
+ filtered := []string{}
+ for _, team := range p.Teams {
+ if allowed[team] {
+ filtered = append(filtered, team)
+ }
+ }
+ p.Teams = filtered
+ if len(filtered) == 0 {
+ fail(w, 401, "invalid_token")
+ return
+ }
+ write(w, 200, map[string]any{"resource": in.Resource, "principal": p})
+}
diff --git a/grant/server_test.go b/grant/server_test.go
new file mode 100644
index 0000000..0d60624
--- /dev/null
+++ b/grant/server_test.go
@@ -0,0 +1,256 @@
+package grant
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ access "amadan.net/oficina/agent-access"
+ "amadan.net/oficina/agent-access/client"
+ "golang.org/x/oauth2"
+ _ "modernc.org/sqlite"
+)
+
+type memoryStore struct{ c client.Credentials }
+
+func (m *memoryStore) Load() (client.Credentials, error) { return m.c, nil }
+func (m *memoryStore) Save(c client.Credentials) error { m.c = c; return nil }
+func (m *memoryStore) Delete() error { m.c = client.Credentials{}; return nil }
+func setup(t *testing.T) (*Server, *httptest.Server, *bool) {
+ t.Helper()
+ db, err := sql.Open("sqlite", t.TempDir()+"/grants.sqlite")
+ if err != nil {
+ t.Fatal(err)
+ }
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { db.Close() })
+ store, err := NewStore(context.Background(), db)
+ if err != nil {
+ t.Fatal(err)
+ }
+ admitted := true
+ var handler http.Handler
+ ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler.ServeHTTP(w, r) }))
+ t.Cleanup(ts.Close)
+ s, err := NewServer(Config{Origin: ts.URL, Resource: ts.URL + "/mcp", Store: store, ConsentKey: []byte(strings.Repeat("k", 32)), Clients: []Client{{ID: client.ClientID, Name: "Oficina CLI", Loopback: true}}, Scopes: map[string]string{"notes:write": "Create and edit notes", "offline_access": "Keep this connection"}, Subject: func(r *http.Request) string {
+ if r.Header.Get("Test-Session") == "signed-in" {
+ return "opaque-person"
+ }
+ return ""
+ }, Teams: func(context.Context, string) ([]Team, error) {
+ if admitted {
+ return []Team{{ID: "acme", Name: "Acme"}}, nil
+ }
+ return nil, nil
+ }, SignInPath: "/signin"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ handler = s.Handler()
+ return s, ts, &admitted
+}
+func TestBrowserLoginRefreshReplayAndRevocation(t *testing.T) {
+ s, ts, admitted := setup(t)
+ memory := &memoryStore{}
+ c := client.New(memory)
+ c.HTTP = ts.Client()
+ c.HTTP.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ browser := func(raw string) error {
+ req, _ := http.NewRequest("GET", raw, nil)
+ req.Header.Set("Test-Session", "signed-in")
+ resp, err := c.HTTP.Do(req)
+ if err != nil {
+ return err
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != 200 {
+ t.Fatalf("consent: %d %s", resp.StatusCode, body)
+ }
+ ticket := regexp.MustCompile(`name="ticket" value="([^"]+)"`).FindSubmatch(body)
+ if len(ticket) != 2 {
+ t.Fatalf("missing consent ticket: %s", body)
+ }
+ form := url.Values{"ticket": {string(ticket[1])}, "team": {"acme"}, "decision": {"approve"}}
+ post, _ := http.NewRequest("POST", ts.URL+"/oauth/authorize", strings.NewReader(form.Encode()))
+ post.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ post.Header.Set("Origin", ts.URL)
+ post.Header.Set("Test-Session", "signed-in")
+ for _, cookie := range resp.Cookies() {
+ post.AddCookie(cookie)
+ }
+ result, err := c.HTTP.Do(post)
+ if err != nil {
+ return err
+ }
+ result.Body.Close()
+ if result.StatusCode != 303 {
+ t.Fatalf("approve %d", result.StatusCode)
+ }
+ // The same form cannot create a second grant.
+ replay := post.Clone(context.Background())
+ replay.Body = io.NopCloser(strings.NewReader(form.Encode()))
+ replayed, err := c.HTTP.Do(replay)
+ if err != nil {
+ return err
+ }
+ replayed.Body.Close()
+ if replayed.StatusCode != 400 {
+ t.Fatalf("consent replay %d", replayed.StatusCode)
+ }
+ callback, err := http.Get(result.Header.Get("Location"))
+ if err != nil {
+ return err
+ }
+ callback.Body.Close()
+ if callback.StatusCode != 200 {
+ t.Fatalf("callback %d", callback.StatusCode)
+ }
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := c.Login(ctx, ts.URL, []string{"notes:write", "offline_access"}, browser); err != nil {
+ t.Fatal(err)
+ }
+ original := memory.c.Token
+ p, err := s.Verify(ctx, original.AccessToken)
+ if err != nil || !p.Allows("acme", "notes:write") || p.Subject != "opaque-person" {
+ t.Fatalf("principal %+v %v", p, err)
+ }
+ downstream, err := s.cfg.Store.Downstream(ctx, p, "https://notes.example/api/v1", "acme", []string{"notes:write"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote, err := access.NewRemoteVerifier(ts.URL, "https://notes.example/api/v1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote.Client = ts.Client()
+ narrowed, err := remote.Verify(ctx, downstream)
+ if err != nil || len(narrowed.Teams) != 1 || len(narrowed.Scopes) != 1 || narrowed.Scopes[0] != "notes:write" {
+ t.Fatalf("downstream: %+v %v", narrowed, err)
+ }
+ if _, err = remote.Verify(ctx, original.AccessToken); err == nil {
+ t.Fatal("suite token accepted at an app audience")
+ }
+ if _, err = s.cfg.Store.Downstream(ctx, p, "https://notes.example/api/v1", "other", []string{"notes:write"}); err == nil {
+ t.Fatal("cross-team delegation")
+ }
+ if _, err = s.cfg.Store.Downstream(ctx, p, "https://notes.example/api/v1", "acme", []string{"notes:delete"}); err == nil {
+ t.Fatal("scope escalation")
+ }
+ if _, err = s.cfg.Store.Verify(ctx, original.AccessToken, ts.URL+"/another-app"); err == nil {
+ t.Fatal("wrong audience accepted")
+ }
+ *admitted = false
+ if _, err = s.Verify(ctx, original.AccessToken); err == nil {
+ t.Fatal("removed membership accepted")
+ }
+ *admitted = true
+ rotated, err := s.cfg.Store.Refresh(ctx, original.RefreshToken, client.ClientID, s.cfg.Resource)
+ if err != nil || rotated.RefreshToken == original.RefreshToken {
+ t.Fatalf("refresh: %v", err)
+ }
+ if _, err = s.Verify(ctx, rotated.AccessToken); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.cfg.Store.Refresh(ctx, original.RefreshToken, client.ClientID, s.cfg.Resource); err == nil {
+ t.Fatal("refresh replay accepted")
+ }
+ if _, err = s.Verify(ctx, rotated.AccessToken); err == nil {
+ t.Fatal("refresh replay did not revoke family")
+ }
+ if _, err = remote.Verify(ctx, downstream); err == nil {
+ t.Fatal("revoked downstream token accepted")
+ }
+ // Tokens are stored as fingerprints, never their bearer values.
+ for _, secret := range []string{original.AccessToken, original.RefreshToken, rotated.AccessToken} {
+ var n int
+ if err := s.cfg.Store.DB.QueryRow(`SELECT COUNT(*) FROM agent_tokens WHERE hash=?`, secret).Scan(&n); err != nil || n != 0 {
+ t.Fatal("plaintext token stored")
+ }
+ }
+}
+func TestCodeBindingAndExpiry(t *testing.T) {
+ s, _, _ := setup(t)
+ ctx := context.Background()
+ verifier := oauth2.GenerateVerifier()
+ newCode := func() string {
+ code, err := s.cfg.Store.CreateCode(ctx, Grant{Subject: "opaque-person", ClientID: client.ClientID, Teams: []string{"acme"}, Scopes: []string{"notes:write"}}, Code{Redirect: "http://127.0.0.1:1234/callback", Challenge: oauth2.S256ChallengeFromVerifier(verifier), Resource: s.cfg.Resource})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return code
+ }
+ code := newCode()
+ for _, tc := range []struct{ client, redirect, resource, verifier string }{{"attacker", "http://127.0.0.1:1234/callback", s.cfg.Resource, verifier}, {client.ClientID, "http://127.0.0.1:9999/callback", s.cfg.Resource, verifier}, {client.ClientID, "http://127.0.0.1:1234/callback", s.cfg.Resource + "/wrong", verifier}, {client.ClientID, "http://127.0.0.1:1234/callback", s.cfg.Resource, oauth2.GenerateVerifier()}} {
+ if _, err := s.cfg.Store.Exchange(ctx, code, tc.client, tc.redirect, tc.resource, tc.verifier); err == nil {
+ t.Fatal("unbound code exchange")
+ }
+ }
+ token, err := s.cfg.Store.Exchange(ctx, code, client.ClientID, "http://127.0.0.1:1234/callback", s.cfg.Resource, verifier)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.cfg.Store.Exchange(ctx, code, client.ClientID, "http://127.0.0.1:1234/callback", s.cfg.Resource, verifier); err == nil {
+ t.Fatal("code reused")
+ }
+ if err = s.cfg.Store.Revoke(ctx, token.AccessToken, client.ClientID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.Verify(ctx, token.AccessToken); err == nil {
+ t.Fatal("revoked token accepted")
+ }
+ code = newCode()
+ future := time.Now().Add(3 * time.Minute)
+ s.cfg.Store.Now = func() time.Time { return future }
+ if _, err = s.cfg.Store.Exchange(ctx, code, client.ClientID, "http://127.0.0.1:1234/callback", s.cfg.Resource, verifier); err == nil {
+ t.Fatal("expired code accepted")
+ }
+}
+func TestConsentAndDiscoveryRefusals(t *testing.T) {
+ s, ts, _ := setup(t)
+ for _, path := range []string{"/oauth/authorize?client_id=unknown&redirect_uri=https://evil.example/callback", "/oauth/authorize?client_id=oficina-cli&client_id=evil", "/oauth/authorize?client_id=oficina-cli&redirect_uri=http://localhost:1234/callback"} {
+ req, _ := http.NewRequest("GET", ts.URL+path, nil)
+ req.Header.Set("Test-Session", "signed-in")
+ resp, err := ts.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != 400 || resp.Header.Get("Location") != "" {
+ t.Fatal("invalid redirect accepted")
+ }
+ }
+ registry, err := access.NewRegistry()
+ if err != nil {
+ t.Fatal(err)
+ }
+ handler := s.ResourceHandler(registry.MCP(s))
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, httptest.NewRequest("POST", ts.URL+"/mcp", nil))
+ if w.Code != 401 || !strings.Contains(w.Header().Get("WWW-Authenticate"), "resource_metadata=") {
+ t.Fatalf("discovery challenge: %d %s", w.Code, w.Header())
+ }
+ resp, err := ts.Client().Get(ts.URL + "/.well-known/oauth-protected-resource")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ var metadata map[string]any
+ if json.NewDecoder(resp.Body).Decode(&metadata) != nil {
+ t.Fatal("metadata")
+ }
+ if len(metadata["scopes_supported"].([]any)) == 0 {
+ t.Fatal("no discoverable scopes")
+ }
+}
diff --git a/grant/store.go b/grant/store.go
new file mode 100644
index 0000000..fcb2378
--- /dev/null
+++ b/grant/store.go
@@ -0,0 +1,294 @@
+// Package grant implements Oficina's temporary delegated credential store.
+// Its API is independent of the MCP adapter so Rastrillo can replace it later.
+package grant
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "time"
+
+ access "amadan.net/oficina/agent-access"
+)
+
+const schema = `
+CREATE TABLE IF NOT EXISTS agent_grants (
+ id TEXT PRIMARY KEY, subject TEXT NOT NULL, client_id TEXT NOT NULL,
+ teams TEXT NOT NULL, scopes TEXT NOT NULL, created INTEGER NOT NULL,
+ expires INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
+CREATE TABLE IF NOT EXISTS agent_codes (
+ hash TEXT PRIMARY KEY, grant_id TEXT NOT NULL, redirect TEXT NOT NULL,
+ challenge TEXT NOT NULL, resource TEXT NOT NULL, expires INTEGER NOT NULL);
+CREATE TABLE IF NOT EXISTS agent_tokens (
+ hash TEXT PRIMARY KEY, grant_id TEXT NOT NULL, kind TEXT NOT NULL,
+ resource TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0,
+ team TEXT NOT NULL DEFAULT '', scopes TEXT NOT NULL DEFAULT '');
+CREATE INDEX IF NOT EXISTS agent_tokens_grant ON agent_tokens(grant_id);
+`
+
+type Store struct {
+ DB *sql.DB
+ Now func() time.Time
+}
+
+func NewStore(ctx context.Context, db *sql.DB) (*Store, error) {
+ if db == nil {
+ return nil, errors.New("grant database required")
+ }
+ if _, err := db.ExecContext(ctx, schema); err != nil {
+ return nil, err
+ }
+ return &Store{DB: db, Now: time.Now}, nil
+}
+func random() string {
+ var b [32]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ panic(err)
+ }
+ return base64.RawURLEncoding.EncodeToString(b[:])
+}
+func hash(s string) string { sum := sha256.Sum256([]byte(s)); return hex.EncodeToString(sum[:]) }
+
+type Grant struct {
+ ID, Subject, ClientID string
+ Teams, Scopes []string
+ Expires time.Time
+}
+type Code struct{ Redirect, Challenge, Resource string }
+type TokenResponse struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn int `json:"expires_in"`
+ RefreshToken string `json:"refresh_token,omitempty"`
+ Scope string `json:"scope"`
+}
+
+var ErrCredential = errors.New("invalid or expired credential")
+
+func (s *Store) CreateCode(ctx context.Context, g Grant, c Code) (string, error) {
+ now := s.Now()
+ if g.ID == "" {
+ g.ID = random()
+ }
+ code := random()
+ teams, _ := json.Marshal(g.Teams)
+ scopes, _ := json.Marshal(g.Scopes)
+ tx, err := s.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return "", err
+ }
+ defer tx.Rollback()
+ if _, err = tx.ExecContext(ctx, `INSERT INTO agent_grants(id,subject,client_id,teams,scopes,created,expires) VALUES(?,?,?,?,?,?,?)`, g.ID, g.Subject, g.ClientID, string(teams), string(scopes), now.Unix(), now.Add(90*24*time.Hour).Unix()); err != nil {
+ return "", err
+ }
+ if _, err = tx.ExecContext(ctx, `INSERT INTO agent_codes(hash,grant_id,redirect,challenge,resource,expires) VALUES(?,?,?,?,?,?)`, hash(code), g.ID, c.Redirect, c.Challenge, c.Resource, now.Add(2*time.Minute).Unix()); err != nil {
+ return "", err
+ }
+ return code, tx.Commit()
+}
+func loadGrant(ctx context.Context, tx *sql.Tx, id string, now int64) (Grant, error) {
+ var g Grant
+ var teams, scopes string
+ var expires int64
+ err := tx.QueryRowContext(ctx, `SELECT id,subject,client_id,teams,scopes,expires FROM agent_grants WHERE id=? AND revoked=0 AND expires>?`, id, now).Scan(&g.ID, &g.Subject, &g.ClientID, &teams, &scopes, &expires)
+ if err != nil {
+ return g, ErrCredential
+ }
+ if json.Unmarshal([]byte(teams), &g.Teams) != nil || json.Unmarshal([]byte(scopes), &g.Scopes) != nil {
+ return g, ErrCredential
+ }
+ g.Expires = time.Unix(expires, 0)
+ return g, nil
+}
+func (s *Store) Exchange(ctx context.Context, code, client, redirect, resource, verifier string) (TokenResponse, error) {
+ if len(verifier) < 43 || len(verifier) > 128 {
+ return TokenResponse{}, ErrCredential
+ }
+ for _, c := range verifier {
+ if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {
+ return TokenResponse{}, ErrCredential
+ }
+ }
+ tx, err := s.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return TokenResponse{}, err
+ }
+ defer tx.Rollback()
+ var id, challenge string
+ // Consuming and minting share the transaction so a retried code cannot mint twice.
+ err = tx.QueryRowContext(ctx, `DELETE FROM agent_codes WHERE hash=? AND redirect=? AND resource=? AND expires>? RETURNING grant_id,challenge`, hash(code), redirect, resource, s.Now().Unix()).Scan(&id, &challenge)
+ if err != nil {
+ return TokenResponse{}, ErrCredential
+ }
+ sum := sha256.Sum256([]byte(verifier))
+ if base64.RawURLEncoding.EncodeToString(sum[:]) != challenge {
+ return TokenResponse{}, ErrCredential
+ }
+ g, err := loadGrant(ctx, tx, id, s.Now().Unix())
+ if err != nil || g.ClientID != client {
+ return TokenResponse{}, ErrCredential
+ }
+ out, err := s.mint(ctx, tx, g, resource, true)
+ if err != nil {
+ return TokenResponse{}, err
+ }
+ return out, tx.Commit()
+}
+func (s *Store) mint(ctx context.Context, tx *sql.Tx, g Grant, resource string, refresh bool) (TokenResponse, error) {
+ now := s.Now()
+ expires := now.Add(5 * time.Minute)
+ if g.Expires.Before(expires) {
+ expires = g.Expires
+ }
+ out := TokenResponse{AccessToken: random(), TokenType: "Bearer", ExpiresIn: int(expires.Sub(now).Seconds()), Scope: join(g.Scopes)}
+ if _, err := tx.ExecContext(ctx, `INSERT INTO agent_tokens(hash,grant_id,kind,resource,expires) VALUES(?,?,'access',?,?)`, hash(out.AccessToken), g.ID, resource, expires.Unix()); err != nil {
+ return TokenResponse{}, err
+ }
+ if refresh && has(g.Scopes, "offline_access") {
+ out.RefreshToken = random()
+ expiry := now.Add(30 * 24 * time.Hour)
+ if g.Expires.Before(expiry) {
+ expiry = g.Expires
+ }
+ if _, err := tx.ExecContext(ctx, `INSERT INTO agent_tokens(hash,grant_id,kind,resource,expires) VALUES(?,?,'refresh',?,?)`, hash(out.RefreshToken), g.ID, resource, expiry.Unix()); err != nil {
+ return TokenResponse{}, err
+ }
+ }
+ return out, nil
+}
+func (s *Store) Refresh(ctx context.Context, token, client, resource string) (TokenResponse, error) {
+ tx, err := s.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return TokenResponse{}, err
+ }
+ defer tx.Rollback()
+ var id, audience string
+ var expires int64
+ var used int
+ err = tx.QueryRowContext(ctx, `SELECT grant_id,resource,expires,used FROM agent_tokens WHERE hash=? AND kind='refresh'`, hash(token)).Scan(&id, &audience, &expires, &used)
+ if err != nil {
+ return TokenResponse{}, ErrCredential
+ }
+ g, err := loadGrant(ctx, tx, id, s.Now().Unix())
+ if err != nil || g.ClientID != client || resource != "" && resource != audience {
+ return TokenResponse{}, ErrCredential
+ }
+ if used != 0 {
+ if _, err = tx.ExecContext(ctx, `UPDATE agent_grants SET revoked=1 WHERE id=?`, id); err != nil {
+ return TokenResponse{}, err
+ }
+ if err = tx.Commit(); err != nil {
+ return TokenResponse{}, err
+ }
+ return TokenResponse{}, ErrCredential
+ }
+ if expires <= s.Now().Unix() {
+ return TokenResponse{}, ErrCredential
+ }
+ result, err := tx.ExecContext(ctx, `UPDATE agent_tokens SET used=1 WHERE hash=? AND used=0`, hash(token))
+ if err != nil {
+ return TokenResponse{}, err
+ }
+ n, _ := result.RowsAffected()
+ if n != 1 {
+ return TokenResponse{}, ErrCredential
+ }
+ out, err := s.mint(ctx, tx, g, audience, true)
+ if err != nil {
+ return TokenResponse{}, err
+ }
+ return out, tx.Commit()
+}
+func (s *Store) Verify(ctx context.Context, token, resource string) (access.Principal, error) {
+ var p access.Principal
+ var teams, scopes, tokenTeam, tokenScopes string
+ err := s.DB.QueryRowContext(ctx, `SELECT g.subject,g.client_id,g.id,g.teams,g.scopes,t.team,t.scopes FROM agent_tokens t JOIN agent_grants g ON g.id=t.grant_id WHERE t.hash=? AND t.kind='access' AND t.resource=? AND t.expires>? AND g.expires>? AND g.revoked=0`, hash(token), resource, s.Now().Unix(), s.Now().Unix()).Scan(&p.Subject, &p.Client, &p.Grant, &teams, &scopes, &tokenTeam, &tokenScopes)
+ if errors.Is(err, sql.ErrNoRows) {
+ return p, access.Fail("unauthenticated", "Connect to Oficina again.")
+ }
+ if err != nil {
+ return p, access.Fail("unavailable", "Authorization is temporarily unavailable.")
+ }
+ if json.Unmarshal([]byte(teams), &p.Teams) != nil || json.Unmarshal([]byte(scopes), &p.Scopes) != nil {
+ return access.Principal{}, access.Fail("unavailable", "Authorization is temporarily unavailable.")
+ }
+ if tokenTeam != "" {
+ if !has(p.Teams, tokenTeam) {
+ return access.Principal{}, access.Fail("unauthenticated", "Connect to Oficina again.")
+ }
+ p.Teams = []string{tokenTeam}
+ }
+ if tokenScopes != "" {
+ var narrowed []string
+ if json.Unmarshal([]byte(tokenScopes), &narrowed) != nil {
+ return access.Principal{}, access.Fail("unavailable", "Authorization is temporarily unavailable.")
+ }
+ approved := []string{}
+ for _, scope := range narrowed {
+ if has(p.Scopes, scope) {
+ approved = append(approved, scope)
+ }
+ }
+ p.Scopes = approved
+ }
+ return p, nil
+}
+func (s *Store) Revoke(ctx context.Context, token, client string) error {
+ _, err := s.DB.ExecContext(ctx, `UPDATE agent_grants SET revoked=1 WHERE client_id=? AND id IN (SELECT grant_id FROM agent_tokens WHERE hash=?)`, client, hash(token))
+ return err
+}
+func has(xs []string, x string) bool {
+ for _, s := range xs {
+ if s == x {
+ return true
+ }
+ }
+ return false
+}
+func join(xs []string) string {
+ out := ""
+ for i, s := range xs {
+ if i > 0 {
+ out += " "
+ }
+ out += s
+ }
+ return out
+}
+
+// Downstream attenuates an already verified connection to one team, resource and
+// scope set. Only trusted routing code chooses the destination resource.
+func (s *Store) Downstream(ctx context.Context, p access.Principal, resource, team string, scopes []string) (string, error) {
+ if resource == "" || team == "" || len(scopes) == 0 {
+ return "", ErrCredential
+ }
+ tx, err := s.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return "", err
+ }
+ defer tx.Rollback()
+ g, err := loadGrant(ctx, tx, p.Grant, s.Now().Unix())
+ if err != nil || g.Subject != p.Subject || g.ClientID != p.Client || !has(g.Teams, team) || !has(p.Teams, team) {
+ return "", ErrCredential
+ }
+ for _, scope := range scopes {
+ if !has(g.Scopes, scope) || !has(p.Scopes, scope) {
+ return "", ErrCredential
+ }
+ }
+ token := random()
+ encoded, _ := json.Marshal(scopes)
+ expires := s.Now().Add(time.Minute)
+ if g.Expires.Before(expires) {
+ expires = g.Expires
+ }
+ if _, err = tx.ExecContext(ctx, `INSERT INTO agent_tokens(hash,grant_id,kind,resource,expires,team,scopes) VALUES(?,?,'access',?,?,?,?)`, hash(token), g.ID, resource, expires.Unix(), team, string(encoded)); err != nil {
+ return "", err
+ }
+ return token, tx.Commit()
+}
diff --git a/http.go b/http.go
index 4088296..6266c78 100644
--- a/http.go
+++ b/http.go
@@ -33,7 +33,9 @@ func Authenticate(v Verifier, next http.Handler) http.Handler {
w.Header().Set("Cache-Control", "no-store")
parts := strings.Fields(r.Header.Get("Authorization"))
if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
- w.Header().Set("WWW-Authenticate", "Bearer")
+ if w.Header().Get("WWW-Authenticate") == "" {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ }
writeFailure(w, Fail("unauthenticated", "Connect to Oficina first."))
return
}
@@ -86,7 +88,9 @@ func writeFailure(w http.ResponseWriter, err error) {
status = 500
}
if status == 401 {
- w.Header().Set("WWW-Authenticate", "Bearer")
+ if w.Header().Get("WWW-Authenticate") == "" {
+ w.Header().Set("WWW-Authenticate", "Bearer")
+ }
}
writeJSON(w, status, map[string]any{"error": f})
}
diff --git a/operation.go b/operation.go
index f37c818..8bcd0ee 100644
--- a/operation.go
+++ b/operation.go
@@ -16,11 +16,11 @@ const MaxPayload = 2 << 20
// Principal is supplied by a verifier, never decoded from operation arguments.
type Principal struct {
- Subject string
- Client string
- Grant string
- Teams []string
- Scopes []string
+ Subject string `json:"subject"`
+ Client string `json:"client"`
+ Grant string `json:"grant"`
+ Teams []string `json:"teams"`
+ Scopes []string `json:"scopes"`
}
func (p Principal) Allows(team, scope string) bool {
diff --git a/remote.go b/remote.go
new file mode 100644
index 0000000..476cfcb
--- /dev/null
+++ b/remote.go
@@ -0,0 +1,59 @@
+package agentaccess
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+// RemoteVerifier checks an app-audience token online so revocation is observed
+// on the next request. Resolve the returned Home subject locally before use.
+type RemoteVerifier struct {
+ Endpoint, Audience string
+ Client *http.Client
+}
+
+func NewRemoteVerifier(issuer, audience string) (*RemoteVerifier, error) {
+ u, err := url.Parse(issuer)
+ a, ae := url.Parse(audience)
+ if err != nil || ae != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || a.Scheme != "https" || a.Host == "" || a.User != nil || a.RawQuery != "" || a.Fragment != "" {
+ return nil, Fail("invalid", "Use trusted HTTPS issuer and app resource URLs.")
+ }
+ return &RemoteVerifier{Endpoint: issuer + "/api/v1/credential", Audience: audience, Client: &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
+}
+func (v *RemoteVerifier) Verify(ctx context.Context, token string) (Principal, error) {
+ raw, _ := json.Marshal(map[string]string{"resource": v.Audience})
+ req, err := http.NewRequestWithContext(ctx, "POST", v.Endpoint, bytes.NewReader(raw))
+ if err != nil {
+ return Principal{}, Fail("unavailable", "Authorization is unavailable.")
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("Content-Type", "application/json")
+ response, err := v.Client.Do(req)
+ if err != nil {
+ return Principal{}, Fail("unavailable", "Authorization is unavailable.")
+ }
+ defer response.Body.Close()
+ if response.StatusCode == 401 {
+ return Principal{}, Fail("unauthenticated", "Connect to Oficina again.")
+ }
+ if response.StatusCode != 200 {
+ return Principal{}, Fail("unavailable", "Authorization is unavailable.")
+ }
+ body, err := io.ReadAll(io.LimitReader(response.Body, 65537))
+ if err != nil || len(body) > 65536 {
+ return Principal{}, Fail("unavailable", "Authorization is unavailable.")
+ }
+ var out struct {
+ Resource string `json:"resource"`
+ Principal Principal `json:"principal"`
+ }
+ if json.Unmarshal(body, &out) != nil || out.Resource != v.Audience || out.Principal.Subject == "" || out.Principal.Grant == "" {
+ return Principal{}, Fail("unavailable", "Authorization is unavailable.")
+ }
+ return out.Principal, nil
+}