auth

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: MIT Imports: 9 Imported by: 0

README

alis-exchange/auth

This module provides packages for handling authentication (AuthN) and authorization (AuthZ) across services. It is designed around a shared auth.Identity model that makes it easy to pass authenticated contexts between clients, HTTP/gRPC middlewares, and authorization checks.

Packages

1. auth (Identity)

The core package that defines auth.Identity. An Identity represents an authenticated user, service account, or system.

Key Features:

  • Stores core user details (ID, Email, Type, Groups, Scopes, Seats).
  • Provides context helpers: FromContext(), Context().
  • Provides gRPC metadata helpers for passing identities between microservices: FromIncomingMetadata(), OutgoingMetadata().
  • JWT parsing: FromJWT() decodes tokens into an Identity.
2. authn (Authentication)

Provides a client for authenticating users via OAuth2/OIDC.

Key Features:

  • Generates authorization URLs (AuthorizeURL).
  • Exchanges authorization codes for tokens (ExchangeCode).
  • Refreshes tokens (Refresh).
  • Validates tokens (ValidateToken, Authenticate) by syncing and verifying against JWKS public keys.

Example Usage:

client := &authn.Client{
    AuthURL:     "...",
    TokenURL:    "...",
    JWKSURL:     "...",
    ID:          "client-id",
    Secret:      "client-secret",
    CallbackURL: "https://yourapp.com/callback",
}

// 1. Redirect user to auth provider
url := client.AuthorizeURL("random-state-string")

// 2. Exchange code for tokens
tokens, err := client.ExchangeCode(code)

// 3. Authenticate to ensure tokens are valid
valid, err := client.Authenticate(tokens, time.Now())
3. authz (Authorization)

Provides an Authorizer to check if a given auth.Identity has the necessary roles to perform an action. It evaluates IAM policies to determine role bindings.

Key Features:

  • Extract roles from an identity's attached IAM policy or explicit Google Cloud IAM policies.
  • Check if an identity has specific roles: HasRole(roles []string, policies ...*iampb.Policy).

Example Usage:

identity := auth.MustFromContext(ctx)
authorizer := authz.MustNew(identity)

// Check if the identity has a required role within the provided policies
hasRole := authorizer.HasRole([]string{"roles/viewer", "roles/editor"}, myPolicy)
if !hasRole {
    return status.Error(codes.PermissionDenied, "unauthorized")
}
4. policypool (Concurrent Policy Fetching)

A utility to fetch Google Cloud IAM policies (*iampb.Policy) concurrently, making authorization checks against multiple resources significantly faster.

Key Features:

  • Built on golang.org/x/sync/errgroup.
  • Fetch from local or remote gRPC methods (AddFromRemoteMethod, AddFromLocalMethod).
  • Wait and collect all policies (WaitPolicies).

Example Usage:

pool := policypool.New()

// Add concurrent policy fetch requests
pool.AddFromRemoteMethod(ctx, remoteClient.GetIamPolicy, "resources/A")
pool.AddFromRemoteMethod(ctx, remoteClient.GetIamPolicy, "resources/B")

// Block and retrieve all policies
policies, err := pool.WaitPolicies()
if err != nil {
    return err
}

// Pass policies to authorizer
authorizer.HasRole([]string{"roles/admin"}, policies...)

Documentation

Overview

Package auth provides an identity which is shared by the authn and authz packages.

Index

Constants

This section is empty.

Variables

View Source
var SystemIdentity = &Identity{
	Type: System,
	ID:   "system",
}

Functions

func AddSystemEmail

func AddSystemEmail(email string)

Types

type Identity

type Identity struct {
	Type     Type              // Type of the identity
	ID       string            `json:"sub"`      // E.g. "1934872948" or "alis-build@my-project.iam.gserviceaccount.com"
	Email    string            `json:"email"`    // E.g. "john@example.com" or "alis-build@myproject.iam.gserviceaccount.com"
	Accounts map[string]*Seats `json:"accounts"` // User's seats in their accounts
	GroupIDs []string          `json:"groups"`   // IDs of the groups the user belongs to
	Policy   string            `json:"policy"`   // Base64 encoded iam policy
	Exp      int64             `json:"exp"`      // Expiration time in seconds since epoch. Only used for validating tokens.
	App      string            `json:"app"`      // Client ID (if any) of the registered third party app.
	Scopes   []string          `json:"scopes"`   // Set of scopes that the third party app has been granted.
}

func FromContext

func FromContext(ctx context.Context) (*Identity, error)

FromContext returns the Identity inside the given ctx, if any.

func FromIncomingMetadata

func FromIncomingMetadata(ctx context.Context) (*Identity, error)

FromIncomingMetadata returns the Identity inside the given gRPC context, if any.

func FromJWT

func FromJWT(jwt string) (*Identity, error)

FromJWT decodes and unmarshals the given jwt into an Identity.

func MustFromContext

func MustFromContext(ctx context.Context) *Identity

MustFromContext does the same as FromContext, but panics on an error.

func MustFromIncomingMetadata

func MustFromIncomingMetadata(ctx context.Context) *Identity

MustFromIncomingMetadata does the same as FromIncomingMetadata, but panics on an error.

func MustFromJWT

func MustFromJWT(jwt string) *Identity

MustFromJWT does the same as FromJWT, but panics on an error.

func MustUnmarshal

func MustUnmarshal(data []byte) *Identity

MustUnmarshal does the same as Unmarshal, but panics on an error.

func Unmarshal

func Unmarshal(data []byte) (*Identity, error)

Unmarshal returns the identity represented by the bytes.

func (*Identity) Context

func (i *Identity) Context(ctx context.Context) context.Context

Context returns a derived context with the identity value in it to use locally. Use OutgoingMetadata if you want remote services to identify the requester. You can use Context and OutgoingMetadata together.

func (*Identity) IsSystem

func (i *Identity) IsSystem() bool

func (*Identity) Marshal

func (i *Identity) Marshal() []byte

Marshal returns the bytes representation of the identity.

func (*Identity) OutgoingMetadata

func (i *Identity) OutgoingMetadata(ctx context.Context) context.Context

OutgoingMetadata returns a derived context with the identity value in it. Enables downstream gRPC services in the same environment to identify the requester.

func (*Identity) PolicyMember

func (i *Identity) PolicyMember() string

PolicyMember returns the member to use in iam policy bindings. E.g. "user:1234129384" or "serviceAccount:alis-build@myproject.iam.gserviceaccount.com"

type Seat

type Seat struct {
	Plan int32
	Seat int32
}

type Seats

type Seats map[string]*Seat

type Type

type Type string
const (
	User           Type = "user"
	ServiceAccount Type = "serviceAccount"
	System         Type = "system" // can do everything

)

Directories

Path Synopsis
Package authn is used to identify requesters
Package authn is used to identify requesters
Package authz is used to authorize whether an identity has the required role.
Package authz is used to authorize whether an identity has the required role.
Package policypool provides a Pooler which can fetch policies async.
Package policypool provides a Pooler which can fetch policies async.

Jump to

Keyboard shortcuts

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