authgate

package
v0.15.2 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 35 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 authgate asks every caller of an agni server for a token (agni issues 1627 and 1765). agni serve and agnids both use it, over the tokens `agni token create` keeps in the shared --store.

Index

Constants

View Source
const (
	// ClaimOIDCGroup prefixes a value of the OIDC groups claim, as --oidc-allow group: reads it.
	ClaimOIDCGroup = "oidc:group:"
	// ClaimGitHubOrg prefixes a GitHub org the person was a member of at sign-in, as
	// --github-allow org: checks it.
	ClaimGitHubOrg = "github:org:"
)

A token minted at sign-in carries claims the sign-in saw, kept in the token's scopes, so an operator's grant can follow a group rather than a list of people (agni issue 1896). Each claim starts with a prefix no subject can equal. A subject is "oidc:<sub>" or "github:<login>", and a GitHub login holds no ':'. An OIDC sub could, but the identity provider issues both the sub and the groups, so it could admit anyone to a group anyway.

View Source
const (
	AnyDevicePath      = "/signin/device"
	AnyDeviceTokenPath = "/signin/device/token" // #nosec G101 -- a URL path, not a credential
)

AnyDevicePath and AnyDeviceTokenPath run the device flow of the server's only sign-in provider, so `agni login` needs no --with when the server offers one (agni issue 1811).

View Source
const (
	DevicePath      = githubDevice
	DeviceTokenPath = githubDeviceToken
)

DevicePath and DeviceTokenPath are where `agni login` starts and finishes GitHub's device flow.

View Source
const AccountsDir = "accounts"

AccountsDir holds the server's local accounts under a file:// --store, each as a bcrypt hash of its password and never the password itself.

View Source
const BrandLogoPath = "/brand/logo"

BrandLogoPath is where a server serves the logo a Brand names by file. The gate lets anyone fetch it, since the sign-in page shows it before anyone has signed in.

View Source
const LocalSignInPath = "/signin/local"

LocalSignInPath is where the sign-in page posts a local username and password (agni issue 1815).

View Source
const OIDCSignInPath = "/signin/oidc"

OIDCSignInPath is where a browser signs in through the OpenID Connect provider (agni issue 1811).

View Source
const SessionCookie = "agni_session"

SessionCookie carries a browser's token once it signs in at /signin, since a page can't send an Authorization header.

View Source
const SignInPath = "/signin/github"

SignInPath is where a browser signs in with GitHub, on a gate that has one (agni issue 1772). A page links here with ?next= naming where to land after.

View Source
const StoreDir = "tokens"

StoreDir holds the server's tokens under --store, each as a bcrypt hash and never the token itself.

View Source
const Tokens = "tokens"

Tokens is --auth's one value today: callers present a token `agni token create` made (agni issue 1627). An identity provider joins it with agni issue 1176.

Variables

View Source
var CacheTTL = time.Minute

CacheTTL is how long the server trusts a token it has checked before checking it again. A revoked token keeps working for up to this long, since `agni token revoke` runs in another process and can't clear the server's cache.

View Source
var ErrNoSuchUser = errors.New("no such user")

ErrNoSuchUser is what SetPassword returns for a name with no account.

View Source
var ErrUserExists = errors.New("that user already exists")

ErrUserExists is what AddUser returns for a name that already has an account.

Functions

func AddUser added in v0.11.5

func AddUser(ctx context.Context, store Accounts, name, password string) (string, error)

AddUser makes a local account for name with password, and returns the canonical username. It returns ErrUserExists for a name that has one, and refuses a password shorter than 8 characters. The check and the write are two steps, so two operators adding one name at once can both succeed, and the second password wins.

func CanonicalUsername added in v0.11.5

func CanonicalUsername(name string) (string, error)

CanonicalUsername lowercases name and checks it against oneauth's username pattern, 3 to 20 letters, digits, dashes or underscores. A username is case-insensitive, so "Alice" and "alice" name one account, and the lowercased form is the one stored and the one in the subject.

func CheckFlags

func CheckFlags(auth, store, tlsCert, tlsKey, addr string, proxies skmw.TrustedProxies) error

CheckFlags refuses a combination of --auth and the TLS flags that would serve tokens badly. A server with trusted proxies may serve plain HTTP on any address, since the proxies end TLS in front of it (agni issue 1810).

func Claims added in v0.11.9

func Claims(scopes []string) []string

Claims keeps the scopes of a request's token that are claims a sign-in recorded, and drops anything else, such as an OAuth scope on a token some other path minted.

func GitHubEndpoint added in v0.10.0

func GitHubEndpoint(api string) oauth2.Endpoint

GitHubEndpoint is the OAuth endpoint that signs people in for the GitHub REST API at api, the server's --github-api. goapplib refreshes a signed-in person's token through it too.

func GrantOrgs added in v0.11.9

func GrantOrgs(patterns []string) []string

GrantOrgs returns the orgs a GitHub sign-in checks membership of for grants, one per "github:org:<org>" pattern in patterns. A pattern ending in '*' names no one org, so it is left out, and it admits nobody.

func List

func List(ctx context.Context, store Keys) ([]*core.APIKey, error)

List returns every token in the store, newest first, without their hashes.

func ParseOIDCAllow added in v0.11.0

func ParseOIDCAllow(allow []string) (oidc.AllowList, error)

ParseOIDCAllow reads --oidc-allow values into an allow list. Each is domain:, group:, sub: or hd: followed by a value, and an empty list is an error.

func ParseProxies added in v0.11.0

func ParseProxies(entries []string) (skmw.TrustedProxies, error)

ParseProxies reads --trusted-proxy, each an address or a CIDR range such as 10.0.0.0/8. servicekit's middleware owns the type, so every service on servicekit reads forwarding headers the same way (panyam/servicekit#67).

func Prune added in v0.10.0

func Prune(ctx context.Context, store Keys, now time.Time) (int, error)

Prune deletes the tokens whose expiry is at or before now, and returns how many it deleted (agni issue 1778). Each GitHub sign-in mints a token that expires, so without this the store keeps one record per sign-in for good. A token with no expiry, as `agni token create` makes, stays, and so does a revoked one, which `agni token ls` still lists.

func RemoveUser added in v0.11.5

func RemoveUser(ctx context.Context, store Accounts, name string) (bool, error)

RemoveUser deletes name's account, and reports whether it had one. Removing a name with no account is false and no error. A token minted at an earlier sign-in keeps working until it expires or `agni token revoke` revokes it.

func SetPassword added in v0.11.5

func SetPassword(ctx context.Context, store Accounts, name, password string) (string, error)

SetPassword replaces name's password. It returns ErrNoSuchUser for a name with no account. A token minted at an earlier sign-in keeps working until it expires or is revoked.

Types

type Accounts added in v0.11.5

type Accounts interface {
	accounts.ChannelStore
	accounts.ChannelAdmin
}

Accounts is the store of the server's local accounts: oneauth's channel store, with the listing and the delete of its ChannelAdmin that ListUsers and RemoveUser use (panyam/oneauth#574). Each account is one channel with provider "local" and identity key "username:<name>", holding a bcrypt hash of its password.

func AccountsStore added in v0.11.5

func AccountsStore(storeDir string) Accounts

AccountsStore is the store of the server's local accounts, as files under the --store folder.

func GAEAccounts added in v0.11.5

func GAEAccounts(client *datastore.Client, namespace string) Accounts

GAEAccounts is the store of the server's local accounts in Datastore, in namespace.

func SQLAccounts added in v0.11.5

func SQLAccounts(db *gorm.DB) (Accounts, error)

SQLAccounts is the store of the server's local accounts in db, creating oneauth's channels table if absent.

type Brand added in v0.13.0

type Brand struct {

Brand is what a deployment calls its server on the sign-in page (agni issue 1986). Name replaces "Agni", Logo is the URL of an image shown above the heading, and Note is one line of text under it, such as whose server this is. The zero value is agni's own page.

type DeviceStart added in v0.10.0

type DeviceStart struct {
	UserCode        string `json:"user_code"`
	VerificationURI string `json:"verification_uri"`
	Interval        int    `json:"interval"`
	ExpiresIn       int    `json:"expires_in"`
	Handle          string `json:"handle"`
}

DeviceStart is the server's answer to a POST to DevicePath. The person opens VerificationURI and types UserCode. The CLI then posts Handle to DeviceTokenPath until the server answers with a token.

type DeviceToken added in v0.10.0

type DeviceToken struct {
	Pending bool   `json:"pending,omitempty"`
	Token   string `json:"token,omitempty"`
	Subject string `json:"subject,omitempty"`
}

DeviceToken is the server's answer to a POST to DeviceTokenPath. Pending says GitHub is still waiting for the person. Otherwise Token is the agni token minted for Subject.

func DeviceLogin added in v0.10.0

func DeviceLogin(ctx context.Context, server, with string, show func(DeviceStart)) (DeviceToken, error)

DeviceLogin signs in to the agni server at server through a provider's device flow, which the server runs (agni issues 1772, 1811). with is "github", "oidc", or empty for the server's only provider. It calls show with the code the person types at the provider, then waits until the server answers with a token, the code expires, or ctx ends.

type Gate

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

Gate refuses every request without a valid token, apart from the health check, the viewer's static assets, the sign-in pages, GitHub's push webhook and Graph's notifications. It puts the token's subject in the request's context as a service.Caller.

func New

func New(store core.APIKeyStore, proxies skmw.TrustedProxies) *Gate

New checks tokens against store. proxies are the proxies that end TLS in front of the server, as ParseProxies reads them from --trusted-proxy. Empty trusts no forwarded header, so a cookie is Secure only on a request the server took over TLS itself.

func (*Gate) WithBrand added in v0.13.0

func (g *Gate) WithBrand(b Brand) *Gate

WithBrand shows b on the sign-in page, and returns g.

func (*Gate) WithGitHub added in v0.10.0

func (g *Gate) WithGitHub(cfg GitHub) (*Gate, error)

WithGitHub lets people sign in through cfg's GitHub App, and returns g. It refuses a cfg with no client, no PublicURL or an empty Allow.

func (*Gate) WithLocalAccounts added in v0.11.5

func (g *Gate) WithLocalAccounts(cfg LocalAccounts) (*Gate, error)

WithLocalAccounts lets people sign in with a local username and password, and returns g. It refuses a cfg with no Store.

func (*Gate) WithOIDC added in v0.11.0

func (g *Gate) WithOIDC(ctx context.Context, cfg OIDC) (*Gate, error)

WithOIDC lets people sign in through cfg's provider, and returns g. It reads the provider's discovery document now, and refuses a cfg with no client, no PublicURL or an empty Allow.

func (*Gate) WithOwnAuth added in v0.11.10

func (g *Gate) WithOwnAuth(prefixes ...string) *Gate

WithOwnAuth passes every request under each prefix to the wrapped handler unchecked, and copies no session cookie into its Authorization header. Use it only for a handler that refuses a request without a credential of its own. The viewer rooms' relay is one: it admits a page by the relay token that ViewerRoomService minted, and that service sits behind the gate. The relay reads an Authorization header before its own token, so the copied session cookie would replace the relay token and the relay would refuse every signed-in tab.

func (*Gate) Wrap

func (g *Gate) Wrap(next http.Handler) http.Handler

Wrap guards next.

type GitHub added in v0.10.0

type GitHub struct {
	// ClientID and ClientSecret are the GitHub App's OAuth client.
	ClientID, ClientSecret string
	// API is the GitHub REST API the server reads through, the server's --github-api. Empty is
	// api.github.com, and sign-in goes through github.com.
	API string
	// PublicURL is the server's URL as a browser reaches it, such as https://agni.example.com.
	// GitHub sends the browser back to PublicURL + /signin/github/callback/.
	PublicURL string
	// Allow names who may sign in, each "org:<org>" for the members of an org or "user:<login>".
	// It can't be empty, since anyone with a GitHub account could sign in otherwise.
	Allow []string
	// Save keeps the GitHub token of the person signed in as login, as subject's own connection.
	Save func(ctx context.Context, subject, login string, tok *oauth2.Token) error
	// GrantOrgs are the orgs an operator's grants name as github:org:<org> (agni issue 1896). Sign-in
	// checks the person's membership of each, beside Allow's, and the token carries each org they
	// are in as a claim.
	GrantOrgs []string
	// TTL is how long a minted agni token works. Zero is 30 days.
	TTL time.Duration
	// HTTPClient makes the calls to GitHub. Nil is http.DefaultClient.
	HTTPClient *http.Client
}

GitHub signs people in through a GitHub App (agni issue 1772). A browser signs in at /signin/github, through GitHub's web flow, and `agni login` through its device flow. Either way the server checks the person against Allow, mints them an agni token for the subject "github:<login>", and hands their GitHub token to Save, which keeps it as their own connection.

type Keys added in v0.11.0

type Keys interface {
	core.APIKeyStore
	core.APIKeyAdmin
}

Keys is the store of the server's tokens: oneauth's API key store, with the listing and the expiry sweep of its APIKeyAdmin that List and Prune use (agni issue 1733, panyam/oneauth#549). Store keeps them as files under a --store folder, SQLStore as rows of a sqlite or postgres database, and GAEStore as Datastore entities.

func GAEStore added in v0.11.0

func GAEStore(client *datastore.Client, namespace string) Keys

GAEStore is the store of the server's tokens in Datastore, in namespace.

func SQLStore added in v0.11.0

func SQLStore(db *gorm.DB) (Keys, error)

SQLStore is the store of the server's tokens in db, creating oneauth's api_keys table if absent.

func Store

func Store(storeDir string) Keys

Store is the store of the server's tokens, inside the --store folder.

type LocalAccounts added in v0.11.5

type LocalAccounts struct {
	// Store holds the accounts, in the server's --store.
	Store Accounts
	// TTL is how long a minted agni token works. Zero is 30 days.
	TTL time.Duration
	// PerUser and PerAddress limit sign-in attempts for one username and from one client address.
	// Nil allows 5 attempts per username and 20 per address in a burst, each refilling one a minute
	// and one every 6 seconds. The address is the client's as the trusted proxies report it.
	PerUser, PerAddress core.RateLimiter
}

LocalAccounts signs people in with a username and password an operator made with `agni users add` (agni issue 1815). A good sign-in mints an agni token for the subject "local:<username>", the same kind of token a GitHub or OIDC sign-in mints. There is no self-signup.

type LocalLogin added in v0.11.6

type LocalLogin struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

LocalLogin is the JSON body `agni login --with local` posts to LocalSignInPath, sent with the Content-Type application/json (agni issue 1879). The sign-in page posts a form instead.

type LocalLoginError added in v0.11.6

type LocalLoginError struct {
	Error string `json:"error"`
}

LocalLoginError answers a refused JSON sign-in at LocalSignInPath. A bad username or password gets a 401, too many attempts get a 429, and a body that isn't a LocalLogin gets a 400.

type LocalToken added in v0.11.6

type LocalToken struct {
	Token   string    `json:"token"`
	Subject string    `json:"subject"`
	Expires time.Time `json:"expires"`
}

LocalToken answers a good JSON sign-in at LocalSignInPath. Token is an agni token for Subject, which is "local:<username>". The token works until Expires. A JSON sign-in sets no cookie.

func PasswordLogin added in v0.11.6

func PasswordLogin(ctx context.Context, server, name, password string) (LocalToken, error)

PasswordLogin signs in to the agni server at server as the local account name, posting a LocalLogin as JSON to LocalSignInPath (agni issue 1879). It returns the token the server mints. A refusal is an error carrying the server's message, and a server without local accounts is an error saying so.

type OIDC added in v0.11.0

type OIDC struct {
	// Issuer is the provider's issuer URL. The server reads <Issuer>/.well-known/openid-configuration
	// at start, so a wrong issuer fails the start, not the first sign-in.
	Issuer string
	// ClientID and ClientSecret are the client registered with the provider. ClientSecret may be empty
	// for a public client.
	ClientID, ClientSecret string
	// PublicURL is the server's URL as a browser reaches it. The provider sends the browser back to
	// PublicURL + /signin/oidc/callback/, which the client registration must list.
	PublicURL string
	// Allow names who may sign in: "domain:<domain>" for a verified email in a domain, "group:<id>" for
	// a value in the groups claim, "sub:<sub>" for one person, "hd:<domain>" for a Google Workspace
	// domain. It can't be empty, since anyone the provider knows could sign in otherwise. An email is
	// verified when the token's email_verified is true, or Entra ID's optional xms_edov claim is.
	Allow []string
	// AllowUnverifiedEmail lets a domain: rule admit an email the provider did not verify (agni issue
	// 1992). It is safe only with a single-tenant issuer, where the tenant controls every address in
	// its domains. On Entra ID, adding the xms_edov optional claim is the narrower fix.
	AllowUnverifiedEmail bool
	// Label names the provider on the sign-in page's button. Empty is "single sign-on".
	Label string
	// TTL is how long a minted agni token works. Zero is 30 days.
	TTL time.Duration
	// HTTPClient makes the discovery, key, token and device requests. Nil uses oneauth's default.
	HTTPClient *http.Client
}

OIDC signs people in through any OpenID Connect provider, such as Entra ID, Okta, Google Workspace or Keycloak (agni issue 1811). A browser signs in at /signin/oidc and `agni login --with oidc` through the provider's device flow. Either way the server checks the verified ID token's claims against Allow and mints an agni token for the subject "oidc:<sub>". It keeps no connection, so a person who also needs private repos adds their own with `agni connections add --mine`.

type User added in v0.11.5

type User struct {
	Name      string
	CreatedAt time.Time
}

User is one local account as ListUsers shows it, with no password hash.

func ListUsers added in v0.11.5

func ListUsers(ctx context.Context, store Accounts) ([]User, error)

ListUsers returns every local account, sorted by name.

Jump to

Keyboard shortcuts

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