oauth

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2026 License: AGPL-3.0 Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package oauth is Agent GM's OAuth 2.1 authorization server (spec section 9).

claude.ai and ChatGPT connectors require one. The design is carried over from Agent MX with the Matrix-specific parts removed and the issuer fixed, and with one deliberate simplification recorded as decision D20: **client resolution is DCR-only**. There is no preregistered client table, no Client ID Metadata Document fetch, and therefore no outbound HTTP from this package at all -- which removes the SSRF surface rather than defending it. Every client this server will ever see registers itself.

Three properties are worth stating once, because the rest of the package depends on them:

  • **The issuer is a byte string, not a URL.** `issuer` equals AGENT_GM_PUBLIC_URL exactly and `resource` is that plus `/mcp`. Both are compared as string equality and never as parsed-URL equivalence (section 9.2), because a client that normalises differently must still match.
  • **The request ID conveys no authority.** Every `/oauth/requests` route answers 404 without the signed context cookie, so knowing an `authreq_` ID buys nothing.
  • **Nothing here stores a credential value.** Enrollment codes, authorization codes and the two browser secrets all reach the database as hashes. See compare.go, which is the only file in this package permitted to compare a caller-supplied value against a stored one, and comparison_audit_test.go, which enforces that by parsing this package's own source, exactly as `internal/authz` does.

Index

Constants

View Source
const (
	MinEnrollmentTTL = time.Minute
	MaxEnrollmentTTL = 24 * time.Hour
)

EnrollmentTTLBounds are section 9.5's: a duration between one minute and 24 hours, capped at 24 hours.

View Source
const (
	ErrInvalidRequest          = "invalid_request"
	ErrInvalidClientMetadata   = "invalid_client_metadata"
	ErrInvalidRedirectURI      = "invalid_redirect_uri"
	ErrInvalidClient           = "invalid_client"
	ErrInvalidGrant            = "invalid_grant"
	ErrInvalidScope            = "invalid_scope"
	ErrInvalidTarget           = "invalid_target"
	ErrUnsupportedResponseType = "unsupported_response_type"
	ErrUnsupportedGrantType    = "unsupported_grant_type"
	ErrAccessDenied            = "access_denied"
	ErrServerError             = "server_error"
	ErrTemporarilyUnavailable  = "temporarily_unavailable"
)

The RFC 6749 / RFC 7591 / RFC 8707 error codes this server produces. They are the `error` member of every OAuth error body and of every error redirect.

View Source
const (
	MaxRedirectURIs      = 10
	MaxRedirectURILength = 500
)

MaxRedirectURIs and MaxRedirectURILength are section 9.3's bounds.

View Source
const CookieName = "agm_oauth_context"

CookieName is the signed context cookie of spec section 9.4.

View Source
const GenericEnrollmentFailure = "That enrollment code was not accepted. Check it and try again, or ask the owner for a new one."

GenericEnrollmentFailure is the ONE message an invalid enrollment code produces, byte-identical for unknown, expired, revoked and consumed (spec section 9.4, section 16 Slice 3 test 5).

It is a single exported constant rather than four call sites that happen to agree, because four sites that happen to agree are four sites one edit away from telling an attacker which of their guesses was once a real code.

View Source
const GlobalScopeDisclosure = "This will let the client read and send as any Google account on this server, including accounts added later."

GlobalScopeDisclosure is the fixed line rendered verbatim ABOVE the scope checkboxes, because scopes are global across accounts (D29, sections 9.4 and 9.7).

It is part of the screen's contract and section 16 Slice 3 test 18 asserts it as a string. That assertion is what makes section 9.7's claim to honesty testable rather than aspirational: the owner approves knowing that a token reaches every account this server holds, including ones added later.

View Source
const RegistrationTTL = 24 * time.Hour

RegistrationTTL is how long a registration lives before an authorization activates it (spec section 9.3).

View Source
const RegistrationsPerSourcePerHour = 20

RegistrationsPerSourcePerHour is section 9.3's budget. It is counted over rows rather than a token bucket, so it survives a restart -- a registration is a durable object, and forgiving it on restart would forgive something that is still there.

View Source
const SourceURL = "https://github.com/thisnick/agent-gm"

SourceURL is the repository this server's source lives in. It is the `resource_documentation` of the protected-resource document, and it is the same URL section 1.4's AGPL obligation puts in `GET /v1/health`.

View Source
const StatusExpired = "expired"

StatusExpired is the status the API reports for a pending request whose deadline has passed. It is derived rather than stored: a sweep that had to run before an expiry took effect would make expiry depend on a timer.

Variables

DefaultEnrollmentCeiling is the scope ceiling a code carries when the owner names none: read and write, but never delete and never admin.

Delete is left out deliberately. A code issued without thinking should not be able to grant the one permission whose mistakes cannot be undone; an owner who wants it says so.

DefaultScopes is what `GET /oauth/authorize` requests when the client sends no `scope` (spec section 9.4).

ScopesSupported is the three messaging scopes, in the order both documents list them. `admin` is not here and never will be: it is issued only by the admin bootstrap and is invalid_scope at /oauth/authorize (section 9.7).

Functions

func CanonicalEnrollmentCode

func CanonicalEnrollmentCode(raw string) string

CanonicalEnrollmentCode is the form the hash is taken over: upper case, with every character outside the alphabet removed.

It is exported because it is part of the contract -- `docs/oauth.md` documents it so an owner can reproduce `enrollment_codes.code_hash` with `printf '%s' A1B2C3D4E5F6G7H8 | sha256sum` and check for themselves that the value is not in the database.

func EnrollmentCodeHash

func EnrollmentCodeHash(raw string) string

EnrollmentCodeHash is the stored form: plain SHA-256 of the canonical form, hex. Plain, and documented as plain, for the reason at the top of this file.

func IsLoopbackRedirect

func IsLoopbackRedirect(raw string) bool

IsLoopbackRedirect reports whether a registered URI is one of the three loopback forms, which is what makes it port-agnostic at authorization time.

func MatchRegisteredRedirect

func MatchRegisteredRedirect(registered []string, presented string) (string, bool)

MatchRegisteredRedirect returns the registered URI that matches, or "" and false. The presented value is returned rather than the registered one where they differ only by port, because that is the URI the code is bound to and the one the token endpoint will require exactly.

func NewEnrollmentCode

func NewEnrollmentCode() (string, error)

NewEnrollmentCode mints a code value. It is returned to the owner exactly once and never stored (spec section 9.5).

The form is four groups of four characters separated by hyphens -- `A1B2-C3D4-E5F6-G7H8` -- which is 80 bits of entropy, and the hyphens are cosmetic: CanonicalEnrollmentCode strips them.

func RedirectMatches

func RedirectMatches(registered, offered string) bool

RedirectMatches reports whether a redirect URI presented at `/oauth/authorize` matches one that was registered.

A registered loopback redirect matches ANY PORT (RFC 8252 section 7.3), for `127.0.0.1`, `[::1]` and `localhost` alike -- because a native client binds an ephemeral port it cannot know at registration time. Everything else about the URI must still be equal: scheme, host, path and query. So a registered `http://127.0.0.1/cb` matches `http://127.0.0.1:53211/cb`, and matches neither `http://127.0.0.1:53211/cb2` nor `http://127.0.0.2/cb`.

Note what is NOT relaxed: the token endpoint still requires `redirect_uri` to equal the one bound to the code exactly (section 9.3), so the port a client authorized on is the port it must present at exchange.

func ValidateRedirectURI

func ValidateRedirectURI(raw string) error

ValidateRedirectURI reports why a registration's redirect URI is refused, or nil if it is acceptable.

Types

type Account

type Account struct {
	ID      string
	Address string
	Label   string
}

Account is one Google account, as the authorization screen names it.

type AuthorizationRequest

type AuthorizationRequest struct {
	ID          string `json:"id"`
	ClientID    string `json:"client_id"`
	ClientName  string `json:"client_name,omitempty"`
	RedirectURI string `json:"redirect_uri"`
	// Scopes is the effective set: what was granted if the owner has
	// decided, else what the browser selected. It is served alongside the
	// three underlying sets rather than instead of them, because "what does
	// this request currently amount to" is the question an owner asks, and
	// answering it by making them compare three arrays answers a different
	// one.
	Scopes          []string `json:"scopes"`
	RequestedScopes []string `json:"requested_scopes"`
	SelectedScopes  []string `json:"selected_scopes"`
	GrantedScopes   []string `json:"granted_scopes,omitempty"`
	// AuthorizationID is the grant this request eventually minted. It is
	// null until the browser completes and the token endpoint runs -- the
	// owner approves BEFORE anything is minted -- and it is what
	// `agm admin authorizations revoke` is given to undo the whole thing.
	AuthorizationID *string `json:"authorization_id"`
	Status          string  `json:"status"`
	DenyReason      string  `json:"deny_reason,omitempty"`
	Source          string  `json:"source,omitempty"`
	ExpiresAt       *string `json:"expires_at"`
	DecidedAt       *string `json:"decided_at"`
	CompletedAt     *string `json:"completed_at"`
	CreatedAt       *string `json:"created_at"`
}

AuthorizationRequest is one pending decision as the owner sees it. It carries no secret: not the handle, not the form token, not a code.

type Client

type Client struct {
	ID           string   `json:"id"`
	Name         string   `json:"name,omitempty"`
	RedirectURIs []string `json:"redirect_uris"`
	GrantTypes   []string `json:"grant_types"`
	Source       string   `json:"source,omitempty"`
	ActivatedAt  *string  `json:"activated_at"`
	ExpiresAt    *string  `json:"expires_at"`
	CreatedAt    *string  `json:"created_at"`
}

Client is one dynamic registration as the owner sees it.

type Config

type Config struct {
	// PublicURL is AGENT_GM_PUBLIC_URL. It is the issuer BYTE FOR BYTE, and
	// the canonical resource is it plus "/mcp".
	PublicURL string
	// SigningKey signs the context cookie and derives the form token. It is
	// the data key, domain-separated; it never leaves this process and never
	// reaches a page.
	SigningKey []byte
	// Authz is the credential layer: it mints, rotates and revokes, and it
	// owns the store this package writes its protocol tables through.
	Authz *authz.Service
	// Clock is the injected clock. Nothing in this package calls time.Now.
	Clock clock.Clock
	// Accounts lists the accounts the authorization screen names under its
	// global-scope disclosure line (spec section 9.4). It is a function
	// rather than a slice because the set changes while the server runs, and
	// a screen that named a stale set would be exactly the dishonesty
	// section 9.7 is trying to avoid.
	Accounts func() []Account
	// Log receives one line per refusal. It never receives a credential.
	Log func(msg string, kv ...any)
}

Config is what a Server needs. Every field is required.

type EnrollmentCode

type EnrollmentCode struct {
	ID            string   `json:"id"`
	Code          string   `json:"code,omitempty"`
	Label         string   `json:"label"`
	Scopes        []string `json:"scopes"`
	ExpiresAt     *string  `json:"expires_at"`
	ConsumedAt    *string  `json:"consumed_at"`
	ConsumedBy    string   `json:"consumed_by,omitempty"`
	RevokedAt     *string  `json:"revoked_at"`
	RevokedReason string   `json:"revoked_reason,omitempty"`
	CreatedAt     *string  `json:"created_at"`
}

EnrollmentCode is one code as the owner sees it. `Code` is populated exactly once, by IssueEnrollmentCode, and is empty on every listing: only the SHA-256 is stored, so there is nothing to show later even if a route wanted to.

type EnrollmentRequest

type EnrollmentRequest struct {
	Label string
	// ExpiresIn is a duration string ("30m") or a number of seconds. Empty
	// means the `oauth.enrollment_default_ttl` setting.
	ExpiresIn string
	// Scopes REPLACES the default ceiling; AllowScopes EXTENDS it. They are
	// mutually exclusive, because a request carrying both is a request whose
	// author did not know which one they meant.
	Scopes      []string
	AllowScopes []string
}

EnrollmentRequest is `POST /v1/admin/enrollment-codes`.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server serves the public OAuth routes of spec section 9.1.

func New

func New(cfg Config) (*Server, error)

New builds the server. It takes no listener and binds nothing: the caller mounts it.

func (*Server) Approve

func (s *Server) Approve(ctx context.Context, id string, scopes []string, source string) (*AuthorizationRequest, *apierr.Error)

Approve is `POST /v1/admin/authorization-requests/{id}/approve`.

The optional `scopes` may only NARROW the browser-selected set. Widening or an empty list is `invalid_request`; a no-longer-pending request is `idempotency_conflict`; an expired one is `invalid_request` (section 9.5).

Narrowing-only matters because the browser-selected set is what the owner saw on the screen next to the disclosure line. An approval that could widen it would grant access the screen never described.

func (*Server) AuthorizationServerDocument

func (s *Server) AuthorizationServerDocument() any

AuthorizationServerDocument is the RFC 8414 document.

`token_endpoint_auth_methods_supported` is `["none"]` and there is no client_secret anywhere in this server: public native clients only (section 9.3).

func (*Server) Deny

func (s *Server) Deny(ctx context.Context, id, reason, source string) (*AuthorizationRequest, *apierr.Error)

Deny is `POST /v1/admin/authorization-requests/{id}/deny`. A denial is a decision the client is entitled to hear, so the waiting page's completion redirects with `error=access_denied` rather than leaving it hanging.

func (*Server) GetAuthorizationRequest

func (s *Server) GetAuthorizationRequest(ctx context.Context, id string) (*AuthorizationRequest, *apierr.Error)

GetAuthorizationRequest shows one request.

func (*Server) GetClient

func (s *Server) GetClient(ctx context.Context, id string) (*Client, *apierr.Error)

GetClient shows one registration.

func (*Server) GetEnrollmentCode

func (s *Server) GetEnrollmentCode(ctx context.Context, id string) (*EnrollmentCode, *apierr.Error)

GetEnrollmentCode shows one code row.

func (*Server) Handles

func (s *Server) Handles(path string) bool

Handles reports whether a path belongs to this server. The `/oauth` prefix is included whether or not the exact path is served, because an unknown path under `/oauth` is this package's 404 to answer (spec section 9.1) and not the REST router's business.

func (*Server) IssueEnrollmentCode

func (s *Server) IssueEnrollmentCode(ctx context.Context, in EnrollmentRequest, source string) (*EnrollmentCode, *apierr.Error)

IssueEnrollmentCode mints a code. `data.code` is the ONLY time the value is returned, and only its SHA-256 is stored (section 9.5).

func (*Server) Issuer

func (s *Server) Issuer() string

Issuer is AGENT_GM_PUBLIC_URL, byte for byte (spec section 9.2).

func (*Server) ListAuthorizationRequests

func (s *Server) ListAuthorizationRequests(ctx context.Context, status string) ([]AuthorizationRequest, *apierr.Error)

ListAuthorizationRequests lists requests, optionally by status.

func (*Server) ListClients

func (s *Server) ListClients(ctx context.Context) ([]Client, *apierr.Error)

ListClients lists every registration.

func (*Server) ListEnrollmentCodes

func (s *Server) ListEnrollmentCodes(ctx context.Context) ([]EnrollmentCode, *apierr.Error)

ListEnrollmentCodes lists every code. No value is in the answer.

func (*Server) Paths

func (s *Server) Paths() []string

Paths reports every path this server serves, which lets the process's own mux ask "is this mine?" without duplicating the table.

func (*Server) ProtectedResourceDocument

func (s *Server) ProtectedResourceDocument() any

ProtectedResourceDocument is the RFC 9728 document, as a value, so that a test can assert its fields without going through HTTP and the MCP layer can point at the same strings.

func (*Server) Register

func (s *Server) Register(ctx context.Context, req registrationRequest, source string) (*registrationResponse, *oauthError)

Register is the registration decision, separated from the transport so a test can drive it directly and so the refusal order is one readable list.

func (*Server) Resource

func (s *Server) Resource() string

Resource is the canonical resource every access token is bound to: the issuer plus "/mcp", with no trailing-slash drift.

func (*Server) RevokeClient

func (s *Server) RevokeClient(ctx context.Context, id, reason, source string) (int, *apierr.Error)

RevokeClient removes a registration and revokes every authorization it holds, returning how many. Removing the registration alone would leave live tokens behind: the grant outlives the client row, so both have to go.

func (*Server) RevokeEnrollmentCode

func (s *Server) RevokeEnrollmentCode(ctx context.Context, id, reason, source string) (bool, *apierr.Error)

RevokeEnrollmentCode revokes one code. Repeating it answers 200 with `revoked: false` (section 9.5), which is why the boolean is the result rather than an error: a second revocation is not a failure, it is a no-longer-necessary act.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP resolves one OAuth route.

The order is the contract of spec section 9.1, and every step of it exists because the HTTP framework's own answer would have been the wrong SHAPE:

  1. a body over 1 MiB is `413` with the `{error, error_description}` body;
  2. a path this server does not serve is the REST `not_found` envelope, because an unknown path is not an OAuth protocol failure;
  3. a wrong method is `405` with the OAuth body AND an `Allow` header;
  4. only then the handler.

func (*Server) SweepExpiredRegistrations

func (s *Server) SweepExpiredRegistrations(ctx context.Context) ([]string, error)

SweepExpiredRegistrations removes expired, never-activated registrations that no authorization request names, auditing each removal (spec section 9.3). The caller runs it every 60 seconds.

It returns the IDs it removed so a caller can log a count without this function knowing what a logger is.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL