auth

package
v1.0.0-alpha1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 21 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 auth resolves bearer tokens into principals and enforces the authority checks that Spring expressed as @PreAuthorize.

Index

Constants

View Source
const CurrentUserPath = "/api/v1/users/me"

CurrentUserPath is the one route an account that is not active may call.

View Source
const DashboardCallbackPath = "/dashboard/login/callback/"

DashboardCallbackPath is the only redirect URI path the exchange accepts: the dashboard's sign-in callback page.

View Source
const RootUsername = "root"

RootUsername is the principal name the bootstrap account authenticates as. Note that it is also the user id ownership checks compare against, so acting on owned resources as root requires a users row with this id.

View Source
const ServiceAccountAuthority = role.User

ServiceAccountAuthority is the only authority a service account ever holds.

It is fixed here rather than looked up, so no row in user_roles — however it got there — can make a service account an administrator.

View Source
const ServiceAccountIDPrefix = "sa:"

ServiceAccountIDPrefix namespaces service account user ids. Every service account is a users row whose id is this prefix followed by the account's name, so a service account can own resources, be shared with and join groups exactly as a person does, and its id can never collide with a CILogon subject.

View Source
const ServiceAccountTokenPrefix = "airavata_sa_"

ServiceAccountTokenPrefix marks a bearer token as a service account token.

The prefix is what lets the introspector route the token to the local database instead of CILogon: an Airavata-issued secret must never be sent to a third party's introspection endpoint. It also makes a leaked token recognisable to secret scanners.

View Source
const StatusActive = "ACTIVE"

StatusActive is the user status that may use Airavata.

View Source
const WebSocketProtocol = "airavata.v1"

WebSocketProtocol is the subprotocol a browser offers alongside its token, and the one a websocket handler must accept: a browser fails the upgrade when it offered subprotocols and the server selected none.

Variables

View Source
var ErrInvalidToken = fmt.Errorf("invalid bearer token")

ErrInvalidToken reports a token that introspection rejected.

View Source
var SignInScopes = []string{"openid", "email", "profile", "org.cilogon.userinfo", "offline_access"}

SignInScopes are the scopes the dashboard asks CILogon for: the profile claims the introspector reads, and offline_access for a refresh token, since CILogon access tokens are short-lived.

Functions

func GenerateServiceAccountToken

func GenerateServiceAccountToken() (token, hash string, err error)

GenerateServiceAccountToken returns a new random token and the digest to store for it. The token itself is never persisted; it is shown to the caller once.

func HashServiceAccountToken

func HashServiceAccountToken(token string) string

HashServiceAccountToken returns the hex SHA-256 digest a token is stored and looked up by.

func IsServiceAccountID

func IsServiceAccountID(userID string) bool

IsServiceAccountID reports whether a user id names a service account.

func IsServiceAccountToken

func IsServiceAccountToken(token string) bool

IsServiceAccountToken reports whether token is shaped like a service account token.

func Middleware

func Middleware(introspector Introspector, opts ...Option) func(http.Handler) http.Handler

Middleware resolves the bearer token, if any, onto the request context.

It deliberately does not reject anonymous requests. The Java filter chain permits every request and leaves enforcement to the method-level guards, so an endpoint with no authority requirement stays reachable without a token. What it does reject is a token that is present but unusable: a caller who supplies a bad token gets 401 rather than being silently downgraded to anonymous, which would otherwise turn a typo'd token into a confusing 403 further down.

func NormalizeUsername

func NormalizeUsername(username string) string

NormalizeUsername reduces a CILogon identifier to the form stored as iam/model.User.ID.

CILogon sometimes reports usernames as full URIs like "http://cilogon.org/serverE/users/12345"; those collapse to "cilogon:12345" so that a user is looked up the same way no matter which claim carried the identity.

func WithPrincipal

func WithPrincipal(ctx context.Context, p *Principal) context.Context

WithPrincipal returns a context carrying p.

Types

type CILogonIntrospector

type CILogonIntrospector struct {
	HTTPClient       *http.Client
	IntrospectionURI string
	UserInfoURI      string
	ClientID         string
	ClientSecret     string
	Roles            RoleLookup

	// Root, when set, short-circuits introspection for the bootstrap token.
	Root *RootTokenProvider

	// ServiceAccounts, when set, resolves service account tokens locally. A token
	// carrying the service account prefix is never forwarded to CILogon, whether or
	// not this is set.
	ServiceAccounts ServiceAccountResolver

	// Users, when set, gives every CILogon principal a user record the first time it
	// authenticates, and sets the principal's Status from it. The root account and
	// service accounts never reach it.
	Users UserProvisioner
}

CILogonIntrospector validates tokens against CILogon.

CILogon access tokens for standard OAuth clients are opaque strings rather than self-contained JWTs, so they cannot be verified locally against a JWK set — each one is checked by calling CILogon's RFC 7662 introspection endpoint. Introspection returns only a small fixed claim set, so profile attributes come from a second call to userinfo with the same token.

func NewCILogonIntrospector

func NewCILogonIntrospector(introspectionURI, userInfoURI, clientID, clientSecret string, roles RoleLookup, root *RootTokenProvider) *CILogonIntrospector

NewCILogonIntrospector builds an introspector with a bounded HTTP client, so a hanging identity provider cannot pin request goroutines indefinitely.

func (*CILogonIntrospector) Introspect

func (c *CILogonIntrospector) Introspect(ctx context.Context, token string) (*Principal, error)

Introspect implements Introspector.

type Introspector

type Introspector interface {
	Introspect(ctx context.Context, token string) (*Principal, error)
}

Introspector validates a bearer token and resolves it to a principal.

type MockRoleLookup

type MockRoleLookup struct{}

MockRoleLookup is the hardcoded stand-in carried over from the Java service: two fixed usernames are admins and everyone else is a plain user.

It is a placeholder. iam/repository.DBRoleLookup reads the user_roles table the schema already provides and should replace this once roles are actually administered.

func (MockRoleLookup) Roles

func (MockRoleLookup) Roles(_ context.Context, username string) []string

Roles implements RoleLookup.

type Option

type Option func(*middlewareConfig)

Option configures Middleware.

func WithPermissions

func WithPermissions(r PermissionResolver) Option

WithPermissions makes Middleware resolve each authenticated principal's permissions onto the principal, so the guards below can answer from it. Without it, no principal holds any permission.

type PermissionResolver

type PermissionResolver interface {
	Permissions(ctx context.Context, name string, authorities []string) permission.Set
}

PermissionResolver turns a caller into the permissions they hold: what their authorities (role names) grant, or for a service account what has been granted to that account itself.

An implementation must not fail open. When it cannot tell what a role grants it returns fewer permissions, never more, so a fault in the lookup denies rather than allows.

type Principal

type Principal struct {
	Name        string
	Authorities []string
	Attributes  map[string]any

	// Permissions is what Authorities grant, resolved by Middleware once per request.
	// An introspector never sets it: like the authorities, it is looked up server-side
	// rather than read from the token. It is empty for a principal that did not come
	// through Middleware, which therefore holds no permission.
	Permissions permission.Set

	// Status is the user record's status for a CILogon principal, and empty for the
	// root account and service accounts, whose standing is decided elsewhere.
	Status string
}

Principal is the authenticated caller.

Name is the identity every service compares ownership against, and it is expected to equal iam/model.User.ID: CILogon subjects normalised to "cilogon:12345", or "root" for the bootstrap account.

Authorities are bare role names — "ADMIN", "SUPER_ADMIN", "USER" — with no "ROLE_" prefix, matching the Java expressions exactly.

func FromContext

func FromContext(ctx context.Context) *Principal

FromContext returns the principal on ctx, or nil when the caller is anonymous.

func RequireAnyAuthority

func RequireAnyAuthority(ctx context.Context, want ...string) (*Principal, error)

RequireAnyAuthority is the @PreAuthorize("hasAnyAuthority(...)") guard. An authenticated caller holding none of want gets 403.

func RequireAuthenticated

func RequireAuthenticated(ctx context.Context) (*Principal, error)

RequireAuthenticated is the @PreAuthorize("isAuthenticated()") guard.

An anonymous caller gets 401 rather than 403: Spring's ExceptionTranslationFilter sends anonymous principals to the authentication entry point, because presenting a token is something the caller can actually do about it.

func RequirePermission

func RequirePermission(ctx context.Context, perm permission.Permission) (*Principal, error)

RequirePermission is the guard for an action gated by a permission. Handlers and services use it instead of naming the roles that happen to grant the permission.

An anonymous caller gets 401 and an authenticated one without the permission gets 403, as RequireAnyAuthority does.

func RequireSelfOrPermission

func RequireSelfOrPermission(ctx context.Context, ownerID string, perm permission.Permission, message string) (*Principal, error)

RequireSelfOrPermission allows the record's owner, or any caller holding perm. It is the imperative check the user service uses where an annotation cannot see the owner. The message is caller-supplied because each service phrases its own.

func ServiceAccountPrincipal

func ServiceAccountPrincipal(userID string) *Principal

ServiceAccountPrincipal builds the principal a service account authenticates as. Its authorities are always exactly USER.

func (*Principal) Active

func (p *Principal) Active() bool

Active reports whether the principal may use Airavata. A CILogon user starts out SUSPENDED and is let in once an administrator makes them ACTIVE.

func (*Principal) Can

func (p *Principal) Can(perm permission.Permission) bool

Can reports whether the principal holds permission p. A nil principal, an anonymous caller, holds none.

func (*Principal) HasAnyAuthority

func (p *Principal) HasAnyAuthority(want ...string) bool

HasAnyAuthority reports whether the principal holds at least one of want.

func (*Principal) IsAdmin

func (p *Principal) IsAdmin() bool

IsAdmin reports whether the principal holds ADMIN or SUPER_ADMIN, the pairing every administrative check in the Java services uses.

func (*Principal) IsServiceAccount

func (p *Principal) IsServiceAccount() bool

IsServiceAccount reports whether the principal is a service account.

type RoleLookup

type RoleLookup interface {
	Roles(ctx context.Context, username string) []string
}

RoleLookup resolves the authorities granted to an authenticated username.

Authorities are looked up here rather than read out of the token, so a token cannot assert its own privileges.

type RootTokenProvider

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

RootTokenProvider holds the bootstrap Super Admin token.

It exists so a fresh deployment has some way in before any real identity provider is wired up. It is meant for initial setup and testing; production deployments should disable it and authenticate through CILogon.

func NewRootTokenProvider

func NewRootTokenProvider(configured string) *RootTokenProvider

NewRootTokenProvider returns a provider using configured, or a fresh random token when configured is empty.

func (*RootTokenProvider) Banner

func (p *RootTokenProvider) Banner() string

Banner is the startup notice announcing the token, matching the Java service's behaviour of printing it where an operator will see it.

func (*RootTokenProvider) Matches

func (p *RootTokenProvider) Matches(token string) bool

Matches reports whether token is the root token, comparing in constant time so the token cannot be recovered by timing repeated guesses.

func (*RootTokenProvider) Principal

func (p *RootTokenProvider) Principal() *Principal

Principal returns the Super Admin principal the root token authenticates as.

func (*RootTokenProvider) Token

func (p *RootTokenProvider) Token() string

Token returns the active root token.

type ServiceAccountResolver

type ServiceAccountResolver interface {
	ResolveServiceAccount(ctx context.Context, token string) (*Principal, error)
}

ServiceAccountResolver resolves a service account token to its principal.

It returns ErrInvalidToken for a token that is unknown, expired, or belongs to an account that is not active, and any other error when the lookup itself failed.

type SignIn

type SignIn struct {
	Issuer       string
	ClientID     string
	ClientSecret string
	HTTPClient   *http.Client
	// contains filtered or unexported fields
}

SignIn lets a browser sign in with CILogon through the authorization code flow with PKCE. The browser sends the user to CILogon itself; this server performs the code exchange and refreshes, because they need the client secret, which never leaves it, and because CILogon's token endpoint does not answer browsers.

The client is the same one introspection uses, so the access tokens it returns are ones the introspector accepts. Its redirect URIs, registered with CILogon, must include <dashboard origin>/dashboard/login/callback/.

func NewSignIn

func NewSignIn(issuer, clientID, clientSecret string) *SignIn

NewSignIn returns the sign-in routes for a CILogon client.

func (*SignIn) Enabled

func (s *SignIn) Enabled() bool

Enabled reports whether a client is configured to sign in with.

func (*SignIn) Register

func (s *SignIn) Register(mux *http.ServeMux)

Register mounts the sign-in routes. They take no bearer token.

type SignInConfig

type SignInConfig struct {
	Enabled               bool   `json:"enabled"`
	AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`
	ClientID              string `json:"clientId,omitempty"`
	Scope                 string `json:"scope,omitempty"`
}

SignInConfig is what the browser needs to send a user to CILogon.

type SignInTokens

type SignInTokens struct {
	AccessToken  string `json:"accessToken"`
	RefreshToken string `json:"refreshToken,omitempty"`
	ExpiresIn    int64  `json:"expiresIn,omitempty"`
}

SignInTokens is the outcome of an exchange or refresh. ExpiresIn is in seconds; 0 when CILogon did not say.

type UserProvisioner

type UserProvisioner interface {
	ProvisionUser(ctx context.Context, p *Principal) (status string, err error)
}

UserProvisioner resolves a CILogon principal to its user record, creating one the first time the principal is seen, and reports the record's status.

Jump to

Keyboard shortcuts

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