
OAuth and OpenID Connect for an agent service in Go: sign-in, sessions, and each user’s own credentials
Sign people in, keep their tokens off the browser, and call other services with each user’s own credentials.
On the agent compass Stage 3 of 4 · Run the toolsAn agent that people use from a browser has three jobs that OAuth and OpenID Connect split between them. It has to know who is asking, which is signing in. It has to keep knowing it on every request after, which is the session. And it has to act at other services for that person, reading their calendar or filing issues in their tracker, with their rights and nobody else’s, which is their connected accounts.
OpenID Connect handles the first; OAuth handles the third. Each job has its own token, meant for a different party, and most mistakes in this area come from using one where another belongs. This page builds the service in Go and runs it offline, against an identity provider and a calendar service, with tests for each check. MCP authorization covers the other end: the server that receives a token and decides whether to accept it.
Four credentials, four audiences
- The ID token is for the agent service. Its audience is the service’s client ID, and it says who signed in, once. It is never sent to an API.
- An access token is for one API. The calendar’s is issued for the calendar, by the calendar’s authorization server, and the agent’s tools send it there and nowhere else.
- A refresh token is for the authorization server that issued it. It renews access tokens while the user is away, for as long as the connection lasts, which makes it the credential most worth stealing.
- The session cookie is for the browser. It holds a random ID and nothing else, and the service looks everything up from it.
The browser holds only the last. The other three stay on the server.
The whole thing, in one run
The demo starts an identity provider that people sign in with, a calendar API with its own authorization server, and the agent service, all on loopback addresses, with stand-ins for two people’s browsers. It prints every request and never a token:
In the log: agent is the agent service, idp the identity provider
users sign in with, cal-auth the calendar's authorization server,
and calendar its API. Lines starting "agent ->" are requests the
agent service makes; the rest are the browsers'.
0. The agent service starts and reads the identity provider's metadata
agent -> GET idp /.well-known/openid-configuration -> 200
1. Alice opens the agent service and signs in
alice GET agent / -> 302 to /login
alice GET agent /login -> 302 to idp/authorize
alice GET idp /authorize scope="email openid" S256, state, nonce -> 302 to agent/callback
agent -> POST idp /token authorization_code -> 200
agent -> GET idp /jwks -> 200
alice GET agent /callback code, state, iss=idp -> 200
alice GET agent / -> 200
page: signed in as alice@example.com
2. She asks for her next meeting
alice POST agent /ask -> 200
reply: I can't reach that account (calendar: not connected). Connect it, then ask again.
3. She connects her calendar
alice POST agent /connect/calendar -> 303 to cal-auth/authorize
alice GET cal-auth /authorize scope="calendar:read offline_access" resource=calendar S256, state -> 302 to agent/connect/calendar/callback
agent -> POST cal-auth /token authorization_code -> 200
alice GET agent /connect/calendar/callback code, state, iss=cal-auth -> 200
page: connected calendar
4. She asks again
agent -> GET calendar /events -> 200
alice POST agent /ask -> 200
reply: Next: "Design review" at 2026-11-03T14:00:00Z.
5. Ten minutes later, her token has expired; two questions at once
(these ran at the same time, so their lines are sorted)
agent -> GET calendar /events -> 200 (x2)
agent -> POST cal-auth /token refresh_token -> 200
alice POST agent /ask -> 200 (x2)
reply: Next: "Design review" at 2026-11-03T14:00:00Z. (x2)
6. Bob signs in and asks
bob GET agent / -> 302 to /login
bob GET agent /login -> 302 to idp/authorize
bob GET idp /authorize scope="email openid" S256, state, nonce -> 302 to agent/callback
agent -> POST idp /token authorization_code -> 200
bob GET agent /callback code, state, iss=idp -> 200
bob GET agent / -> 200
page: signed in as bob@example.com
bob POST agent /ask -> 200
reply: I can't reach that account (calendar: not connected). Connect it, then ask again.
7. A copy of alice's first refresh token is stolen
thief POST cal-auth /token refresh_token -> 401 invalid_client: client authentication failed
thief+secret POST cal-auth /token refresh_token -> 400 invalid_grant: refresh token already used: every token from this grant is revoked
agent -> POST cal-auth /token refresh_token -> 400 invalid_grant: unknown or revoked refresh token
alice POST agent /ask -> 200
reply: I can't reach that account (calendar: not connected: the connection was revoked). Connect it, then ask again.
8. Alice signs out
alice POST agent /logout -> 204
copy GET agent / -> 302 to /login
- Alice signs in. Her browser goes to the identity provider and back, the agent service redeems the code itself, and the browser ends with a session cookie.
- She asks for her next meeting. The agent’s tool needs her calendar, which she hasn’t connected.
- She connects it. This is a second authorization, at the calendar’s own authorization server, which asks for
offline_accessand so returns a refresh token. The service stores it encrypted. - She asks again, and the tool calls the calendar with her access token.
- Ten minutes later her access token has expired, and two questions arrive at once. Both tool calls need a fresh token, and the service sends one refresh for both.
- Bob signs in and asks. His agent can’t reach alice’s calendar, and it can’t reach his own until he connects it.
- A copy of alice’s first refresh token, the one rotated away in step 5, turns up in the wrong hands. Without the service’s client secret it is refused outright. With the secret, the calendar’s authorization server sees a used token presented again and revokes everything descended from it, so alice’s next question asks her to connect again.
- Alice signs out, and a copy of her old session cookie gets nothing.
Keep the tokens on the server
The service is a backend for frontend, the pattern RFC 10017 (OAuth 2.0 for Browser-Based Applications, August 2026) recommends first, in section 6.1.
The OAuth client is the server, a confidential client with a secret of its own, and every token lives there.
The browser gets an HttpOnly cookie that script can’t read, and a page with a script injected into it can’t take a token away, because the page never had one.
Such a script can still send requests as the user while the page is open, which no token storage prevents.
Keeping tokens off the browser takes away the part that outlives the page: a stolen refresh token works for weeks from anywhere.
// Config describes an agent service.
type Config struct {
BaseURL string // where browsers reach the service: https://agent.example.com
// The identity provider users sign in with, and the service's
// client there: a confidential client, since the secret never
// leaves the server.
Issuer, ClientID, ClientSecret string
Providers map[string]Provider // services users can connect, by name
Vault *Vault
Tools map[string]Tool // the agent's tools, by name
Model Model
Client *http.Client // for every request the service makes
Now func() time.Time
}
// A Provider is a service whose API the agent's tools call, once a user
// connects an account there.
type Provider struct {
Issuer string // its authorization server
AuthURL, TokenURL, RevokeURL string
ClientID, ClientSecret string
Resource string // its API, as a resource indicator (RFC 8707)
Scopes []string // what the tools need, and offline_access
// SendsIss says the authorization server puts iss in its answers
// (RFC 9207), as its metadata's
// authorization_response_iss_parameter_supported says: answers
// without it are then refused.
SendsIss bool
}
Start the sign-in
// startLogin sends the browser to the identity provider. state ties the
// answer to this browser, nonce ties the ID token to this sign-in, and
// the PKCE verifier ties the code to this server: a code stolen on its
// way back is useless without it.
func (s *Service) startLogin(w http.ResponseWriter, r *http.Request) {
p := s.remember(w, &pending{state: rand.Text(), nonce: rand.Text(),
verifier: oauth2.GenerateVerifier()})
u := s.signIn.AuthCodeURL(p.state, oidc.Nonce(p.nonce),
oauth2.S256ChallengeOption(p.verifier))
http.Redirect(w, r, u, http.StatusFound)
}
Three values go out with the browser, and each one stops a different attack:
stateties the answer to this browser. Without it, an attacker can finish their own sign-in in your browser, by getting it to open a callback URL carrying the attacker’s code, and you are using the agent as them.nonceties the ID token to this sign-in. The identity provider copies it into the ID token, so an ID token from another sign-in can’t be passed off as this one’s.- The PKCE verifier (RFC 7636) ties the code to this server. Only its hash goes out, and the code is worth nothing without the verifier. RFC 9700, the OAuth security best current practice, recommends it for confidential clients too, since a client secret doesn’t stop a code stolen on its way back from being redeemed by the client itself, in the attacker’s session.
All three are kept server-side, under a random ID in a short-lived cookie:
// remember stores p and gives this browser a cookie naming it. The
// cookie is SameSite=Lax: it must come back on the authorization
// server's redirect, which another site starts.
func (s *Service) remember(w http.ResponseWriter, p *pending) *pending {
id := rand.Text()
p.expires = s.cfg.Now().Add(10 * time.Minute)
s.mu.Lock()
s.pending[id] = p
s.mu.Unlock()
http.SetCookie(w, &http.Cookie{Name: loginCookie, Value: id, Path: "/",
MaxAge: 600, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
return p
}
// recall takes the flow this browser started, once, and checks the
// answer belongs to it: the same state, from the authorization server
// it was sent to, and not an error. An iss in the answer must name that
// server (RFC 9207), and when the server says it always sends one, an
// answer without one is refused.
func (s *Service) recall(w http.ResponseWriter, r *http.Request,
provider, issuer string, sendsIss bool) (*pending, error) {
c, err := r.Cookie(loginCookie)
if err != nil {
return nil, errors.New("this browser started no sign-in")
}
s.mu.Lock()
p := s.pending[c.Value]
delete(s.pending, c.Value) // one answer per flow
s.mu.Unlock()
http.SetCookie(w, &http.Cookie{Name: loginCookie, Path: "/", MaxAge: -1,
Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
q := r.URL.Query()
switch {
case p == nil || p.provider != provider || s.cfg.Now().After(p.expires):
return nil, errors.New("unknown or expired")
case subtle.ConstantTimeCompare([]byte(q.Get("state")), []byte(p.state)) != 1:
return nil, errors.New("the state doesn't match")
case (sendsIss || q.Has("iss")) && q.Get("iss") != issuer:
return nil, errors.New("the answer came from another authorization server")
case q.Get("error") != "":
return nil, fmt.Errorf("the authorization server said %s", q.Get("error"))
}
return p, nil
}
The login cookie is SameSite=Lax, because it must come back on the identity provider’s redirect, a navigation another site starts.
Finish it
// finishLogin takes the identity provider's answer: it checks the answer
// belongs to the sign-in this browser started, redeems the code, checks
// the ID token, and starts a session.
func (s *Service) finishLogin(w http.ResponseWriter, r *http.Request) {
p, err := s.recall(w, r, "", s.cfg.Issuer, s.idpIss)
if err != nil {
http.Error(w, "sign-in failed: "+err.Error(), http.StatusBadRequest)
return
}
ctx := oidc.ClientContext(r.Context(), s.cfg.Client)
tok, err := s.signIn.Exchange(ctx, r.URL.Query().Get("code"),
oauth2.VerifierOption(p.verifier))
if err != nil {
http.Error(w, "sign-in failed: the code was refused", http.StatusBadRequest)
return
}
raw, _ := tok.Extra("id_token").(string)
id, err := s.ids.Verify(ctx, raw)
if err != nil {
http.Error(w, "sign-in failed: bad ID token", http.StatusBadRequest)
return
}
var claims struct {
Email string `json:"email"`
Verified bool `json:"email_verified"`
AZP string `json:"azp"`
}
switch {
case id.Claims(&claims) != nil:
err = errors.New("unreadable claims")
case subtle.ConstantTimeCompare([]byte(id.Nonce), []byte(p.nonce)) != 1:
err = errors.New("the ID token is from another sign-in")
case claims.AZP != "" && claims.AZP != s.cfg.ClientID:
err = errors.New("the ID token was issued to another client")
}
if err != nil {
http.Error(w, "sign-in failed: "+err.Error(), http.StatusBadRequest)
return
}
s.startSession(w, id.Subject, claims.Email)
// A page, not a redirect: a session cookie with SameSite=Strict
// isn't sent on a redirect that began at another site, so the
// browser moves on from here, a navigation this site starts.
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, `<!doctype html><meta http-equiv="refresh" content="0;url=/">`)
}
- The answer must belong to this browser’s sign-in: the login cookie must name a sign-in in progress, the state must match, and the answer must come from the identity provider it was sent to. An
issin the answer must name that provider (RFC 9207), and when the provider’s metadata says it always sends one, an answer without one is refused. The sign-in is removed as it is read, so an answer works once. - The code is redeemed with the verifier, and with the client secret, in the request’s
Authorizationheader. - The ID token is checked by go-oidc, the maintained OpenID Connect library for Go: its signature, with the algorithm pinned to ES256, its issuer, that its audience includes this client, and its expiry.
- The nonce is checked here, because go-oidc doesn’t: its verifier leaves nonce to the caller, and so does
azp, the authorized party, which the next line checks when it is present. - A new session starts, and everything else from the sign-in is dropped. The service keeps who signed in and doesn’t keep the tokens: it has no API to call with them.
The callback answers with a page rather than a redirect.
The session cookie is SameSite=Strict, which browsers don’t send on a redirect that began at another site, so a redirect from the callback to / would arrive without it.
A page that sends the browser on is a navigation this site starts, and the cookie goes with it.
TestSignInRefuses sends six answers that must fail: one for a sign-in another browser started, a changed state, an answer with no iss from a server that always sends one, an answer naming another issuer, the attacker’s code with the victim’s state (PKCE stops it at the token endpoint), and a nonce changed on its way to the identity provider.
// TestSignInRefuses: an answer from the identity provider signs a
// browser in only if it belongs to the sign-in that browser started.
func TestSignInRefuses(t *testing.T) {
w := newTestWorld(t)
// start begins a sign-in in b and returns the URL the identity
// provider would send the browser back to.
start := func(b *http.Client, change func(url.Values)) *url.URL {
loc, _ := step(t, b, w.agent+"/login")
authz, _ := url.Parse(loc)
q := authz.Query()
if change != nil {
change(q)
}
authz.RawQuery = q.Encode()
loc, _ = step(t, b, authz.String())
back, _ := url.Parse(loc)
return back
}
with := func(u *url.URL, k, v string) string {
q := u.Query()
q.Set(k, v)
c := *u
c.RawQuery = q.Encode()
return c.String()
}
victim, attacker := w.browser("alice@example.com"), w.browser("mallory@example.com")
for _, c := range []struct {
name string
send func() (int, string)
}{
{"an answer this browser never asked for", func() (int, string) {
back := start(attacker, nil)
return do(t, w.browser("alice@example.com"), "GET", back.String(), "", "")
}},
{"a changed state", func() (int, string) {
return do(t, victim, "GET", with(start(victim, nil), "state", "guess"), "", "")
}},
{"an answer with no iss, from a server that always sends one", func() (int, string) {
back := start(victim, nil)
q := back.Query()
q.Del("iss")
back.RawQuery = q.Encode()
return do(t, victim, "GET", back.String(), "", "")
}},
{"an answer naming another issuer", func() (int, string) {
return do(t, victim, "GET", with(start(victim, nil), "iss", "https://evil.example"), "", "")
}},
{"the attacker's code, with the victim's state", func() (int, string) {
mine := start(attacker, nil)
theirs := start(victim, nil)
return do(t, victim, "GET", with(theirs, "code", mine.Query().Get("code")), "", "")
}},
{"a nonce changed on the way to the identity provider", func() (int, string) {
back := start(victim, func(q url.Values) { q.Set("nonce", "attacker's") })
return do(t, victim, "GET", back.String(), "", "")
}},
} {
code, body := c.send()
if code != http.StatusBadRequest || !strings.Contains(body, "sign-in failed") {
t.Errorf("%s: %d %q, want a refusal", c.name, code, body)
}
}
}
What the ID token is for
Its subject, sub, is who the user is to this identity provider.
Key everything on the issuer and the subject together, never on the email: addresses change, get reassigned, and at some providers can be set by the user.
The demo’s subjects happen to be addresses, which keeps the log readable.
The ID token is not an access token.
Its audience is the agent service, and an API that accepted it would accept a token issued for someone else.
The identity provider here types it JWT and its access tokens at+jwt, and the resource server’s verifier refuses anything not typed as an access token.
The session
// A session is a signed-in browser. The browser holds only its ID.
type session struct {
user, email string
started, seen time.Time
}
// startSession signs the browser in as user. Every sign-in gets a new
// session ID, never one the browser brought with it, so an attacker who
// planted a session ID before sign-in doesn't share the session after.
func (s *Service) startSession(w http.ResponseWriter, user, email string) {
id, now := rand.Text(), s.cfg.Now()
s.mu.Lock()
s.sessions[id] = &session{user: user, email: email, started: now, seen: now}
s.mu.Unlock()
http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: id, Path: "/",
Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode})
}
// session returns the browser's session, if it has one that hasn't been
// idle for 30 minutes or open for 12 hours.
func (s *Service) session(r *http.Request) (*session, string) {
c, err := r.Cookie(sessionCookie)
if err != nil {
return nil, ""
}
now := s.cfg.Now()
s.mu.Lock()
defer s.mu.Unlock()
ss := s.sessions[c.Value]
if ss == nil || now.Sub(ss.seen) > idleTimeout || now.Sub(ss.started) > maxSession {
delete(s.sessions, c.Value)
return nil, ""
}
ss.seen = now
return ss, c.Value
}
// signedIn wraps a handler that needs a session. A request that
// changes something must also come from the service's own pages: a
// browser sends Origin on every POST, and another site can't set it
// to this one.
func (s *Service) signedIn(h func(http.ResponseWriter, *http.Request,
*session)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ss, _ := s.session(r)
if ss == nil {
http.Error(w, "sign in first", http.StatusUnauthorized)
return
}
if r.Method == http.MethodPost && r.Header.Get("Origin") != s.origin() {
http.Error(w, "cross-site request refused", http.StatusForbidden)
return
}
h(w, r, ss)
}
}
The cookie’s name starts with __Host-Http-, the prefix RFC 10017 asks for: __Host- makes browsers refuse it unless it is Secure, has Path=/, and names no domain, so a subdomain can’t set it, and Http- requires HttpOnly, so no script can set it or read it.
Every sign-in gets a new session ID, so an ID planted in the browser before sign-in isn’t the one that becomes signed in.
A session ends after 30 minutes idle or 12 hours in all, and signing out deletes it on the server, so a copy of the cookie stops working too, which is the last line of step 8.
A POST must carry an Origin header naming the service.
Browsers send one on every POST, and a page on another site can’t make it say this site, so a form on that site can’t make a signed-in user’s browser ask the agent to do something.
With SameSite=Strict as well, the cookie isn’t sent on such a request in the first place.
Connect the user’s accounts
The calendar is a separate service with its own authorization server, where the agent service is registered as a client of its own. Connecting is a second authorization code flow, started by a signed-in user:
// startConnect sends a signed-in user to a provider to grant the agent
// access to their account there, asking for the scopes the tools need
// and offline_access, for a refresh token: the agent works when the
// user isn't there to sign in again.
func (s *Service) startConnect(w http.ResponseWriter, r *http.Request, ss *session) {
name, prov, ok := s.provider(r)
if !ok {
http.NotFound(w, r)
return
}
p := s.remember(w, &pending{state: rand.Text(),
verifier: oauth2.GenerateVerifier(), provider: name, user: ss.user})
u := prov.oauth(s.callbackURL(name)).AuthCodeURL(p.state,
oauth2.S256ChallengeOption(p.verifier),
oauth2.SetAuthURLParam("resource", prov.Resource))
http.Redirect(w, r, u, http.StatusSeeOther)
}
// finishConnect redeems the provider's code and stores the credential
// under the user who started the connection, who must be the one
// signed in now.
func (s *Service) finishConnect(w http.ResponseWriter, r *http.Request, ss *session) {
name, prov, ok := s.provider(r)
if !ok {
http.NotFound(w, r)
return
}
p, err := s.recall(w, r, name, prov.Issuer, prov.SendsIss)
if err == nil && p.user != ss.user {
err = errors.New("started by another user")
}
if err != nil {
http.Error(w, "connecting failed: "+err.Error(), http.StatusBadRequest)
return
}
ctx := oidc.ClientContext(r.Context(), s.cfg.Client)
tok, err := prov.oauth(s.callbackURL(name)).Exchange(ctx,
r.URL.Query().Get("code"), oauth2.VerifierOption(p.verifier),
oauth2.SetAuthURLParam("resource", prov.Resource))
if err != nil || tok.RefreshToken == "" {
http.Error(w, "connecting failed: no refresh token", http.StatusBadGateway)
return
}
err = s.cfg.Vault.Put(ss.user, name, Token{Access: tok.AccessToken,
Refresh: tok.RefreshToken, Expiry: s.expiry(tok)})
if err != nil {
http.Error(w, "connecting failed", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "connected %s\n", name)
}
It asks for the scopes the tools need and offline_access, which is what gets a refresh token: the agent works for the user when they aren’t there to sign in again.
It names the API with resource (RFC 8707), so the access token is issued for the calendar API and no other.
The callback checks the answer exactly as the sign-in’s does, against the calendar’s issuer this time, and checks that the user signed in now is the one who started connecting.
Store each credential for one user
// A Vault keeps users' credentials for the providers they connected,
// encrypted with AES-256-GCM. Each row is sealed with its user and
// provider as additional data, so a row copied under another user's
// key, by a bug or by someone with write access to the table, fails to
// open instead of handing one user's account to another.
type Vault struct {
aead cipher.AEAD
mu sync.Mutex
rows map[string][]byte // stands in for a table: row key to nonce and ciphertext
}
// NewVault returns a vault that encrypts with key, 32 bytes. In
// production the key comes from a key management service, never from
// the database that holds the rows.
func NewVault(key []byte) (*Vault, error) {
block, err := aes.NewCipher(key)
if err != nil || len(key) != 32 {
return nil, errors.New("vault: the key must be 32 bytes")
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("vault: %w", err)
}
return &Vault{aead: aead, rows: map[string][]byte{}}, nil
}
// Put stores t as user's credential at provider, replacing any before.
func (v *Vault) Put(user, provider string, t Token) error {
plain, err := json.Marshal(t)
if err != nil {
return fmt.Errorf("vault: %w", err)
}
nonce := make([]byte, v.aead.NonceSize())
rand.Read(nonce) // never returns an error
ad := rowKey(user, provider)
sealed := v.aead.Seal(nonce, nonce, plain, ad)
v.mu.Lock()
defer v.mu.Unlock()
v.rows[string(ad)] = sealed
return nil
}
// Get returns user's credential at provider, or ErrNotConnected.
func (v *Vault) Get(user, provider string) (Token, error) {
var t Token
ad := rowKey(user, provider)
v.mu.Lock()
sealed, ok := v.rows[string(ad)]
v.mu.Unlock()
n := v.aead.NonceSize()
if !ok || len(sealed) < n {
return t, ErrNotConnected
}
plain, err := v.aead.Open(nil, sealed[:n], sealed[n:], ad)
if err != nil {
return t, fmt.Errorf("vault: %s's credential at %s doesn't open: %w",
user, provider, err)
}
if err := json.Unmarshal(plain, &t); err != nil {
return t, fmt.Errorf("vault: %w", err)
}
return t, nil
}
- Each row is sealed with AES-256-GCM, with its user and provider as additional data. The ciphertext opens only under the same user and provider, so a row copied to bob’s key, by a bug in a query or by someone with write access to the table, fails to open instead of giving bob alice’s calendar.
- Opening checks the same binding, and any change to the row fails it.
The key comes from a key management service, never from the database the rows live in, so a copy of the table alone is ciphertext. In production the rows also carry a key ID, so the key can be rotated without rewriting every row at once.
// TestVault: a row opens only as the user and provider it was stored
// for, unchanged, with the key it was sealed with.
func TestVault(t *testing.T) {
key := bytes.Repeat([]byte{1}, 32)
v, err := NewVault(key)
if err != nil {
t.Fatal(err)
}
if err := v.Put("alice", "calendar", Token{Access: "a", Refresh: "r"}); err != nil {
t.Fatal(err)
}
if got, err := v.Get("alice", "calendar"); err != nil || got.Refresh != "r" {
t.Fatalf("Get = %+v, %v", got, err)
}
alices := v.rows[string(rowKey("alice", "calendar"))]
other, _ := NewVault(bytes.Repeat([]byte{2}, 32))
for _, c := range []struct {
name string
v *Vault
user string
setup func()
}{
{"copied to bob's row", v, "bob", func() {
v.rows[string(rowKey("bob", "calendar"))] = alices
}},
{"one byte changed", v, "alice", func() {
bad := bytes.Clone(alices)
bad[len(bad)-1] ^= 1
v.rows[string(rowKey("alice", "calendar"))] = bad
}},
{"opened with another key", other, "alice", func() {
other.rows[string(rowKey("alice", "calendar"))] = alices
}},
} {
c.setup()
if _, err := c.v.Get(c.user, "calendar"); err == nil ||
!strings.Contains(err.Error(), "doesn't open") {
t.Errorf("%s: Get = %v, want it refused", c.name, err)
}
}
}
Refresh once
The calendar’s authorization server rotates refresh tokens: each works once, and the answer carries the next. Presenting a used one means two parties hold copies, the client and a thief, and the server can’t tell which is which, so it revokes the whole family, as RFC 9700 describes in section 4.14.2:
// TestRefreshRotation: each refresh token works once, and using one a
// second time revokes every token descended from the same grant, the
// one the rightful client holds now included.
func TestRefreshRotation(t *testing.T) {
srv := oidcSetup(t)
_, body := redeem(t, srv, "s3cret",
codeFor(t, srv, "issues:read offline_access", resource, ""), resource)
first, _ := body["refresh_token"].(string)
refresh := func(rt string) (int, map[string]any) {
return tokenReq(t, srv, "/token", "s3cret", url.Values{
"grant_type": {"refresh_token"}, "refresh_token": {rt}})
}
status, body := refresh(first)
second, _ := body["refresh_token"].(string)
if status != http.StatusOK || second == "" || second == first {
t.Fatalf("first refresh: %d, rotated %v", status, second != first)
}
if status, body := refresh(first); status != http.StatusBadRequest ||
body["error"] != "invalid_grant" {
t.Errorf("the used token again: %d %v", status, body)
}
if status, _ := refresh(second); status != http.StatusBadRequest {
t.Errorf("the newest token after the reuse: %d, want it revoked too", status)
}
}
Rotation is good against theft and hard on concurrency. An agent runs tools in parallel, and when the access token expires, every tool call that needs it finds it expired at once. If each refreshes, all but the first present a used refresh token, and the provider revokes the connection: the service locks itself out with no attacker involved.
// TokenFor returns an access token for user's account at provider,
// refreshing it when it has run out. Calls for one user and provider
// share a refresh: with rotation, every refresh token works once, and
// two refreshes sent with the same one look to the provider like a
// stolen copy in use, so it revokes both.
func (s *Service) TokenFor(ctx context.Context, user, provider string) (string, error) {
tok, err, _ := s.flight.Do(string(rowKey(user, provider)), func() (any, error) {
return s.current(context.WithoutCancel(ctx), user, provider)
})
if err != nil {
return "", err //nolint:wrapcheck // current's errors name the provider
}
return tok.(string), nil
}
// The margin before expiry at which a token counts as run out, so a
// request doesn't set off with a token that expires on the way.
const margin = 30 * time.Second
func (s *Service) current(ctx context.Context, user, name string) (string, error) {
t, err := s.cfg.Vault.Get(user, name)
if err != nil {
return "", fmt.Errorf("%s: %w", name, err)
}
if s.cfg.Now().Before(t.Expiry.Add(-margin)) {
return t.Access, nil
}
ctx, cancel := context.WithTimeout(oidc.ClientContext(ctx, s.cfg.Client),
10*time.Second)
defer cancel()
prov := s.cfg.Providers[name]
nt, err := prov.oauth("").TokenSource(ctx,
&oauth2.Token{RefreshToken: t.Refresh}).Token()
var re *oauth2.RetrieveError
if errors.As(err, &re) && re.ErrorCode == "invalid_grant" {
s.cfg.Vault.Delete(user, name)
return "", fmt.Errorf("%s: %w: the connection was revoked", name, ErrNotConnected)
}
if err != nil {
return "", fmt.Errorf("%s: refresh: %w", name, err)
}
next := Token{Access: nt.AccessToken, Refresh: nt.RefreshToken, Expiry: s.expiry(nt)}
if next.Refresh == "" {
next.Refresh = t.Refresh // the provider doesn't rotate
}
if err := s.cfg.Vault.Put(user, name, next); err != nil {
return "", err
}
return next.Access, nil
}
- Calls for one user and provider share a refresh, through
singleflight, and the refresh runs on a context that ignores the caller’s cancellation. Once the provider has rotated the token, the new one must be stored, or the service holds only a used token and the next refresh revokes the connection. A caller giving up doesn’t get to stop that halfway. - The refresh token is redeemed with the client secret. The service computes the new expiry with its own clock from
expires_in. - A refused refresh token means the connection is gone, revoked by the user at the provider or by reuse detection. The service forgets it, and the tool tells the model the user must connect again, which is how step 7 ends.
- The new token is stored before it is used.
singleflight coordinates calls in one process.
Several replicas of the service need the same guarantee across processes, a lock on the user and provider’s row, for example, held while refreshing.
Some providers allow a grace period in which the previous refresh token still works, Okta’s for one, which softens the race; it is not a substitute for not having it.
// TestOneRefreshAtATime: many tool calls finding the token expired at
// once share one refresh. Each sending its own would reuse the refresh
// token, and the provider would revoke the connection.
func TestOneRefreshAtATime(t *testing.T) {
w := newTestWorld(t)
b := w.browser("alice@example.com")
w.signIn(t, b)
w.connect(t, b)
w.advance(10 * time.Minute)
var wg sync.WaitGroup
toks := make([]string, 20)
errs := make([]error, 20)
for i := range toks {
wg.Go(func() {
toks[i], errs[i] = w.svc.TokenFor(t.Context(), "alice@example.com", "calendar")
})
}
wg.Wait()
for i := range toks {
if errs[i] != nil || toks[i] != toks[0] {
t.Fatalf("call %d: %v, or a different token", i, errs[i])
}
}
if n := w.refreshes.Load(); n != 1 {
t.Errorf("%d refreshes, want 1", n)
}
if reply := w.ask(t, b); !strings.Contains(reply, "Design review") {
t.Errorf("after the refresh: %q", reply)
}
}
Step 7 shows the other reason the service is a confidential client: a refresh token alone is useless. RFC 9700 binds a confidential client’s refresh tokens to its client authentication, so a token copied out of a backup needs the client secret too, and the secret lives somewhere the backup doesn’t.
The model never sees a token
// ask runs one turn of the agent for the signed-in user. The model
// picks the tool and its arguments; the user it runs for comes from
// the session. Neither the model nor the browser ever sees a token.
func (s *Service) ask(w http.ResponseWriter, r *http.Request, ss *session) {
var req struct {
Question string `json:"question"`
}
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
if err := json.UnmarshalRead(r.Body, &req); err != nil {
http.Error(w, "a JSON question is required", http.StatusBadRequest)
return
}
name, args := s.cfg.Model(req.Question)
tool, ok := s.cfg.Tools[name]
reply := "I have no tool for that."
if ok {
out, err := tool(r.Context(), s, ss.user, args)
switch {
case errors.Is(err, ErrNotConnected):
reply = fmt.Sprintf("I can't reach that account (%v). Connect it,"+
" then ask again.", err)
case err != nil:
reply = "That didn't work: " + err.Error()
default:
reply = out
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.MarshalWrite(w, map[string]string{"reply": reply})
}
The model picks a tool and its arguments.
Who the tool runs as comes from the session, and a tool gets its credential from TokenFor, by that user’s name:
// NextMeeting is a tool that reads the user's next meeting from the
// calendar API at api, with the user's own credential for the provider
// named calendar.
func NextMeeting(api string) Tool {
return func(ctx context.Context, s *Service, user string, _ []byte) (string, error) {
tok, err := s.TokenFor(ctx, user, "calendar")
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, api+"/events", nil)
if err != nil {
return "", fmt.Errorf("next_meeting: %w", err)
}
req.Header.Set("Authorization", "Bearer "+tok)
resp, err := s.cfg.Client.Do(req)
if err != nil {
return "", fmt.Errorf("next_meeting: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("next_meeting: the calendar answered %s", resp.Status)
}
var events []struct {
Title string `json:"title"`
Start string `json:"start"`
}
b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err == nil {
err = json.Unmarshal(b, &events)
}
if err != nil {
return "", fmt.Errorf("next_meeting: %w", err)
}
if len(events) == 0 {
return "Nothing on your calendar.", nil
}
return fmt.Sprintf("Next: %q at %s.", events[0].Title, events[0].Start), nil
}
}
No token passes through the model’s context, so no prompt can get one printed, and an argument naming another user changes nothing: TestToolRunsAsSessionUser has the model ask for alice’s calendar while bob is signed in, and the answer is that bob hasn’t connected one.
Disconnecting revokes
// disconnect revokes the user's refresh token at the provider (RFC
// 7009), which also ends every token descended from it, and then
// forgets the credential. Deleting the row alone would leave a working
// refresh token in every backup of the table.
func (s *Service) disconnect(w http.ResponseWriter, r *http.Request, ss *session) {
name, prov, ok := s.provider(r)
if !ok {
http.NotFound(w, r)
return
}
t, err := s.cfg.Vault.Get(ss.user, name)
if err != nil {
http.Error(w, "not connected", http.StatusNotFound)
return
}
if err := s.revoke(r.Context(), prov, t.Refresh); err != nil {
http.Error(w, "the provider didn't confirm the revocation", http.StatusBadGateway)
return
}
s.cfg.Vault.Delete(ss.user, name)
w.WriteHeader(http.StatusNoContent)
}
Deleting the row isn’t enough: every backup of the table holds the refresh token, and to the provider it is still good. Revoking it at the provider’s revocation endpoint (RFC 7009) ends it, and the family descended from it, everywhere at once. Access tokens already issued are JWTs that the provider doesn’t track, so they run until they expire, five minutes here.
With Okta
The example’s identity provider and the calendar’s authorization server are a test double. With Okta as the identity provider, the configuration becomes Okta’s values, and a few of its defaults matter:
- The issuer. A custom authorization server’s issuer is
https://{yourOktaDomain}/oauth2/{authorizationServerId},https://{yourOktaDomain}/oauth2/defaultfor the default one, with its discovery document at/.well-known/openid-configurationunder that path. go-oidc compares the issuer in the document with the one you configured exactly. - Which authorization server. For signing in, either works. Access tokens your own APIs will validate must come from a custom authorization server: Okta’s documentation says access tokens from the org authorization server aren’t intended for validation by your own apps or resource servers.
- The client. Register the agent service as a web application, a confidential client, and turn on PKCE for it as well.
- Refresh tokens. Ask for
offline_accessand enable the refresh token grant for the app. Rotation is on by default only for single-page apps; web apps get persistent refresh tokens unless you turn rotation on, with a grace period of 0 to 60 seconds, 30 by default. Reusing a rotated token past the grace period invalidates the newest one and the access tokens issued since. - The
issparameter. Readauthorization_response_iss_parameter_supportedin the metadata; the service requiresissonly when the provider says it sends one. - The user’s key. Okta’s
subis a stable user ID; key on it with the issuer, not on the email.
The code here was tested against its own authorization servers only. Run the same tests against a test tenant before relying on it.
Why this way and not another
- Tokens in the browser. A single-page app as a public OAuth client is allowed, with a token store any injected script can read, and RFC 10017 describes the backend for frontend first, as the architecture that keeps tokens out of the browser altogether. An agent’s tokens reach the user’s other accounts, which raises the stakes.
- Using the sign-in’s access token for the calendar. It is issued for the identity provider, and the calendar isn’t. Each API gets a token issued for it.
- Stateless sessions in a signed cookie. No lookup per request, and no way to end one: signing out can’t stop a copy of the cookie, and neither can an administrator.
- Encryption without the binding. It protects against someone reading the table, and not against a row put under the wrong user, which is the mistake the binding catches.
- Refreshing wherever a token runs out. Fine without rotation, and with it, a parallel agent revokes its own connections.
- A key per user pasted into settings. No expiry, no scopes, no revocation at the provider, and the user’s whole account.
Mistakes to avoid
- Skipping the nonce check. go-oidc’s verifier doesn’t do it.
- Keying users by email. Use the issuer and
sub. - Letting a refresh be cancelled halfway. Finish it and store the result.
- Refreshing in parallel with rotating tokens. Share one refresh per user and provider.
- Deleting a credential without revoking it.
- Sending an ID token to an API.
- Ending a session only in the browser. Delete it on the server.
Try it
From the code/mcpauth directory of a clone of the companion repository:
$ go run ./cmd/agentweb
$ go test -race ./...
- In
agentweb/connect.go, haveTokenForcalls.currentdirectly instead of throughs.flight.Do, and rungo test ./agentweb -run TestOneRefreshAtATime. The twenty tool calls refresh twenty times, and the provider revokes the connection. - Remove
context.WithoutCancelfromTokenForand rungo test ./agentweb -run TestRefreshSurvivesCancel. A caller that has given up now stops the refresh. - In
agentweb/service.go, delete the nonce comparison and rungo test ./agentweb -run TestSignInRefuses. The sign-in with the changed nonce goes through. - In
agentweb/vault.go, passnilfor the additional data to bothSealandOpen, and rungo test ./agentweb -run TestVault. Alice’s row, copied under bob, opens as bob’s.
Undo your edits with git restore . in the code directory.
type Config struct {
BaseURL string // where browsers reach the service: https://agent.example.com
// The identity provider users sign in with, and the service's
// client there: a confidential client, since the secret never
// leaves the server.
Issuer, ClientID, ClientSecret string
Providers map[string]Provider // services users can connect, by name
Vault *Vault
// ...
}
Config describes an agent service.
mcpauth/agentweb/service.go:29
Config describes an agent service. type Config struct { BaseURL string // where browsers reach the service: https://agent.example.com // The identity provider users sign in with, and the service's // client there: a confidential client, since the secret never // leaves the server. Issuer, ClientID, ClientSecret string Providers map[string]Provider // services users can connect, by name Vault *Vault // ... }. In mcpauth/agentweb/service.go, line 29.
field BaseURL string
where browsers reach the service: https://agent.example.com
mcpauth/agentweb/service.go:30
where browsers reach the service: https://agent.example.com field BaseURL string. In mcpauth/agentweb/service.go, line 30.
type string string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text.
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. type string string. Documented at pkg.go.dev, builtin.string.
field Issuer string
The identity provider users sign in with, and the service's client there: a confidential client, since the secret never leaves the server.
mcpauth/agentweb/service.go:35
The identity provider users sign in with, and the service's client there: a confidential client, since the secret never leaves the server. field Issuer string. In mcpauth/agentweb/service.go, line 35.
field ClientID string
The identity provider users sign in with, and the service's client there: a confidential client, since the secret never leaves the server.
mcpauth/agentweb/service.go:35
The identity provider users sign in with, and the service's client there: a confidential client, since the secret never leaves the server. field ClientID string. In mcpauth/agentweb/service.go, line 35.
field ClientSecret string
The identity provider users sign in with, and the service's client there: a confidential client, since the secret never leaves the server.
mcpauth/agentweb/service.go:35
The identity provider users sign in with, and the service's client there: a confidential client, since the secret never leaves the server. field ClientSecret string. In mcpauth/agentweb/service.go, line 35.
field Providers map[string]Provider
services users can connect, by name
mcpauth/agentweb/service.go:37
services users can connect, by name field Providers map[string]Provider. In mcpauth/agentweb/service.go, line 37.
type Provider struct {
Issuer string // its authorization server
AuthURL, TokenURL, RevokeURL string
ClientID, ClientSecret string
Resource string // its API, as a resource indicator (RFC 8707)
Scopes []string // what the tools need, and offline_access
// SendsIss says the authorization server puts iss in its answers
// (RFC 9207), as its metadata's
// authorization_response_iss_parameter_supported says: answers
// ...
}
A Provider is a service whose API the agent's tools call, once a user connects an account there.
mcpauth/agentweb/service.go:48
A Provider is a service whose API the agent's tools call, once a user connects an account there. type Provider struct { Issuer string // its authorization server AuthURL, TokenURL, RevokeURL string ClientID, ClientSecret string Resource string // its API, as a resource indicator (RFC 8707) Scopes []string // what the tools need, and offline_access // SendsIss says the authorization server puts iss in its answers // (RFC 9207), as its metadata's // authorization_response_iss_parameter_supported says: answers // ... }. In mcpauth/agentweb/service.go, line 48.
field Vault *Vault
mcpauth/agentweb/service.go:38
field Vault *Vault. In mcpauth/agentweb/service.go, line 38.
type Vault struct {
aead cipher.AEAD
mu sync.Mutex
rows map[string][]byte // stands in for a table: row key to nonce and ciphertext
}
A Vault keeps users' credentials for the providers they connected, encrypted with AES-256-GCM.
A Vault keeps users' credentials for the providers they connected, encrypted with AES-256-GCM. type Vault struct { aead cipher.AEAD mu sync.Mutex rows map[string][]byte // stands in for a table: row key to nonce and ciphertext }. In mcpauth/agentweb/vault.go, line 34.
field Tools map[string]Tool
the agent's tools, by name
mcpauth/agentweb/service.go:39
the agent's tools, by name field Tools map[string]Tool. In mcpauth/agentweb/service.go, line 39.
type Tool func(ctx context.Context, s *Service, user string, args []byte) (string, error)
A Tool is one of the agent's tools.
mcpauth/agentweb/service.go:71
A Tool is one of the agent's tools. type Tool func(ctx context.Context, s *Service, user string, args []byte) (string, error). In mcpauth/agentweb/service.go, line 71.
field Model Model
mcpauth/agentweb/service.go:40
field Model Model. In mcpauth/agentweb/service.go, line 40.
type Model func(question string) (tool string, args []byte)
A Model stands in for the agent's model: given what the user asked, it picks a tool and its arguments.
mcpauth/agentweb/service.go:66
A Model stands in for the agent's model: given what the user asked, it picks a tool and its arguments. type Model func(question string) (tool string, args []byte). In mcpauth/agentweb/service.go, line 66.
field Client *http.Client
for every request the service makes
mcpauth/agentweb/service.go:42
for every request the service makes field Client *http.Client. In mcpauth/agentweb/service.go, line 42.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
type Client struct {
// Transport specifies the mechanism by which individual
// HTTP requests are made.
// If nil, DefaultTransport is used.
Transport RoundTripper
// CheckRedirect specifies the policy for handling redirects.
// If CheckRedirect is not nil, the client calls it before
// following an HTTP redirect. The arguments req and via are
// the upcoming request and the requests made already, oldest
// ...
}
A Client is an HTTP client.
A Client is an HTTP client. type Client struct { // Transport specifies the mechanism by which individual // HTTP requests are made. // If nil, DefaultTransport is used. Transport RoundTripper // CheckRedirect specifies the policy for handling redirects. // If CheckRedirect is not nil, the client calls it before // following an HTTP redirect. The arguments req and via are // the upcoming request and the requests made already, oldest // ... }. Documented at pkg.go.dev, net/http.Client.
field Now func() time.Time
mcpauth/agentweb/service.go:43
field Now func() time.Time. In mcpauth/agentweb/service.go, line 43.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
type Time struct {
// wall and ext encode the wall time seconds, wall time nanoseconds,
// and optional monotonic clock reading in nanoseconds.
//
// From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
// a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
// The nanoseconds field is in the range [0, 999999999].
// If the hasMonotonic bit is 0, then the 33-bit field must be zero
// and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
// If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
// ...
}
A Time represents an instant in time with nanosecond precision.
A Time represents an instant in time with nanosecond precision. type Time struct { // wall and ext encode the wall time seconds, wall time nanoseconds, // and optional monotonic clock reading in nanoseconds. // // From high to low bit position, wall encodes a 1-bit flag (hasMonotonic), // a 33-bit seconds field, and a 30-bit wall time nanoseconds field. // The nanoseconds field is in the range [0, 999999999]. // If the hasMonotonic bit is 0, then the 33-bit field must be zero // and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext. // If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit // ... }. Documented at pkg.go.dev, time.Time.
field Issuer string
its authorization server
mcpauth/agentweb/service.go:49
its authorization server field Issuer string. In mcpauth/agentweb/service.go, line 49.
field AuthURL string
mcpauth/agentweb/service.go:50
field AuthURL string. In mcpauth/agentweb/service.go, line 50.
field TokenURL string
mcpauth/agentweb/service.go:50
field TokenURL string. In mcpauth/agentweb/service.go, line 50.
field RevokeURL string
mcpauth/agentweb/service.go:50
field RevokeURL string. In mcpauth/agentweb/service.go, line 50.
field ClientID string
mcpauth/agentweb/service.go:51
field ClientID string. In mcpauth/agentweb/service.go, line 51.
field ClientSecret string
mcpauth/agentweb/service.go:51
field ClientSecret string. In mcpauth/agentweb/service.go, line 51.
field Resource string
its API, as a resource indicator (RFC 8707)
mcpauth/agentweb/service.go:52
its API, as a resource indicator (RFC 8707) field Resource string. In mcpauth/agentweb/service.go, line 52.
field Scopes []string
what the tools need, and offline_access
mcpauth/agentweb/service.go:53
what the tools need, and offline_access field Scopes []string. In mcpauth/agentweb/service.go, line 53.
field SendsIss bool
SendsIss says the authorization server puts iss in its answers (RFC 9207), as its metadata's authorization_response_iss_parameter_supported says: answers without it are then refused.
mcpauth/agentweb/service.go:59
SendsIss says the authorization server puts iss in its answers (RFC 9207), as its metadata's authorization_response_iss_parameter_supported says: answers without it are then refused. field SendsIss bool. In mcpauth/agentweb/service.go, line 59.
type bool bool
bool is the set of boolean values, true and false.
bool is the set of boolean values, true and false. type bool bool. Documented at pkg.go.dev, builtin.bool.
var s *Service
mcpauth/agentweb/service.go:155
var s *Service. In mcpauth/agentweb/service.go, line 155.
type Service struct {
cfg Config
ids *oidc.IDTokenVerifier
idpIss bool // the identity provider sends iss in its answers
signIn oauth2.Config
mux *http.ServeMux
mu sync.Mutex
sessions map[string]*session
pending map[string]*pending
flight singleflight.Group // refreshes in progress, by user and provider
}
Service is an agent service; it is an http.Handler.
mcpauth/agentweb/service.go:74
Service is an agent service; it is an http.Handler. type Service struct { cfg Config ids *oidc.IDTokenVerifier idpIss bool // the identity provider sends iss in its answers signIn oauth2.Config mux *http.ServeMux mu sync.Mutex sessions map[string]*session pending map[string]*pending flight singleflight.Group // refreshes in progress, by user and provider }. In mcpauth/agentweb/service.go, line 74.
func (s *Service) startLogin(w http.ResponseWriter, r *http.Request)
startLogin sends the browser to the identity provider.
mcpauth/agentweb/service.go:155
startLogin sends the browser to the identity provider. func (s *Service) startLogin(w http.ResponseWriter, r *http.Request). In mcpauth/agentweb/service.go, line 155.
var w http.ResponseWriter
mcpauth/agentweb/service.go:155
var w http.ResponseWriter. In mcpauth/agentweb/service.go, line 155.
type ResponseWriter interface {
// Header returns the header map that will be sent by
// [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
// [Handler] implementations can set HTTP trailers.
//
// Changing the header map after a call to [ResponseWriter.WriteHeader] (or
// [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
// 1xx class or the modified headers are trailers.
//
// There are two ways to set Trailers. The preferred way is to
// ...
}
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response. type ResponseWriter interface { // Header returns the header map that will be sent by // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which // [Handler] implementations can set HTTP trailers. // // Changing the header map after a call to [ResponseWriter.WriteHeader] (or // [ResponseWriter.Write]) has no effect unless the HTTP status code was of the // 1xx class or the modified headers are trailers. // // There are two ways to set Trailers. The preferred way is to // ... }. Documented at pkg.go.dev, net/http.ResponseWriter.
var r *http.Request
mcpauth/agentweb/service.go:155
var r *http.Request. In mcpauth/agentweb/service.go, line 155.
type Request struct {
// Method specifies the HTTP method (GET, POST, PUT, etc.).
// For client requests, an empty string means GET.
Method string
// URL specifies either the URI being requested (for server
// requests) or the URL to access (for client requests).
//
// For server requests, the URL is parsed from the URI
// supplied on the Request-Line as stored in RequestURI. For
// ...
}
A Request represents an HTTP request received by a server or to be sent by a client.
A Request represents an HTTP request received by a server or to be sent by a client. type Request struct { // Method specifies the HTTP method (GET, POST, PUT, etc.). // For client requests, an empty string means GET. Method string // URL specifies either the URI being requested (for server // requests) or the URL to access (for client requests). // // For server requests, the URL is parsed from the URI // supplied on the Request-Line as stored in RequestURI. For // ... }. Documented at pkg.go.dev, net/http.Request.
var p *pending
mcpauth/agentweb/service.go:156
var p *pending. In mcpauth/agentweb/service.go, line 156.
func (s *Service) remember(w http.ResponseWriter, p *pending) *pending
remember stores p and gives this browser a cookie naming it.
mcpauth/agentweb/service.go:221
remember stores p and gives this browser a cookie naming it. func (s *Service) remember(w http.ResponseWriter, p *pending) *pending. In mcpauth/agentweb/service.go, line 221.
type pending struct {
state, nonce, verifier string
provider string // "" for signing in
user string // who is connecting, for a connection
expires time.Time
}
A pending is a sign-in or a connection in progress, between the redirect to an authorization server and the redirect back.
mcpauth/agentweb/service.go:142
A pending is a sign-in or a connection in progress, between the redirect to an authorization server and the redirect back. type pending struct { state, nonce, verifier string provider string // "" for signing in user string // who is connecting, for a connection expires time.Time }. In mcpauth/agentweb/service.go, line 142.
field state string
mcpauth/agentweb/service.go:143
field state string. In mcpauth/agentweb/service.go, line 143.
package rand ("crypto/rand")
Package rand implements a cryptographically secure random number generator.
Package rand implements a cryptographically secure random number generator. package rand ("crypto/rand"). Documented at pkg.go.dev, crypto/rand.
func Text() string
Text returns a cryptographically random string using the standard RFC 4648 base32 alphabet for use when a secret string, token, password, or other text is needed.
Text returns a cryptographically random string using the standard RFC 4648 base32 alphabet for use when a secret string, token, password, or other text is needed. func Text() string. Documented at pkg.go.dev, crypto/rand.Text.
field nonce string
mcpauth/agentweb/service.go:143
field nonce string. In mcpauth/agentweb/service.go, line 143.
field verifier string
mcpauth/agentweb/service.go:143
field verifier string. In mcpauth/agentweb/service.go, line 143.
package oauth2 ("golang.org/x/oauth2")
package oauth2 ("golang.org/x/oauth2").
func GenerateVerifier() string
GenerateVerifier generates a PKCE code verifier with 32 octets of randomness.
golang.org/x/oauth2.GenerateVerifier
GenerateVerifier generates a PKCE code verifier with 32 octets of randomness. func GenerateVerifier() string. Documented at pkg.go.dev, golang.org/x/oauth2.GenerateVerifier.
field signIn oauth2.Config
mcpauth/agentweb/service.go:78
field signIn oauth2.Config. In mcpauth/agentweb/service.go, line 78.
func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string
AuthCodeURL returns a URL to OAuth 2.0 provider's consent page that asks for permissions for the required scopes explicitly.
golang.org/x/oauth2.Config.AuthCodeURL
AuthCodeURL returns a URL to OAuth 2.0 provider's consent page that asks for permissions for the required scopes explicitly. func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string. Documented at pkg.go.dev, golang.org/x/oauth2.Config.AuthCodeURL.
package oidc ("github.com/coreos/go-oidc/v3/oidc")
package oidc ("github.com/coreos/go-oidc/v3/oidc").
func Nonce(nonce string) oauth2.AuthCodeOption
Nonce returns an auth code option which requires the ID Token created by the OpenID Connect provider to contain the specified nonce.
github.com/coreos/go-oidc/v3/oidc.Nonce
Nonce returns an auth code option which requires the ID Token created by the OpenID Connect provider to contain the specified nonce. func Nonce(nonce string) oauth2.AuthCodeOption. Documented at pkg.go.dev, github.com/coreos/go-oidc/v3/oidc.Nonce.
func S256ChallengeOption(verifier string) AuthCodeOption
S256ChallengeOption derives a PKCE code challenge from the verifier with method S256.
golang.org/x/oauth2.S256ChallengeOption
S256ChallengeOption derives a PKCE code challenge from the verifier with method S256. func S256ChallengeOption(verifier string) AuthCodeOption. Documented at pkg.go.dev, golang.org/x/oauth2.S256ChallengeOption.
func Redirect(w ResponseWriter, r *Request, url string, code int)
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
Redirect replies to the request with a redirect to url, which may be a path relative to the request path. func Redirect(w ResponseWriter, r *Request, url string, code int). Documented at pkg.go.dev, net/http.Redirect.
const StatusFound = 302
RFC 9110, 15.4.3
RFC 9110, 15.4.3 const StatusFound = 302. Documented at pkg.go.dev, net/http.StatusFound.
var s *Service
mcpauth/agentweb/service.go:221
var s *Service. In mcpauth/agentweb/service.go, line 221.
var w http.ResponseWriter
mcpauth/agentweb/service.go:221
var w http.ResponseWriter. In mcpauth/agentweb/service.go, line 221.
var p *pending
mcpauth/agentweb/service.go:221
var p *pending. In mcpauth/agentweb/service.go, line 221.
var id string
mcpauth/agentweb/service.go:222
var id string. In mcpauth/agentweb/service.go, line 222.
field expires time.Time
mcpauth/agentweb/service.go:146
field expires time.Time. In mcpauth/agentweb/service.go, line 146.
field cfg Config
mcpauth/agentweb/service.go:75
field cfg Config. In mcpauth/agentweb/service.go, line 75.
func (t Time) Add(d Duration) Time
Add returns the time t+d.
Add returns the time t+d. func (t Time) Add(d Duration) Time. Documented at pkg.go.dev, time.Time.Add.
const Minute = 60 * Second
const Minute = 60 * Second. Documented at pkg.go.dev, time.Minute.
field mu sync.Mutex
mcpauth/agentweb/service.go:81
field mu sync.Mutex. In mcpauth/agentweb/service.go, line 81.
func (m *Mutex) Lock()
Lock locks m.
Lock locks m. func (m *Mutex) Lock(). Documented at pkg.go.dev, sync.Mutex.Lock.
field pending map[string]*pending
mcpauth/agentweb/service.go:83
field pending map[string]*pending. In mcpauth/agentweb/service.go, line 83.
func (m *Mutex) Unlock()
Unlock unlocks m.
Unlock unlocks m. func (m *Mutex) Unlock(). Documented at pkg.go.dev, sync.Mutex.Unlock.
func SetCookie(w ResponseWriter, cookie *Cookie)
SetCookie adds a Set-Cookie header to the provided [ResponseWriter]'s headers.
SetCookie adds a Set-Cookie header to the provided [ResponseWriter]'s headers. func SetCookie(w ResponseWriter, cookie *Cookie). Documented at pkg.go.dev, net/http.SetCookie.
type Cookie struct {
Name string
Value string
Quoted bool // indicates whether the Value was originally quoted
Path string // optional
Domain string // optional
Expires time.Time // optional
RawExpires string // for reading cookies only
// ...
}
A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request.
A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an HTTP response or the Cookie header of an HTTP request. type Cookie struct { Name string Value string Quoted bool // indicates whether the Value was originally quoted Path string // optional Domain string // optional Expires time.Time // optional RawExpires string // for reading cookies only // ... }. Documented at pkg.go.dev, net/http.Cookie.
field Name string
field Name string. Documented at pkg.go.dev, net/http.Cookie.Name.
const loginCookie = "__Host-Http-login"
mcpauth/agentweb/service.go:89
const loginCookie = "__Host-Http-login". In mcpauth/agentweb/service.go, line 89.
field Value string
field Value string. Documented at pkg.go.dev, net/http.Cookie.Value.
field Path string
optional
optional field Path string. Documented at pkg.go.dev, net/http.Cookie.Path.
field MaxAge int
MaxAge=0 means no 'Max-Age' attribute specified.
MaxAge=0 means no 'Max-Age' attribute specified. field MaxAge int. Documented at pkg.go.dev, net/http.Cookie.MaxAge.
field Secure bool
field Secure bool. Documented at pkg.go.dev, net/http.Cookie.Secure.
const true = 0 == 0
Untyped bool.
Untyped bool. const true = 0 == 0. Documented at pkg.go.dev, builtin.true.
field HttpOnly bool
field HttpOnly bool. Documented at pkg.go.dev, net/http.Cookie.HttpOnly.
field SameSite SameSite
field SameSite SameSite. Documented at pkg.go.dev, net/http.Cookie.SameSite.
const SameSiteLaxMode
const SameSiteLaxMode. Documented at pkg.go.dev, net/http.SameSiteLaxMode.
var s *Service
mcpauth/agentweb/service.go:237
var s *Service. In mcpauth/agentweb/service.go, line 237.
func (s *Service) recall(w http.ResponseWriter, r *http.Request,
provider, issuer string, sendsIss bool) (*pending, error)
recall takes the flow this browser started, once, and checks the answer belongs to it: the same state, from the authorization server it was sent to, and not an error.
mcpauth/agentweb/service.go:237
recall takes the flow this browser started, once, and checks the answer belongs to it: the same state, from the authorization server it was sent to, and not an error. func (s *Service) recall(w http.ResponseWriter, r *http.Request, provider, issuer string, sendsIss bool) (*pending, error). In mcpauth/agentweb/service.go, line 237.
var w http.ResponseWriter
mcpauth/agentweb/service.go:237
var w http.ResponseWriter. In mcpauth/agentweb/service.go, line 237.
var r *http.Request
mcpauth/agentweb/service.go:237
var r *http.Request. In mcpauth/agentweb/service.go, line 237.
var provider string
mcpauth/agentweb/service.go:238
var provider string. In mcpauth/agentweb/service.go, line 238.
var issuer string
mcpauth/agentweb/service.go:238
var issuer string. In mcpauth/agentweb/service.go, line 238.
var sendsIss bool
mcpauth/agentweb/service.go:238
var sendsIss bool. In mcpauth/agentweb/service.go, line 238.
type error interface {
Error() string
}
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. type error interface { Error() string }. Documented at pkg.go.dev, builtin.error.
var c *http.Cookie
mcpauth/agentweb/service.go:239
var c *http.Cookie. In mcpauth/agentweb/service.go, line 239.
var err error
mcpauth/agentweb/service.go:239
var err error. In mcpauth/agentweb/service.go, line 239.
func (r *Request) Cookie(name string) (*Cookie, error)
Cookie returns the named cookie provided in the request or [ErrNoCookie] if not found.
Cookie returns the named cookie provided in the request or [ErrNoCookie] if not found. func (r *Request) Cookie(name string) (*Cookie, error). Documented at pkg.go.dev, net/http.Request.Cookie.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
func New(text string) error
New returns an error that formats as the given text.
New returns an error that formats as the given text. func New(text string) error. Documented at pkg.go.dev, errors.New.
var p *pending
mcpauth/agentweb/service.go:244
var p *pending. In mcpauth/agentweb/service.go, line 244.
func delete(m map[Type]Type1, key Type)
The delete built-in function deletes the element with the specified key (m[key]) from the map.
The delete built-in function deletes the element with the specified key (m[key]) from the map. func delete(m map[Type]Type1, key Type). Documented at pkg.go.dev, builtin.delete.
var q url.Values
mcpauth/agentweb/service.go:249
var q url.Values. In mcpauth/agentweb/service.go, line 249.
field URL *url.URL
URL specifies either the URI being requested (for server requests) or the URL to access (for client requests).
URL specifies either the URI being requested (for server requests) or the URL to access (for client requests). field URL *url.URL. Documented at pkg.go.dev, net/http.Request.URL.
func (u *URL) Query() Values
Query parses RawQuery and returns the corresponding values.
Query parses RawQuery and returns the corresponding values. func (u *URL) Query() Values. Documented at pkg.go.dev, net/url.URL.Query.
field provider string
"" for signing in
mcpauth/agentweb/service.go:144
"" for signing in field provider string. In mcpauth/agentweb/service.go, line 144.
func (t Time) After(u Time) bool
After reports whether the time instant t is after u.
After reports whether the time instant t is after u. func (t Time) After(u Time) bool. Documented at pkg.go.dev, time.Time.After.
package subtle ("crypto/subtle")
Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.
Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly. package subtle ("crypto/subtle"). Documented at pkg.go.dev, crypto/subtle.
func ConstantTimeCompare(x, y []byte) int
ConstantTimeCompare returns 1 if the two slices, x and y, have equal contents and 0 otherwise.
crypto/subtle.ConstantTimeCompare
ConstantTimeCompare returns 1 if the two slices, x and y, have equal contents and 0 otherwise. func ConstantTimeCompare(x, y []byte) int. Documented at pkg.go.dev, crypto/subtle.ConstantTimeCompare.
type byte = uint8
byte is an alias for uint8 and is equivalent to uint8 in all ways.
byte is an alias for uint8 and is equivalent to uint8 in all ways. type byte = uint8. Documented at pkg.go.dev, builtin.byte.
func (v Values) Get(key string) string
Get gets the first value associated with the given key.
Get gets the first value associated with the given key. func (v Values) Get(key string) string. Documented at pkg.go.dev, net/url.Values.Get.
func (v Values) Has(key string) bool
Has checks whether a given key is set.
Has checks whether a given key is set. func (v Values) Has(key string) bool. Documented at pkg.go.dev, net/url.Values.Has.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Errorf(format string, a ...any) (err error)
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
Errorf formats according to a format specifier and returns the string as a value that satisfies error. func Errorf(format string, a ...any) (err error). Documented at pkg.go.dev, fmt.Errorf.
var s *Service
mcpauth/agentweb/service.go:170
var s *Service. In mcpauth/agentweb/service.go, line 170.
func (s *Service) finishLogin(w http.ResponseWriter, r *http.Request)
finishLogin takes the identity provider's answer: it checks the answer belongs to the sign-in this browser started, redeems the code, checks the ID token, and starts a session.
mcpauth/agentweb/service.go:170
finishLogin takes the identity provider's answer: it checks the answer belongs to the sign-in this browser started, redeems the code, checks the ID token, and starts a session. func (s *Service) finishLogin(w http.ResponseWriter, r *http.Request). In mcpauth/agentweb/service.go, line 170.
var w http.ResponseWriter
mcpauth/agentweb/service.go:170
var w http.ResponseWriter. In mcpauth/agentweb/service.go, line 170.
var r *http.Request
mcpauth/agentweb/service.go:170
var r *http.Request. In mcpauth/agentweb/service.go, line 170.
var p *pending
mcpauth/agentweb/service.go:171
var p *pending. In mcpauth/agentweb/service.go, line 171.
var err error
mcpauth/agentweb/service.go:171
var err error. In mcpauth/agentweb/service.go, line 171.
field idpIss bool
the identity provider sends iss in its answers
mcpauth/agentweb/service.go:77
the identity provider sends iss in its answers field idpIss bool. In mcpauth/agentweb/service.go, line 77.
func Error(w ResponseWriter, error string, code int)
Error replies to the request with the specified error message and HTTP code.
Error replies to the request with the specified error message and HTTP code. func Error(w ResponseWriter, error string, code int). Documented at pkg.go.dev, net/http.Error.
func (error).Error() string
func (error).Error() string.
const StatusBadRequest = 400
RFC 9110, 15.5.1
RFC 9110, 15.5.1 const StatusBadRequest = 400. Documented at pkg.go.dev, net/http.StatusBadRequest.
var ctx context.Context
mcpauth/agentweb/service.go:176
var ctx context.Context. In mcpauth/agentweb/service.go, line 176.
func ClientContext(ctx context.Context, client *http.Client) context.Context
ClientContext returns a new Context that carries the provided HTTP client.
github.com/coreos/go-oidc/v3/oidc.ClientContext
ClientContext returns a new Context that carries the provided HTTP client. func ClientContext(ctx context.Context, client *http.Client) context.Context. Documented at pkg.go.dev, github.com/coreos/go-oidc/v3/oidc.ClientContext.
func (r *Request) Context() context.Context
Context returns the request's context.
Context returns the request's context. func (r *Request) Context() context.Context. Documented at pkg.go.dev, net/http.Request.Context.
var tok *oauth2.Token
mcpauth/agentweb/service.go:177
var tok *oauth2.Token. In mcpauth/agentweb/service.go, line 177.
func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error)
Exchange converts an authorization code into a token.
golang.org/x/oauth2.Config.Exchange
Exchange converts an authorization code into a token. func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error). Documented at pkg.go.dev, golang.org/x/oauth2.Config.Exchange.
func VerifierOption(verifier string) AuthCodeOption
VerifierOption returns a PKCE code verifier [AuthCodeOption].
golang.org/x/oauth2.VerifierOption
VerifierOption returns a PKCE code verifier [AuthCodeOption]. func VerifierOption(verifier string) AuthCodeOption. Documented at pkg.go.dev, golang.org/x/oauth2.VerifierOption.
var raw string
mcpauth/agentweb/service.go:183
var raw string. In mcpauth/agentweb/service.go, line 183.
func (t *Token) Extra(key string) any
Extra returns an extra field.
golang.org/x/oauth2.Token.Extra
Extra returns an extra field. func (t *Token) Extra(key string) any. Documented at pkg.go.dev, golang.org/x/oauth2.Token.Extra.
var id *oidc.IDToken
mcpauth/agentweb/service.go:184
var id *oidc.IDToken. In mcpauth/agentweb/service.go, line 184.
field ids *oidc.IDTokenVerifier
mcpauth/agentweb/service.go:76
field ids *oidc.IDTokenVerifier. In mcpauth/agentweb/service.go, line 76.
func (v *IDTokenVerifier) Verify(ctx context.Context, rawIDToken string) (*IDToken, error)
Verify parses a raw ID Token, verifies it's been signed by the provider, performs any additional checks depending on the Config, and returns the payload.
github.com/coreos/go-oidc/v3/oidc.IDTokenVerifier.Verify
Verify parses a raw ID Token, verifies it's been signed by the provider, performs any additional checks depending on the Config, and returns the payload. func (v *IDTokenVerifier) Verify(ctx context.Context, rawIDToken string) (*IDToken, error). Documented at pkg.go.dev, github.com/coreos/go-oidc/v3/oidc.IDTokenVerifier.Verify.
var claims struct{Email string "json:\"email\""; Verified bool "json:\"email_verified\""; AZP string "json:\"azp\""}
mcpauth/agentweb/service.go:189
var claims struct{Email string "json:\"email\""; Verified bool "json:\"email_verified\""; AZP string "json:\"azp\""}. In mcpauth/agentweb/service.go, line 189.
field Email string
mcpauth/agentweb/service.go:190
field Email string. In mcpauth/agentweb/service.go, line 190.
field Verified bool
mcpauth/agentweb/service.go:191
field Verified bool. In mcpauth/agentweb/service.go, line 191.
field AZP string
mcpauth/agentweb/service.go:192
field AZP string. In mcpauth/agentweb/service.go, line 192.
func (i *IDToken) Claims(v any) error
Claims unmarshals the raw JSON payload of the ID Token into a provided struct.
github.com/coreos/go-oidc/v3/oidc.IDToken.Claims
Claims unmarshals the raw JSON payload of the ID Token into a provided struct. func (i *IDToken) Claims(v any) error. Documented at pkg.go.dev, github.com/coreos/go-oidc/v3/oidc.IDToken.Claims.
field Nonce string
Initial nonce provided during the authentication redirect.
github.com/coreos/go-oidc/v3/oidc.IDToken.Nonce
Initial nonce provided during the authentication redirect. field Nonce string. Documented at pkg.go.dev, github.com/coreos/go-oidc/v3/oidc.IDToken.Nonce.
func (s *Service) startSession(w http.ResponseWriter, user, email string)
startSession signs the browser in as user.
mcpauth/agentweb/service.go:276
startSession signs the browser in as user. func (s *Service) startSession(w http.ResponseWriter, user, email string). In mcpauth/agentweb/service.go, line 276.
field Subject string
A unique string which identifies the end user.
github.com/coreos/go-oidc/v3/oidc.IDToken.Subject
A unique string which identifies the end user. field Subject string. Documented at pkg.go.dev, github.com/coreos/go-oidc/v3/oidc.IDToken.Subject.
func (ResponseWriter) Header() Header
Header returns the header map that will be sent by [ResponseWriter.WriteHeader].
net/http.ResponseWriter.Header
Header returns the header map that will be sent by [ResponseWriter.WriteHeader]. func (ResponseWriter) Header() Header. Documented at pkg.go.dev, net/http.ResponseWriter.Header.
func (h Header) Set(key, value string)
Set sets the header entries associated with key to the single element value.
Set sets the header entries associated with key to the single element value. func (h Header) Set(key, value string). Documented at pkg.go.dev, net/http.Header.Set.
func Fprint(w io.Writer, a ...any) (n int, err error)
Fprint formats using the default formats for its operands and writes to w.
Fprint formats using the default formats for its operands and writes to w. func Fprint(w io.Writer, a ...any) (n int, err error). Documented at pkg.go.dev, fmt.Fprint.
func TestSignInRefuses(t *testing.T)
TestSignInRefuses: an answer from the identity provider signs a browser in only if it belongs to the sign-in that browser started.
mcpauth/agentweb/agentweb_test.go:198
TestSignInRefuses: an answer from the identity provider signs a browser in only if it belongs to the sign-in that browser started. func TestSignInRefuses(t *testing.T). In mcpauth/agentweb/agentweb_test.go, line 198.
var t *testing.T
mcpauth/agentweb/agentweb_test.go:198
var t *testing.T. In mcpauth/agentweb/agentweb_test.go, line 198.
package testing ("testing")
Package testing provides support for automated testing of Go packages.
Package testing provides support for automated testing of Go packages. package testing ("testing"). Documented at pkg.go.dev, testing.
type T struct {
common
denyParallel bool
tstate *testState // For running tests and subtests.
}
T is a type passed to Test functions to manage test state and support formatted test logs.
T is a type passed to Test functions to manage test state and support formatted test logs. type T struct { common denyParallel bool tstate *testState // For running tests and subtests. }. Documented at pkg.go.dev, testing.T.
var w *testWorld
mcpauth/agentweb/agentweb_test.go:199
var w *testWorld. In mcpauth/agentweb/agentweb_test.go, line 199.
func newTestWorld(t *testing.T) *testWorld
mcpauth/agentweb/agentweb_test.go:47
func newTestWorld(t *testing.T) *testWorld. In mcpauth/agentweb/agentweb_test.go, line 47.
var start func(b *http.Client, change func(url.Values)) *url.URL
mcpauth/agentweb/agentweb_test.go:202
var start func(b *http.Client, change func(url.Values)) *url.URL. In mcpauth/agentweb/agentweb_test.go, line 202.
var b *http.Client
mcpauth/agentweb/agentweb_test.go:202
var b *http.Client. In mcpauth/agentweb/agentweb_test.go, line 202.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
var change func(url.Values)
mcpauth/agentweb/agentweb_test.go:202
var change func(url.Values). In mcpauth/agentweb/agentweb_test.go, line 202.
package url ("net/url")
Package url parses URLs and implements query escaping.
Package url parses URLs and implements query escaping. package url ("net/url"). Documented at pkg.go.dev, net/url.
type Values map[string][]string
Values maps a string key to a list of values.
Values maps a string key to a list of values. type Values map[string][]string. Documented at pkg.go.dev, net/url.Values.
type URL struct {
Scheme string
Opaque string // encoded opaque data
User *Userinfo // username and password information
Host string // "host" or "host:port" (see Hostname and Port methods)
Path string // path (relative paths may omit leading slash)
Fragment string // fragment for references (without '#')
// RawQuery contains the encoded query values, without the initial '?'.
// Use URL.Query to decode the query.
// ...
}
A URL represents a parsed URL (technically, a URI reference).
A URL represents a parsed URL (technically, a URI reference). type URL struct { Scheme string Opaque string // encoded opaque data User *Userinfo // username and password information Host string // "host" or "host:port" (see Hostname and Port methods) Path string // path (relative paths may omit leading slash) Fragment string // fragment for references (without '#') // RawQuery contains the encoded query values, without the initial '?'. // Use URL.Query to decode the query. // ... }. Documented at pkg.go.dev, net/url.URL.
var loc string
mcpauth/agentweb/agentweb_test.go:203
var loc string. In mcpauth/agentweb/agentweb_test.go, line 203.
func step(t *testing.T, b *http.Client, u string) (string, []*http.Cookie)
step sends GET u from b without following a redirect, and returns where it redirects to and the cookies it sets.
mcpauth/agentweb/agentweb_test.go:131
step sends GET u from b without following a redirect, and returns where it redirects to and the cookies it sets. func step(t *testing.T, b *http.Client, u string) (string, []*http.Cookie). In mcpauth/agentweb/agentweb_test.go, line 131.
field agent string
mcpauth/agentweb/agentweb_test.go:27
field agent string. In mcpauth/agentweb/agentweb_test.go, line 27.
var authz *url.URL
mcpauth/agentweb/agentweb_test.go:204
var authz *url.URL. In mcpauth/agentweb/agentweb_test.go, line 204.
func Parse(rawURL string) (*URL, error)
Parse parses a raw url into a [URL] structure.
Parse parses a raw url into a [URL] structure. func Parse(rawURL string) (*URL, error). Documented at pkg.go.dev, net/url.Parse.
var q url.Values
mcpauth/agentweb/agentweb_test.go:205
var q url.Values. In mcpauth/agentweb/agentweb_test.go, line 205.
field RawQuery string
RawQuery contains the encoded query values, without the initial '?'.
RawQuery contains the encoded query values, without the initial '?'. field RawQuery string. Documented at pkg.go.dev, net/url.URL.RawQuery.
func (v Values) Encode() string
Encode encodes the values into “URL encoded” form ("bar=baz&foo=quux") sorted by key.
Encode encodes the values into “URL encoded” form ("bar=baz&foo=quux") sorted by key. func (v Values) Encode() string. Documented at pkg.go.dev, net/url.Values.Encode.
func (u *URL) String() string
String reassembles the [URL] into a valid URL string.
String reassembles the [URL] into a valid URL string. func (u *URL) String() string. Documented at pkg.go.dev, net/url.URL.String.
var back *url.URL
mcpauth/agentweb/agentweb_test.go:211
var back *url.URL. In mcpauth/agentweb/agentweb_test.go, line 211.
var with func(u *url.URL, k string, v string) string
mcpauth/agentweb/agentweb_test.go:214
var with func(u *url.URL, k string, v string) string. In mcpauth/agentweb/agentweb_test.go, line 214.
var u *url.URL
mcpauth/agentweb/agentweb_test.go:214
var u *url.URL. In mcpauth/agentweb/agentweb_test.go, line 214.
var k string
mcpauth/agentweb/agentweb_test.go:214
var k string. In mcpauth/agentweb/agentweb_test.go, line 214.
var v string
mcpauth/agentweb/agentweb_test.go:214
var v string. In mcpauth/agentweb/agentweb_test.go, line 214.
var q url.Values
mcpauth/agentweb/agentweb_test.go:215
var q url.Values. In mcpauth/agentweb/agentweb_test.go, line 215.
func (v Values) Set(key, value string)
Set sets the key to value.
Set sets the key to value. func (v Values) Set(key, value string). Documented at pkg.go.dev, net/url.Values.Set.
var c url.URL
mcpauth/agentweb/agentweb_test.go:217
var c url.URL. In mcpauth/agentweb/agentweb_test.go, line 217.
var victim *http.Client
mcpauth/agentweb/agentweb_test.go:221
var victim *http.Client. In mcpauth/agentweb/agentweb_test.go, line 221.
var attacker *http.Client
mcpauth/agentweb/agentweb_test.go:221
var attacker *http.Client. In mcpauth/agentweb/agentweb_test.go, line 221.
func (w *testWorld) browser(who string) *http.Client
browser is who's browser, signed in at both authorization servers.
mcpauth/agentweb/agentweb_test.go:120
browser is who's browser, signed in at both authorization servers. func (w *testWorld) browser(who string) *http.Client. In mcpauth/agentweb/agentweb_test.go, line 120.
var c struct{name string; send func() (int, string)}
mcpauth/agentweb/agentweb_test.go:222
var c struct{name string; send func() (int, string)}. In mcpauth/agentweb/agentweb_test.go, line 222.
field name string
mcpauth/agentweb/agentweb_test.go:223
field name string. In mcpauth/agentweb/agentweb_test.go, line 223.
field send func() (int, string)
mcpauth/agentweb/agentweb_test.go:224
field send func() (int, string). In mcpauth/agentweb/agentweb_test.go, line 224.
type int int
int is a signed integer type that is at least 32 bits in size.
int is a signed integer type that is at least 32 bits in size. type int int. Documented at pkg.go.dev, builtin.int.
var back *url.URL
mcpauth/agentweb/agentweb_test.go:227
var back *url.URL. In mcpauth/agentweb/agentweb_test.go, line 227.
func do(t *testing.T, c *http.Client, method, u, origin, body string) (int, string)
mcpauth/agentweb/agentweb_test.go:149
func do(t *testing.T, c *http.Client, method, u, origin, body string) (int, string). In mcpauth/agentweb/agentweb_test.go, line 149.
var back *url.URL
mcpauth/agentweb/agentweb_test.go:234
var back *url.URL. In mcpauth/agentweb/agentweb_test.go, line 234.
var q url.Values
mcpauth/agentweb/agentweb_test.go:235
var q url.Values. In mcpauth/agentweb/agentweb_test.go, line 235.
func (v Values) Del(key string)
Del deletes the values associated with key.
Del deletes the values associated with key. func (v Values) Del(key string). Documented at pkg.go.dev, net/url.Values.Del.
var mine *url.URL
mcpauth/agentweb/agentweb_test.go:244
var mine *url.URL. In mcpauth/agentweb/agentweb_test.go, line 244.
var theirs *url.URL
mcpauth/agentweb/agentweb_test.go:245
var theirs *url.URL. In mcpauth/agentweb/agentweb_test.go, line 245.
var back *url.URL
mcpauth/agentweb/agentweb_test.go:249
var back *url.URL. In mcpauth/agentweb/agentweb_test.go, line 249.
var q url.Values
mcpauth/agentweb/agentweb_test.go:249
var q url.Values. In mcpauth/agentweb/agentweb_test.go, line 249.
var code int
mcpauth/agentweb/agentweb_test.go:253
var code int. In mcpauth/agentweb/agentweb_test.go, line 253.
var body string
mcpauth/agentweb/agentweb_test.go:253
var body string. In mcpauth/agentweb/agentweb_test.go, line 253.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
func Contains(s, substr string) bool
Contains reports whether substr is within s.
Contains reports whether substr is within s. func Contains(s, substr string) bool. Documented at pkg.go.dev, strings.Contains.
func (c *common) Errorf(format string, args ...any)
Errorf is equivalent to Logf followed by Fail.
Errorf is equivalent to Logf followed by Fail. func (c *common) Errorf(format string, args ...any). Documented at pkg.go.dev, testing.common.Errorf.
type session struct {
user, email string
started, seen time.Time
}
A session is a signed-in browser.
mcpauth/agentweb/service.go:268
A session is a signed-in browser. type session struct { user, email string started, seen time.Time }. In mcpauth/agentweb/service.go, line 268.
field user string
mcpauth/agentweb/service.go:269
field user string. In mcpauth/agentweb/service.go, line 269.
field email string
mcpauth/agentweb/service.go:269
field email string. In mcpauth/agentweb/service.go, line 269.
field started time.Time
mcpauth/agentweb/service.go:270
field started time.Time. In mcpauth/agentweb/service.go, line 270.
field seen time.Time
mcpauth/agentweb/service.go:270
field seen time.Time. In mcpauth/agentweb/service.go, line 270.
var s *Service
mcpauth/agentweb/service.go:276
var s *Service. In mcpauth/agentweb/service.go, line 276.
var w http.ResponseWriter
mcpauth/agentweb/service.go:276
var w http.ResponseWriter. In mcpauth/agentweb/service.go, line 276.
var user string
mcpauth/agentweb/service.go:276
var user string. In mcpauth/agentweb/service.go, line 276.
var email string
mcpauth/agentweb/service.go:276
var email string. In mcpauth/agentweb/service.go, line 276.
var id string
mcpauth/agentweb/service.go:277
var id string. In mcpauth/agentweb/service.go, line 277.
var now time.Time
mcpauth/agentweb/service.go:277
var now time.Time. In mcpauth/agentweb/service.go, line 277.
field sessions map[string]*session
mcpauth/agentweb/service.go:82
field sessions map[string]*session. In mcpauth/agentweb/service.go, line 82.
const sessionCookie = "__Host-Http-session"
mcpauth/agentweb/service.go:88
const sessionCookie = "__Host-Http-session". In mcpauth/agentweb/service.go, line 88.
const SameSiteStrictMode
const SameSiteStrictMode. Documented at pkg.go.dev, net/http.SameSiteStrictMode.
var s *Service
mcpauth/agentweb/service.go:287
var s *Service. In mcpauth/agentweb/service.go, line 287.
func (s *Service) session(r *http.Request) (*session, string)
session returns the browser's session, if it has one that hasn't been idle for 30 minutes or open for 12 hours.
mcpauth/agentweb/service.go:287
session returns the browser's session, if it has one that hasn't been idle for 30 minutes or open for 12 hours. func (s *Service) session(r *http.Request) (*session, string). In mcpauth/agentweb/service.go, line 287.
var r *http.Request
mcpauth/agentweb/service.go:287
var r *http.Request. In mcpauth/agentweb/service.go, line 287.
var c *http.Cookie
mcpauth/agentweb/service.go:288
var c *http.Cookie. In mcpauth/agentweb/service.go, line 288.
var err error
mcpauth/agentweb/service.go:288
var err error. In mcpauth/agentweb/service.go, line 288.
var now time.Time
mcpauth/agentweb/service.go:292
var now time.Time. In mcpauth/agentweb/service.go, line 292.
var ss *session
mcpauth/agentweb/service.go:295
var ss *session. In mcpauth/agentweb/service.go, line 295.
func (t Time) Sub(u Time) Duration
Sub returns the duration t-u.
Sub returns the duration t-u. func (t Time) Sub(u Time) Duration. Documented at pkg.go.dev, time.Time.Sub.
const idleTimeout = 30 * time.Minute
mcpauth/agentweb/service.go:90
const idleTimeout = 30 * time.Minute. In mcpauth/agentweb/service.go, line 90.
const maxSession = 12 * time.Hour
mcpauth/agentweb/service.go:91
const maxSession = 12 * time.Hour. In mcpauth/agentweb/service.go, line 91.
var s *Service
mcpauth/agentweb/service.go:308
var s *Service. In mcpauth/agentweb/service.go, line 308.
func (s *Service) signedIn(h func(http.ResponseWriter, *http.Request,
*session)) http.HandlerFunc
signedIn wraps a handler that needs a session.
mcpauth/agentweb/service.go:308
signedIn wraps a handler that needs a session. func (s *Service) signedIn(h func(http.ResponseWriter, *http.Request, *session)) http.HandlerFunc. In mcpauth/agentweb/service.go, line 308.
var h func(http.ResponseWriter, *http.Request, *session)
mcpauth/agentweb/service.go:308
var h func(http.ResponseWriter, *http.Request, *session). In mcpauth/agentweb/service.go, line 308.
type HandlerFunc func(ResponseWriter, *Request)
The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers.
The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. type HandlerFunc func(ResponseWriter, *Request). Documented at pkg.go.dev, net/http.HandlerFunc.
var w http.ResponseWriter
mcpauth/agentweb/service.go:310
var w http.ResponseWriter. In mcpauth/agentweb/service.go, line 310.
var r *http.Request
mcpauth/agentweb/service.go:310
var r *http.Request. In mcpauth/agentweb/service.go, line 310.
var ss *session
mcpauth/agentweb/service.go:311
var ss *session. In mcpauth/agentweb/service.go, line 311.
const StatusUnauthorized = 401
RFC 9110, 15.5.2
RFC 9110, 15.5.2 const StatusUnauthorized = 401. Documented at pkg.go.dev, net/http.StatusUnauthorized.
field Method string
Method specifies the HTTP method (GET, POST, PUT, etc.).
Method specifies the HTTP method (GET, POST, PUT, etc.). field Method string. Documented at pkg.go.dev, net/http.Request.Method.
const MethodPost = "POST"
const MethodPost = "POST". Documented at pkg.go.dev, net/http.MethodPost.
field Header Header
Header contains the request header fields either received by the server or to be sent by the client.
Header contains the request header fields either received by the server or to be sent by the client. field Header Header. Documented at pkg.go.dev, net/http.Request.Header.
func (h Header) Get(key string) string
Get gets the first value associated with the given key.
Get gets the first value associated with the given key. func (h Header) Get(key string) string. Documented at pkg.go.dev, net/http.Header.Get.
func (s *Service) origin() string
mcpauth/agentweb/service.go:326
func (s *Service) origin() string. In mcpauth/agentweb/service.go, line 326.
const StatusForbidden = 403
RFC 9110, 15.5.4
RFC 9110, 15.5.4 const StatusForbidden = 403. Documented at pkg.go.dev, net/http.StatusForbidden.
var s *Service
mcpauth/agentweb/connect.go:42
var s *Service. In mcpauth/agentweb/connect.go, line 42.
func (s *Service) startConnect(w http.ResponseWriter, r *http.Request, ss *session)
startConnect sends a signed-in user to a provider to grant the agent access to their account there, asking for the scopes the tools need and offline_access, for a refresh token: the agent works when the user isn't there to sign in again.
mcpauth/agentweb/connect.go:42
startConnect sends a signed-in user to a provider to grant the agent access to their account there, asking for the scopes the tools need and offline_access, for a refresh token: the agent works when the user isn't there to sign in again. func (s *Service) startConnect(w http.ResponseWriter, r *http.Request, ss *session). In mcpauth/agentweb/connect.go, line 42.
var w http.ResponseWriter
mcpauth/agentweb/connect.go:42
var w http.ResponseWriter. In mcpauth/agentweb/connect.go, line 42.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
var r *http.Request
mcpauth/agentweb/connect.go:42
var r *http.Request. In mcpauth/agentweb/connect.go, line 42.
var ss *session
mcpauth/agentweb/connect.go:42
var ss *session. In mcpauth/agentweb/connect.go, line 42.
var name string
mcpauth/agentweb/connect.go:43
var name string. In mcpauth/agentweb/connect.go, line 43.
var prov Provider
mcpauth/agentweb/connect.go:43
var prov Provider. In mcpauth/agentweb/connect.go, line 43.
func (s *Service) provider(r *http.Request) (string, Provider, bool)
mcpauth/agentweb/connect.go:26
func (s *Service) provider(r *http.Request) (string, Provider, bool). In mcpauth/agentweb/connect.go, line 26.
func NotFound(w ResponseWriter, r *Request)
NotFound replies to the request with an HTTP 404 not found error.
NotFound replies to the request with an HTTP 404 not found error. func NotFound(w ResponseWriter, r *Request). Documented at pkg.go.dev, net/http.NotFound.
var p *pending
mcpauth/agentweb/connect.go:48
var p *pending. In mcpauth/agentweb/connect.go, line 48.
package rand ("crypto/rand")
Package rand implements a cryptographically secure random number generator.
Package rand implements a cryptographically secure random number generator. package rand ("crypto/rand"). Documented at pkg.go.dev, crypto/rand.
package oauth2 ("golang.org/x/oauth2")
package oauth2 ("golang.org/x/oauth2").
field user string
who is connecting, for a connection
mcpauth/agentweb/service.go:145
who is connecting, for a connection field user string. In mcpauth/agentweb/service.go, line 145.
func (p Provider) oauth(redirect string) *oauth2.Config
mcpauth/agentweb/connect.go:19
func (p Provider) oauth(redirect string) *oauth2.Config. In mcpauth/agentweb/connect.go, line 19.
func (s *Service) callbackURL(name string) string
mcpauth/agentweb/connect.go:32
func (s *Service) callbackURL(name string) string. In mcpauth/agentweb/connect.go, line 32.
func SetAuthURLParam(key, value string) AuthCodeOption
SetAuthURLParam builds an [AuthCodeOption] which passes key/value parameters to a provider's authorization endpoint.
golang.org/x/oauth2.SetAuthURLParam
SetAuthURLParam builds an [AuthCodeOption] which passes key/value parameters to a provider's authorization endpoint. func SetAuthURLParam(key, value string) AuthCodeOption. Documented at pkg.go.dev, golang.org/x/oauth2.SetAuthURLParam.
const StatusSeeOther = 303
RFC 9110, 15.4.4
RFC 9110, 15.4.4 const StatusSeeOther = 303. Documented at pkg.go.dev, net/http.StatusSeeOther.
var s *Service
mcpauth/agentweb/connect.go:59
var s *Service. In mcpauth/agentweb/connect.go, line 59.
func (s *Service) finishConnect(w http.ResponseWriter, r *http.Request, ss *session)
finishConnect redeems the provider's code and stores the credential under the user who started the connection, who must be the one signed in now.
mcpauth/agentweb/connect.go:59
finishConnect redeems the provider's code and stores the credential under the user who started the connection, who must be the one signed in now. func (s *Service) finishConnect(w http.ResponseWriter, r *http.Request, ss *session). In mcpauth/agentweb/connect.go, line 59.
var w http.ResponseWriter
mcpauth/agentweb/connect.go:59
var w http.ResponseWriter. In mcpauth/agentweb/connect.go, line 59.
var r *http.Request
mcpauth/agentweb/connect.go:59
var r *http.Request. In mcpauth/agentweb/connect.go, line 59.
var ss *session
mcpauth/agentweb/connect.go:59
var ss *session. In mcpauth/agentweb/connect.go, line 59.
var name string
mcpauth/agentweb/connect.go:60
var name string. In mcpauth/agentweb/connect.go, line 60.
var prov Provider
mcpauth/agentweb/connect.go:60
var prov Provider. In mcpauth/agentweb/connect.go, line 60.
var p *pending
mcpauth/agentweb/connect.go:65
var p *pending. In mcpauth/agentweb/connect.go, line 65.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
var ctx context.Context
mcpauth/agentweb/connect.go:73
var ctx context.Context. In mcpauth/agentweb/connect.go, line 73.
package oidc ("github.com/coreos/go-oidc/v3/oidc")
package oidc ("github.com/coreos/go-oidc/v3/oidc").
var tok *oauth2.Token
mcpauth/agentweb/connect.go:74
var tok *oauth2.Token. In mcpauth/agentweb/connect.go, line 74.
field RefreshToken string `json:"refresh_token,omitempty"`
RefreshToken is a token that's used by the application (as opposed to the user) to refresh the access token if it expires.
golang.org/x/oauth2.Token.RefreshToken
RefreshToken is a token that's used by the application (as opposed to the user) to refresh the access token if it expires. field RefreshToken string `json:"refresh_token,omitempty"`. Documented at pkg.go.dev, golang.org/x/oauth2.Token.RefreshToken.
const StatusBadGateway = 502
RFC 9110, 15.6.3
RFC 9110, 15.6.3 const StatusBadGateway = 502. Documented at pkg.go.dev, net/http.StatusBadGateway.
func (v *Vault) Put(user, provider string, t Token) error
Put stores t as user's credential at provider, replacing any before.
Put stores t as user's credential at provider, replacing any before. func (v *Vault) Put(user, provider string, t Token) error. In mcpauth/agentweb/vault.go, line 56.
type Token struct {
Access string `json:"access"`
Refresh string `json:"refresh"`
Expiry time.Time `json:"expiry"`
}
A Token is a user's credential at a provider: what the agent's tools send, what renews it, and when the first runs out by the service's own clock.
A Token is a user's credential at a provider: what the agent's tools send, what renews it, and when the first runs out by the service's own clock. type Token struct { Access string `json:"access"` Refresh string `json:"refresh"` Expiry time.Time `json:"expiry"` }. In mcpauth/agentweb/vault.go, line 17.
field Access string `json:"access"`
field Access string `json:"access"`. In mcpauth/agentweb/vault.go, line 18.
field AccessToken string `json:"access_token"`
AccessToken is the token that authorizes and authenticates the requests.
golang.org/x/oauth2.Token.AccessToken
AccessToken is the token that authorizes and authenticates the requests. field AccessToken string `json:"access_token"`. Documented at pkg.go.dev, golang.org/x/oauth2.Token.AccessToken.
field Refresh string `json:"refresh"`
field Refresh string `json:"refresh"`. In mcpauth/agentweb/vault.go, line 19.
field Expiry time.Time `json:"expiry"`
field Expiry time.Time `json:"expiry"`. In mcpauth/agentweb/vault.go, line 20.
func (s *Service) expiry(tok *oauth2.Token) time.Time
expiry is when tok runs out by the service's clock.
mcpauth/agentweb/connect.go:94
expiry is when tok runs out by the service's clock. func (s *Service) expiry(tok *oauth2.Token) time.Time. In mcpauth/agentweb/connect.go, line 94.
const StatusInternalServerError = 500
RFC 9110, 15.6.1
net/http.StatusInternalServerError
RFC 9110, 15.6.1 const StatusInternalServerError = 500. Documented at pkg.go.dev, net/http.StatusInternalServerError.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Fprintf(w io.Writer, format string, a ...any) (n int, err error)
Fprintf formats according to a format specifier and writes to w.
Fprintf formats according to a format specifier and writes to w. func Fprintf(w io.Writer, format string, a ...any) (n int, err error). Documented at pkg.go.dev, fmt.Fprintf.
field aead cipher.AEAD
field aead cipher.AEAD. In mcpauth/agentweb/vault.go, line 35.
package cipher ("crypto/cipher")
Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations.
Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations. package cipher ("crypto/cipher"). Documented at pkg.go.dev, crypto/cipher.
type AEAD interface {
// NonceSize returns the size of the nonce that must be passed to Seal
// and Open.
NonceSize() int
// Overhead returns the maximum difference between the lengths of a
// plaintext and its ciphertext.
Overhead() int
// Seal encrypts and authenticates plaintext, authenticates the
// ...
}
AEAD is a cipher mode providing authenticated encryption with associated data.
AEAD is a cipher mode providing authenticated encryption with associated data. type AEAD interface { // NonceSize returns the size of the nonce that must be passed to Seal // and Open. NonceSize() int // Overhead returns the maximum difference between the lengths of a // plaintext and its ciphertext. Overhead() int // Seal encrypts and authenticates plaintext, authenticates the // ... }. Documented at pkg.go.dev, crypto/cipher.AEAD.
field mu sync.Mutex
field mu sync.Mutex. In mcpauth/agentweb/vault.go, line 36.
package sync ("sync")
Package sync provides basic synchronization primitives such as mutual exclusion locks.
Package sync provides basic synchronization primitives such as mutual exclusion locks. package sync ("sync"). Documented at pkg.go.dev, sync.
type Mutex struct {
_ noCopy
mu isync.Mutex
}
A Mutex is a mutual exclusion lock.
A Mutex is a mutual exclusion lock. type Mutex struct { _ noCopy mu isync.Mutex }. Documented at pkg.go.dev, sync.Mutex.
field rows map[string][]byte
stands in for a table: row key to nonce and ciphertext
stands in for a table: row key to nonce and ciphertext field rows map[string][]byte. In mcpauth/agentweb/vault.go, line 37.
func NewVault(key []byte) (*Vault, error)
NewVault returns a vault that encrypts with key, 32 bytes.
NewVault returns a vault that encrypts with key, 32 bytes. func NewVault(key []byte) (*Vault, error). In mcpauth/agentweb/vault.go, line 43.
var block cipher.Block
var block cipher.Block. In mcpauth/agentweb/vault.go, line 44.
package aes ("crypto/aes")
Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.
Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197. package aes ("crypto/aes"). Documented at pkg.go.dev, crypto/aes.
func NewCipher(key []byte) (cipher.Block, error)
NewCipher creates and returns a new [cipher.Block].
NewCipher creates and returns a new [cipher.Block]. func NewCipher(key []byte) (cipher.Block, error). Documented at pkg.go.dev, crypto/aes.NewCipher.
func len(v Type) int
The len built-in function returns the length of v, according to its type:
The len built-in function returns the length of v, according to its type: func len(v Type) int. Documented at pkg.go.dev, builtin.len.
package errors ("errors")
Package errors implements functions to manipulate errors.
Package errors implements functions to manipulate errors. package errors ("errors"). Documented at pkg.go.dev, errors.
var aead cipher.AEAD
var aead cipher.AEAD. In mcpauth/agentweb/vault.go, line 48.
func NewGCM(cipher Block) (AEAD, error)
NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode with the standard nonce length.
NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode with the standard nonce length. func NewGCM(cipher Block) (AEAD, error). Documented at pkg.go.dev, crypto/cipher.NewGCM.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
var provider string
var provider string. In mcpauth/agentweb/vault.go, line 56.
var plain []byte
var plain []byte. In mcpauth/agentweb/vault.go, line 57.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
func Marshal(in any, opts ...Options) (out []byte, err error)
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options).
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options). func Marshal(in any, opts ...Options) (out []byte, err error). Documented at pkg.go.dev, encoding/json/v2.Marshal.
var nonce []byte
var nonce []byte. In mcpauth/agentweb/vault.go, line 61.
func make(t Type, size ...IntegerType) Type
The make built-in function allocates and initializes an object of type slice, map, or chan (only).
The make built-in function allocates and initializes an object of type slice, map, or chan (only). func make(t Type, size ...IntegerType) Type. Documented at pkg.go.dev, builtin.make.
func (AEAD) NonceSize() int
NonceSize returns the size of the nonce that must be passed to Seal and Open.
NonceSize returns the size of the nonce that must be passed to Seal and Open. func (AEAD) NonceSize() int. Documented at pkg.go.dev, crypto/cipher.AEAD.NonceSize.
package rand ("crypto/rand")
Package rand implements a cryptographically secure random number generator.
Package rand implements a cryptographically secure random number generator. package rand ("crypto/rand"). Documented at pkg.go.dev, crypto/rand.
func Read(b []byte) (n int, err error)
Read fills b with cryptographically secure random bytes.
Read fills b with cryptographically secure random bytes. func Read(b []byte) (n int, err error). Documented at pkg.go.dev, crypto/rand.Read.
func rowKey(user, provider string) []byte
rowKey names a row, and is the additional data it is sealed with: a JSON array, so no user or provider name can be made to look like another pair.
rowKey names a row, and is the additional data it is sealed with: a JSON array, so no user or provider name can be made to look like another pair. func rowKey(user, provider string) []byte. In mcpauth/agentweb/vault.go, line 105.
var sealed []byte
var sealed []byte. In mcpauth/agentweb/vault.go, line 64.
func (AEAD) Seal(dst, nonce, plaintext, additionalData []byte) []byte
Seal encrypts and authenticates plaintext, authenticates the additional data and appends the result to dst, returning the updated slice.
Seal encrypts and authenticates plaintext, authenticates the additional data and appends the result to dst, returning the updated slice. func (AEAD) Seal(dst, nonce, plaintext, additionalData []byte) []byte. Documented at pkg.go.dev, crypto/cipher.AEAD.Seal.
func (v *Vault) Get(user, provider string) (Token, error)
Get returns user's credential at provider, or ErrNotConnected.
Get returns user's credential at provider, or ErrNotConnected. func (v *Vault) Get(user, provider string) (Token, error). In mcpauth/agentweb/vault.go, line 72.
var provider string
var provider string. In mcpauth/agentweb/vault.go, line 72.
var sealed []byte
var sealed []byte. In mcpauth/agentweb/vault.go, line 76.
var ErrNotConnected = errors.New("not connected")
ErrNotConnected means the user hasn't connected an account at the provider, or the connection was lost and must be made again.
ErrNotConnected means the user hasn't connected an account at the provider, or the connection was lost and must be made again. var ErrNotConnected = errors.New("not connected"). In mcpauth/agentweb/vault.go, line 25.
var plain []byte
var plain []byte. In mcpauth/agentweb/vault.go, line 82.
func (AEAD) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
Open decrypts and authenticates ciphertext, authenticates the additional data and, if successful, appends the resulting plaintext to dst, returning the updated slice.
Open decrypts and authenticates ciphertext, authenticates the additional data and, if successful, appends the resulting plaintext to dst, returning the updated slice. func (AEAD) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error). Documented at pkg.go.dev, crypto/cipher.AEAD.Open.
func Unmarshal(in []byte, out any, opts ...Options) (err error)
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options).
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options). func Unmarshal(in []byte, out any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.Unmarshal.
func TestVault(t *testing.T)
TestVault: a row opens only as the user and provider it was stored for, unchanged, with the key it was sealed with.
mcpauth/agentweb/agentweb_test.go:307
TestVault: a row opens only as the user and provider it was stored for, unchanged, with the key it was sealed with. func TestVault(t *testing.T). In mcpauth/agentweb/agentweb_test.go, line 307.
var t *testing.T
mcpauth/agentweb/agentweb_test.go:307
var t *testing.T. In mcpauth/agentweb/agentweb_test.go, line 307.
var key []byte
mcpauth/agentweb/agentweb_test.go:308
var key []byte. In mcpauth/agentweb/agentweb_test.go, line 308.
package bytes ("bytes")
Package bytes implements functions for the manipulation of byte slices.
Package bytes implements functions for the manipulation of byte slices. package bytes ("bytes"). Documented at pkg.go.dev, bytes.
func Repeat(b []byte, count int) []byte
Repeat returns a new byte slice consisting of count copies of b.
Repeat returns a new byte slice consisting of count copies of b. func Repeat(b []byte, count int) []byte. Documented at pkg.go.dev, bytes.Repeat.
var v *Vault
mcpauth/agentweb/agentweb_test.go:309
var v *Vault. In mcpauth/agentweb/agentweb_test.go, line 309.
var err error
mcpauth/agentweb/agentweb_test.go:309
var err error. In mcpauth/agentweb/agentweb_test.go, line 309.
func (c *common) Fatal(args ...any)
Fatal is equivalent to Log followed by FailNow.
Fatal is equivalent to Log followed by FailNow. func (c *common) Fatal(args ...any). Documented at pkg.go.dev, testing.common.Fatal.
var err error
mcpauth/agentweb/agentweb_test.go:313
var err error. In mcpauth/agentweb/agentweb_test.go, line 313.
var got Token
mcpauth/agentweb/agentweb_test.go:316
var got Token. In mcpauth/agentweb/agentweb_test.go, line 316.
var err error
mcpauth/agentweb/agentweb_test.go:316
var err error. In mcpauth/agentweb/agentweb_test.go, line 316.
func (c *common) Fatalf(format string, args ...any)
Fatalf is equivalent to Logf followed by FailNow.
Fatalf is equivalent to Logf followed by FailNow. func (c *common) Fatalf(format string, args ...any). Documented at pkg.go.dev, testing.common.Fatalf.
var alices []byte
mcpauth/agentweb/agentweb_test.go:319
var alices []byte. In mcpauth/agentweb/agentweb_test.go, line 319.
var other *Vault
mcpauth/agentweb/agentweb_test.go:320
var other *Vault. In mcpauth/agentweb/agentweb_test.go, line 320.
var c struct{name string; v *Vault; user string; setup func()}
mcpauth/agentweb/agentweb_test.go:321
var c struct{name string; v *Vault; user string; setup func()}. In mcpauth/agentweb/agentweb_test.go, line 321.
field name string
mcpauth/agentweb/agentweb_test.go:322
field name string. In mcpauth/agentweb/agentweb_test.go, line 322.
field v *Vault
mcpauth/agentweb/agentweb_test.go:323
field v *Vault. In mcpauth/agentweb/agentweb_test.go, line 323.
field user string
mcpauth/agentweb/agentweb_test.go:324
field user string. In mcpauth/agentweb/agentweb_test.go, line 324.
field setup func()
mcpauth/agentweb/agentweb_test.go:325
field setup func(). In mcpauth/agentweb/agentweb_test.go, line 325.
var bad []byte
mcpauth/agentweb/agentweb_test.go:331
var bad []byte. In mcpauth/agentweb/agentweb_test.go, line 331.
func Clone(b []byte) []byte
Clone returns a copy of b[:len(b)].
Clone returns a copy of b[:len(b)]. func Clone(b []byte) []byte. Documented at pkg.go.dev, bytes.Clone.
var err error
mcpauth/agentweb/agentweb_test.go:340
var err error. In mcpauth/agentweb/agentweb_test.go, line 340.
func TestRefreshRotation(t *testing.T)
TestRefreshRotation: each refresh token works once, and using one a second time revokes every token descended from the same grant, the one the rightful client holds now included.
mcpauth/authserver/oidc_test.go:137
TestRefreshRotation: each refresh token works once, and using one a second time revokes every token descended from the same grant, the one the rightful client holds now included. func TestRefreshRotation(t *testing.T). In mcpauth/authserver/oidc_test.go, line 137.
var t *testing.T
mcpauth/authserver/oidc_test.go:137
var t *testing.T. In mcpauth/authserver/oidc_test.go, line 137.
package testing ("testing")
Package testing provides support for automated testing of Go packages.
Package testing provides support for automated testing of Go packages. package testing ("testing"). Documented at pkg.go.dev, testing.
var srv *httptest.Server
mcpauth/authserver/oidc_test.go:138
var srv *httptest.Server. In mcpauth/authserver/oidc_test.go, line 138.
func oidcSetup(t *testing.T) *httptest.Server
oidcSetup returns an authorization server with one confidential client, web, whose secret is s3cret.
mcpauth/authserver/oidc_test.go:20
oidcSetup returns an authorization server with one confidential client, web, whose secret is s3cret. func oidcSetup(t *testing.T) *httptest.Server. In mcpauth/authserver/oidc_test.go, line 20.
var body map[string]any
mcpauth/authserver/oidc_test.go:139
var body map[string]any. In mcpauth/authserver/oidc_test.go, line 139.
func redeem(t *testing.T, srv *httptest.Server, secret, code, res string) (int, map[string]any)
mcpauth/authserver/oidc_test.go:78
func redeem(t *testing.T, srv *httptest.Server, secret, code, res string) (int, map[string]any). In mcpauth/authserver/oidc_test.go, line 78.
func codeFor(t *testing.T, srv *httptest.Server, scope, res, nonce string) string
codeFor runs an authorization request for web and returns the code.
mcpauth/authserver/oidc_test.go:35
codeFor runs an authorization request for web and returns the code. func codeFor(t *testing.T, srv *httptest.Server, scope, res, nonce string) string. In mcpauth/authserver/oidc_test.go, line 35.
const resource = "https://mcp.example.com/mcp"
mcpauth/authserver/authserver_test.go:14
const resource = "https://mcp.example.com/mcp". In mcpauth/authserver/authserver_test.go, line 14.
var first string
mcpauth/authserver/oidc_test.go:141
var first string. In mcpauth/authserver/oidc_test.go, line 141.
var refresh func(rt string) (int, map[string]any)
mcpauth/authserver/oidc_test.go:142
var refresh func(rt string) (int, map[string]any). In mcpauth/authserver/oidc_test.go, line 142.
var rt string
mcpauth/authserver/oidc_test.go:142
var rt string. In mcpauth/authserver/oidc_test.go, line 142.
type any = interface{}
any is an alias for interface{} and is equivalent to interface{} in all ways.
any is an alias for interface{} and is equivalent to interface{} in all ways. type any = interface{}. Documented at pkg.go.dev, builtin.any.
func tokenReq(t *testing.T, srv *httptest.Server, path, secret string,
form url.Values) (int, map[string]any)
tokenReq posts form to the token endpoint as web with secret.
mcpauth/authserver/oidc_test.go:61
tokenReq posts form to the token endpoint as web with secret. func tokenReq(t *testing.T, srv *httptest.Server, path, secret string, form url.Values) (int, map[string]any). In mcpauth/authserver/oidc_test.go, line 61.
package url ("net/url")
Package url parses URLs and implements query escaping.
Package url parses URLs and implements query escaping. package url ("net/url"). Documented at pkg.go.dev, net/url.
var status int
mcpauth/authserver/oidc_test.go:146
var status int. In mcpauth/authserver/oidc_test.go, line 146.
var second string
mcpauth/authserver/oidc_test.go:147
var second string. In mcpauth/authserver/oidc_test.go, line 147.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
const StatusOK = 200
RFC 9110, 15.3.1
RFC 9110, 15.3.1 const StatusOK = 200. Documented at pkg.go.dev, net/http.StatusOK.
var status int
mcpauth/authserver/oidc_test.go:151
var status int. In mcpauth/authserver/oidc_test.go, line 151.
var body map[string]any
mcpauth/authserver/oidc_test.go:151
var body map[string]any. In mcpauth/authserver/oidc_test.go, line 151.
var status int
mcpauth/authserver/oidc_test.go:155
var status int. In mcpauth/authserver/oidc_test.go, line 155.
var s *Service
mcpauth/agentweb/connect.go:105
var s *Service. In mcpauth/agentweb/connect.go, line 105.
func (s *Service) TokenFor(ctx context.Context, user, provider string) (string, error)
TokenFor returns an access token for user's account at provider, refreshing it when it has run out.
mcpauth/agentweb/connect.go:105
TokenFor returns an access token for user's account at provider, refreshing it when it has run out. func (s *Service) TokenFor(ctx context.Context, user, provider string) (string, error). In mcpauth/agentweb/connect.go, line 105.
var ctx context.Context
mcpauth/agentweb/connect.go:105
var ctx context.Context. In mcpauth/agentweb/connect.go, line 105.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
var user string
mcpauth/agentweb/connect.go:105
var user string. In mcpauth/agentweb/connect.go, line 105.
var provider string
mcpauth/agentweb/connect.go:105
var provider string. In mcpauth/agentweb/connect.go, line 105.
var err error
mcpauth/agentweb/connect.go:106
var err error. In mcpauth/agentweb/connect.go, line 106.
field flight singleflight.Group
refreshes in progress, by user and provider
mcpauth/agentweb/service.go:84
refreshes in progress, by user and provider field flight singleflight.Group. In mcpauth/agentweb/service.go, line 84.
func (g *Group) Do(key string, fn func() (any, error)) (v any, err error, shared bool)
Do executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time.
golang.org/x/sync/singleflight.Group.Do
Do executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time. func (g *Group) Do(key string, fn func() (any, error)) (v any, err error, shared bool). Documented at pkg.go.dev, golang.org/x/sync/singleflight.Group.Do.
func (s *Service) current(ctx context.Context, user, name string) (string, error)
mcpauth/agentweb/connect.go:119
func (s *Service) current(ctx context.Context, user, name string) (string, error). In mcpauth/agentweb/connect.go, line 119.
func WithoutCancel(parent Context) Context
WithoutCancel returns a derived context that points to the parent context and is not canceled when parent is canceled.
WithoutCancel returns a derived context that points to the parent context and is not canceled when parent is canceled. func WithoutCancel(parent Context) Context. Documented at pkg.go.dev, context.WithoutCancel.
const margin = 30 * time.Second
The margin before expiry at which a token counts as run out, so a request doesn't set off with a token that expires on the way.
mcpauth/agentweb/connect.go:117
The margin before expiry at which a token counts as run out, so a request doesn't set off with a token that expires on the way. const margin = 30 * time.Second. In mcpauth/agentweb/connect.go, line 117.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
const Second = 1000 * Millisecond
const Second = 1000 * Millisecond. Documented at pkg.go.dev, time.Second.
var s *Service
mcpauth/agentweb/connect.go:119
var s *Service. In mcpauth/agentweb/connect.go, line 119.
var ctx context.Context
mcpauth/agentweb/connect.go:119
var ctx context.Context. In mcpauth/agentweb/connect.go, line 119.
var user string
mcpauth/agentweb/connect.go:119
var user string. In mcpauth/agentweb/connect.go, line 119.
var name string
mcpauth/agentweb/connect.go:119
var name string. In mcpauth/agentweb/connect.go, line 119.
var err error
mcpauth/agentweb/connect.go:120
var err error. In mcpauth/agentweb/connect.go, line 120.
func (t Time) Before(u Time) bool
Before reports whether the time instant t is before u.
Before reports whether the time instant t is before u. func (t Time) Before(u Time) bool. Documented at pkg.go.dev, time.Time.Before.
var cancel context.CancelFunc
mcpauth/agentweb/connect.go:127
var cancel context.CancelFunc. In mcpauth/agentweb/connect.go, line 127.
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc). Documented at pkg.go.dev, context.WithTimeout.
var prov Provider
mcpauth/agentweb/connect.go:130
var prov Provider. In mcpauth/agentweb/connect.go, line 130.
var nt *oauth2.Token
mcpauth/agentweb/connect.go:131
var nt *oauth2.Token. In mcpauth/agentweb/connect.go, line 131.
func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource
TokenSource returns a [TokenSource] that returns t until t expires, automatically refreshing it as necessary using the provided context.
golang.org/x/oauth2.Config.TokenSource
TokenSource returns a [TokenSource] that returns t until t expires, automatically refreshing it as necessary using the provided context. func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource. Documented at pkg.go.dev, golang.org/x/oauth2.Config.TokenSource.
type Token struct {
// AccessToken is the token that authorizes and authenticates
// the requests.
AccessToken string `json:"access_token"`
// TokenType is the type of token.
// The Type method returns either this or "Bearer", the default.
TokenType string `json:"token_type,omitempty"`
// RefreshToken is a token that's used by the application
// ...
}
Token represents the credentials used to authorize the requests to access protected resources on the OAuth 2.0 provider's backend.
Token represents the credentials used to authorize the requests to access protected resources on the OAuth 2.0 provider's backend. type Token struct { // AccessToken is the token that authorizes and authenticates // the requests. AccessToken string `json:"access_token"` // TokenType is the type of token. // The Type method returns either this or "Bearer", the default. TokenType string `json:"token_type,omitempty"` // RefreshToken is a token that's used by the application // ... }. Documented at pkg.go.dev, golang.org/x/oauth2.Token.
func (TokenSource) Token() (*Token, error)
Token returns a token or an error.
golang.org/x/oauth2.TokenSource.Token
Token returns a token or an error. func (TokenSource) Token() (*Token, error). Documented at pkg.go.dev, golang.org/x/oauth2.TokenSource.Token.
var re *oauth2.RetrieveError
mcpauth/agentweb/connect.go:133
var re *oauth2.RetrieveError. In mcpauth/agentweb/connect.go, line 133.
type RetrieveError struct {
Response *http.Response
// Body is the body that was consumed by reading Response.Body.
// It may be truncated.
Body []byte
// ErrorCode is RFC 6749's 'error' parameter.
ErrorCode string
// ErrorDescription is RFC 6749's 'error_description' parameter.
ErrorDescription string
// ErrorURI is RFC 6749's 'error_uri' parameter.
ErrorURI string
}
RetrieveError is the error returned when the token endpoint returns a non-2XX HTTP status code or populates RFC 6749's 'error' parameter.
golang.org/x/oauth2.RetrieveError
RetrieveError is the error returned when the token endpoint returns a non-2XX HTTP status code or populates RFC 6749's 'error' parameter. type RetrieveError struct { Response *http.Response // Body is the body that was consumed by reading Response.Body. // It may be truncated. Body []byte // ErrorCode is RFC 6749's 'error' parameter. ErrorCode string // ErrorDescription is RFC 6749's 'error_description' parameter. ErrorDescription string // ErrorURI is RFC 6749's 'error_uri' parameter. ErrorURI string }. Documented at pkg.go.dev, golang.org/x/oauth2.RetrieveError.
func As(err error, target any) bool
As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true.
As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true. func As(err error, target any) bool. Documented at pkg.go.dev, errors.As.
field ErrorCode string
ErrorCode is RFC 6749's 'error' parameter.
golang.org/x/oauth2.RetrieveError.ErrorCode
ErrorCode is RFC 6749's 'error' parameter. field ErrorCode string. Documented at pkg.go.dev, golang.org/x/oauth2.RetrieveError.ErrorCode.
func (v *Vault) Delete(user, provider string)
Delete removes user's credential at provider.
Delete removes user's credential at provider. func (v *Vault) Delete(user, provider string). In mcpauth/agentweb/vault.go, line 96.
var next Token
mcpauth/agentweb/connect.go:141
var next Token. In mcpauth/agentweb/connect.go, line 141.
var err error
mcpauth/agentweb/connect.go:145
var err error. In mcpauth/agentweb/connect.go, line 145.
func TestOneRefreshAtATime(t *testing.T)
TestOneRefreshAtATime: many tool calls finding the token expired at once share one refresh.
mcpauth/agentweb/agentweb_test.go:354
TestOneRefreshAtATime: many tool calls finding the token expired at once share one refresh. func TestOneRefreshAtATime(t *testing.T). In mcpauth/agentweb/agentweb_test.go, line 354.
var t *testing.T
mcpauth/agentweb/agentweb_test.go:354
var t *testing.T. In mcpauth/agentweb/agentweb_test.go, line 354.
var w *testWorld
mcpauth/agentweb/agentweb_test.go:355
var w *testWorld. In mcpauth/agentweb/agentweb_test.go, line 355.
var b *http.Client
mcpauth/agentweb/agentweb_test.go:356
var b *http.Client. In mcpauth/agentweb/agentweb_test.go, line 356.
func (w *testWorld) signIn(t *testing.T, b *http.Client)
mcpauth/agentweb/agentweb_test.go:168
func (w *testWorld) signIn(t *testing.T, b *http.Client). In mcpauth/agentweb/agentweb_test.go, line 168.
func (w *testWorld) connect(t *testing.T, b *http.Client)
mcpauth/agentweb/agentweb_test.go:175
func (w *testWorld) connect(t *testing.T, b *http.Client). In mcpauth/agentweb/agentweb_test.go, line 175.
func (w *testWorld) advance(d time.Duration)
mcpauth/agentweb/agentweb_test.go:41
func (w *testWorld) advance(d time.Duration). In mcpauth/agentweb/agentweb_test.go, line 41.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
var wg sync.WaitGroup
mcpauth/agentweb/agentweb_test.go:360
var wg sync.WaitGroup. In mcpauth/agentweb/agentweb_test.go, line 360.
package sync ("sync")
Package sync provides basic synchronization primitives such as mutual exclusion locks.
Package sync provides basic synchronization primitives such as mutual exclusion locks. package sync ("sync"). Documented at pkg.go.dev, sync.
type WaitGroup struct {
noCopy noCopy
// Bits (high to low):
// bits[0:32] counter
// bits[32] flag: synctest bubble membership
// bits[33:64] wait count
state atomic.Uint64
sema uint32
}
A WaitGroup is a counting semaphore typically used to wait for a group of goroutines or tasks to finish.
A WaitGroup is a counting semaphore typically used to wait for a group of goroutines or tasks to finish. type WaitGroup struct { noCopy noCopy // Bits (high to low): // bits[0:32] counter // bits[32] flag: synctest bubble membership // bits[33:64] wait count state atomic.Uint64 sema uint32 }. Documented at pkg.go.dev, sync.WaitGroup.
var toks []string
mcpauth/agentweb/agentweb_test.go:361
var toks []string. In mcpauth/agentweb/agentweb_test.go, line 361.
var errs []error
mcpauth/agentweb/agentweb_test.go:362
var errs []error. In mcpauth/agentweb/agentweb_test.go, line 362.
var i int
mcpauth/agentweb/agentweb_test.go:363
var i int. In mcpauth/agentweb/agentweb_test.go, line 363.
func (wg *WaitGroup) Go(f func())
Go calls f in a new goroutine and adds that task to the [WaitGroup].
Go calls f in a new goroutine and adds that task to the [WaitGroup]. func (wg *WaitGroup) Go(f func()). Documented at pkg.go.dev, sync.WaitGroup.Go.
field svc *Service
mcpauth/agentweb/agentweb_test.go:26
field svc *Service. In mcpauth/agentweb/agentweb_test.go, line 26.
func (c *common) Context() context.Context
Context returns a context that is canceled just before Cleanup-registered functions are called.
Context returns a context that is canceled just before Cleanup-registered functions are called. func (c *common) Context() context.Context. Documented at pkg.go.dev, testing.common.Context.
func (wg *WaitGroup) Wait()
Wait blocks until the [WaitGroup] task counter is zero.
Wait blocks until the [WaitGroup] task counter is zero. func (wg *WaitGroup) Wait(). Documented at pkg.go.dev, sync.WaitGroup.Wait.
var i int
mcpauth/agentweb/agentweb_test.go:369
var i int. In mcpauth/agentweb/agentweb_test.go, line 369.
var n int32
mcpauth/agentweb/agentweb_test.go:374
var n int32. In mcpauth/agentweb/agentweb_test.go, line 374.
field refreshes atomic.Int32
refresh grants at the calendar
mcpauth/agentweb/agentweb_test.go:29
refresh grants at the calendar field refreshes atomic.Int32. In mcpauth/agentweb/agentweb_test.go, line 29.
func (x *Int32) Load() int32
Load atomically loads and returns the value stored in x.
Load atomically loads and returns the value stored in x. func (x *Int32) Load() int32. Documented at pkg.go.dev, sync/atomic.Int32.Load.
var reply string
mcpauth/agentweb/agentweb_test.go:377
var reply string. In mcpauth/agentweb/agentweb_test.go, line 377.
func (w *testWorld) ask(t *testing.T, b *http.Client) string
mcpauth/agentweb/agentweb_test.go:182
func (w *testWorld) ask(t *testing.T, b *http.Client) string. In mcpauth/agentweb/agentweb_test.go, line 182.
var s *Service
mcpauth/agentweb/connect.go:206
var s *Service. In mcpauth/agentweb/connect.go, line 206.
func (s *Service) ask(w http.ResponseWriter, r *http.Request, ss *session)
ask runs one turn of the agent for the signed-in user.
mcpauth/agentweb/connect.go:206
ask runs one turn of the agent for the signed-in user. func (s *Service) ask(w http.ResponseWriter, r *http.Request, ss *session). In mcpauth/agentweb/connect.go, line 206.
var w http.ResponseWriter
mcpauth/agentweb/connect.go:206
var w http.ResponseWriter. In mcpauth/agentweb/connect.go, line 206.
var r *http.Request
mcpauth/agentweb/connect.go:206
var r *http.Request. In mcpauth/agentweb/connect.go, line 206.
var ss *session
mcpauth/agentweb/connect.go:206
var ss *session. In mcpauth/agentweb/connect.go, line 206.
var req struct{Question string "json:\"question\""}
mcpauth/agentweb/connect.go:207
var req struct{Question string "json:\"question\""}. In mcpauth/agentweb/connect.go, line 207.
field Question string
mcpauth/agentweb/connect.go:208
field Question string. In mcpauth/agentweb/connect.go, line 208.
field Body io.ReadCloser
Body is the request's body.
Body is the request's body. field Body io.ReadCloser. Documented at pkg.go.dev, net/http.Request.Body.
func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
MaxBytesReader is similar to io.LimitReader but is intended for limiting the size of incoming request bodies.
MaxBytesReader is similar to io.LimitReader but is intended for limiting the size of incoming request bodies. func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser. Documented at pkg.go.dev, net/http.MaxBytesReader.
var err error
mcpauth/agentweb/connect.go:211
var err error. In mcpauth/agentweb/connect.go, line 211.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
func UnmarshalRead(in io.Reader, out any, opts ...Options) (err error)
UnmarshalRead deserializes a Go value from an io.Reader according to the provided unmarshal and decode options (while ignoring marshal or encode options).
encoding/json/v2.UnmarshalRead
UnmarshalRead deserializes a Go value from an io.Reader according to the provided unmarshal and decode options (while ignoring marshal or encode options). func UnmarshalRead(in io.Reader, out any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.UnmarshalRead.
var name string
mcpauth/agentweb/connect.go:215
var name string. In mcpauth/agentweb/connect.go, line 215.
var args []byte
mcpauth/agentweb/connect.go:215
var args []byte. In mcpauth/agentweb/connect.go, line 215.
var tool Tool
mcpauth/agentweb/connect.go:216
var tool Tool. In mcpauth/agentweb/connect.go, line 216.
var reply string
mcpauth/agentweb/connect.go:217
var reply string. In mcpauth/agentweb/connect.go, line 217.
var out string
mcpauth/agentweb/connect.go:219
var out string. In mcpauth/agentweb/connect.go, line 219.
var err error
mcpauth/agentweb/connect.go:219
var err error. In mcpauth/agentweb/connect.go, line 219.
func Is(err, target error) bool
Is reports whether any error in err's tree matches target.
Is reports whether any error in err's tree matches target. func Is(err, target error) bool. Documented at pkg.go.dev, errors.Is.
func Sprintf(format string, a ...any) string
Sprintf formats according to a format specifier and returns the resulting string.
Sprintf formats according to a format specifier and returns the resulting string. func Sprintf(format string, a ...any) string. Documented at pkg.go.dev, fmt.Sprintf.
func MarshalWrite(out io.Writer, in any, opts ...Options) (err error)
MarshalWrite serializes a Go value into an io.Writer according to the provided marshal and encode options (while ignoring unmarshal or decode options).
MarshalWrite serializes a Go value into an io.Writer according to the provided marshal and encode options (while ignoring unmarshal or decode options). func MarshalWrite(out io.Writer, in any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.MarshalWrite.
func NextMeeting(api string) Tool
NextMeeting is a tool that reads the user's next meeting from the calendar API at api, with the user's own credential for the provider named calendar.
NextMeeting is a tool that reads the user's next meeting from the calendar API at api, with the user's own credential for the provider named calendar. func NextMeeting(api string) Tool. In mcpauth/agentweb/tools.go, line 16.
var ctx context.Context
var ctx context.Context. In mcpauth/agentweb/tools.go, line 17.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
var req *http.Request
var req *http.Request. In mcpauth/agentweb/tools.go, line 22.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
NewRequestWithContext returns a new [Request] given a method, URL, and optional body.
net/http.NewRequestWithContext
NewRequestWithContext returns a new [Request] given a method, URL, and optional body. func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error). Documented at pkg.go.dev, net/http.NewRequestWithContext.
const MethodGet = "GET"
const MethodGet = "GET". Documented at pkg.go.dev, net/http.MethodGet.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
var resp *http.Response
var resp *http.Response. In mcpauth/agentweb/tools.go, line 27.
func (c *Client) Do(req *Request) (*Response, error)
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.
Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client. func (c *Client) Do(req *Request) (*Response, error). Documented at pkg.go.dev, net/http.Client.Do.
field Body io.ReadCloser
Body represents the response body.
Body represents the response body. field Body io.ReadCloser. Documented at pkg.go.dev, net/http.Response.Body.
func (Closer) Close() error
func (Closer) Close() error. Documented at pkg.go.dev, io.Closer.Close.
field StatusCode int
e.g.
e.g. field StatusCode int. Documented at pkg.go.dev, net/http.Response.StatusCode.
field Status string
e.g.
e.g. field Status string. Documented at pkg.go.dev, net/http.Response.Status.
var events []struct{Title string "json:\"title\""; Start string "json:\"start\""}
var events []struct{Title string "json:\"title\""; Start string "json:\"start\""}. In mcpauth/agentweb/tools.go, line 35.
field Title string
field Title string. In mcpauth/agentweb/tools.go, line 36.
field Start string
field Start string. In mcpauth/agentweb/tools.go, line 37.
package io ("io")
Package io provides basic interfaces to I/O primitives.
Package io provides basic interfaces to I/O primitives. package io ("io"). Documented at pkg.go.dev, io.
func ReadAll(r Reader) ([]byte, error)
ReadAll reads from r until an error or EOF and returns the data it read.
ReadAll reads from r until an error or EOF and returns the data it read. func ReadAll(r Reader) ([]byte, error). Documented at pkg.go.dev, io.ReadAll.
func LimitReader(r Reader, n int64) Reader
LimitReader returns a Reader that reads from r but stops with EOF after n bytes.
LimitReader returns a Reader that reads from r but stops with EOF after n bytes. func LimitReader(r Reader, n int64) Reader. Documented at pkg.go.dev, io.LimitReader.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
var s *Service
mcpauth/agentweb/connect.go:159
var s *Service. In mcpauth/agentweb/connect.go, line 159.
func (s *Service) disconnect(w http.ResponseWriter, r *http.Request, ss *session)
disconnect revokes the user's refresh token at the provider (RFC 7009), which also ends every token descended from it, and then forgets the credential.
mcpauth/agentweb/connect.go:159
disconnect revokes the user's refresh token at the provider (RFC 7009), which also ends every token descended from it, and then forgets the credential. func (s *Service) disconnect(w http.ResponseWriter, r *http.Request, ss *session). In mcpauth/agentweb/connect.go, line 159.
var w http.ResponseWriter
mcpauth/agentweb/connect.go:159
var w http.ResponseWriter. In mcpauth/agentweb/connect.go, line 159.
var r *http.Request
mcpauth/agentweb/connect.go:159
var r *http.Request. In mcpauth/agentweb/connect.go, line 159.
var ss *session
mcpauth/agentweb/connect.go:159
var ss *session. In mcpauth/agentweb/connect.go, line 159.
var name string
mcpauth/agentweb/connect.go:160
var name string. In mcpauth/agentweb/connect.go, line 160.
var prov Provider
mcpauth/agentweb/connect.go:160
var prov Provider. In mcpauth/agentweb/connect.go, line 160.
var err error
mcpauth/agentweb/connect.go:165
var err error. In mcpauth/agentweb/connect.go, line 165.
const StatusNotFound = 404
RFC 9110, 15.5.5
RFC 9110, 15.5.5 const StatusNotFound = 404. Documented at pkg.go.dev, net/http.StatusNotFound.
var err error
mcpauth/agentweb/connect.go:170
var err error. In mcpauth/agentweb/connect.go, line 170.
func (s *Service) revoke(ctx context.Context, p Provider, refresh string) error
mcpauth/agentweb/connect.go:180
func (s *Service) revoke(ctx context.Context, p Provider, refresh string) error. In mcpauth/agentweb/connect.go, line 180.
func (ResponseWriter) WriteHeader(statusCode int)
WriteHeader sends an HTTP response header with the provided status code.
net/http.ResponseWriter.WriteHeader
WriteHeader sends an HTTP response header with the provided status code. func (ResponseWriter) WriteHeader(statusCode int). Documented at pkg.go.dev, net/http.ResponseWriter.WriteHeader.
const StatusNoContent = 204
RFC 9110, 15.3.5
RFC 9110, 15.3.5 const StatusNoContent = 204. Documented at pkg.go.dev, net/http.StatusNoContent.

