gate

package
v1.0.0-dev.17 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package gate guards an app's own routes with an access.Authenticator: one table of rows, each with its class, and one handler per row. It answers every refusal through the app's access.ErrorWriter with the codes and challenge the auth tree uses, and imports nothing of the sign-in packages.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Codes

func Codes(r Route) []access.Code

Codes is every code route r can answer, in access.Codes() order.

func MountCodes

func MountCodes() []access.Code

MountCodes is every code the gate answers outside any row: a request that matches no row. An app's error union is every row's Codes and these.

func Principal

func Principal(ctx context.Context) (access.Principal, bool)

Principal is the principal the gate admitted r's route for; false on a Public route.

Types

type Class

type Class int

Class is what a row admits.

const (
	Public  Class = iota + 1 // nothing is read: no principal, no refusal
	Session                  // a full session only
	Key                      // an API key only; with a Scope, Allow decides it too
	Scoped                   // Allow decides, for every principal
)

The classes.

type Config

type Config struct {
	Authenticator *access.Authenticator // required; supplies the realm
	Errors        access.ErrorWriter    // required; the same writer as the auth tree
	// Allow decides a Scoped row, and a Key row with a Scope. Nil is
	// p.IsSession() || (p.IsAPIKey() && p.HasScope(scope)).
	Allow func(p access.Principal, scope string) bool
	// Audit receives one event for each refusal of a presented credential,
	// synchronously, before Errors runs: gate.failure for a 401 and
	// gate.forbidden for a 403. A request with no credential, a 503 and
	// auth_https_required, which refuses the transport, send none. Nil is
	// none.
	Audit func(r *http.Request, e access.AuditEvent)
	// Logger receives the gate's log lines; nil is slog.Default() at each
	// call.
	Logger *slog.Logger
}

Config configures a Gate.

type Gate

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

Gate serves exactly the rows it was built with. Build it with New.

func New

func New(cfg Config, routes []Route, handlers map[string]http.Handler) (*Gate, error)

New builds the gate over the app's endpoint table and one handler per row, by Name. It returns an error, never panics, for: a nil Authenticator or Errors; a duplicate Name; a Method or Path outside Route's rules; two rows with one method and path; paths net/http.ServeMux would refuse to register together; a Scope on the wrong class or outside the scope-token charset; Passive or HTTPS on Public; a row with no handler; and a handler with no row.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"

	"github.com/cplieger/access"
	"github.com/cplieger/access/accesstest"
	"github.com/cplieger/access/gate"
)

func main() {
	authn, err := access.New(accesstest.NewMemStore(), access.Config{})
	if err != nil {
		log.Fatal(err)
	}
	writeError := func(w http.ResponseWriter, _ *http.Request, e access.Error) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(e.Status)
		_ = json.NewEncoder(w).Encode(map[string]string{"code": string(e.Code)})
	}
	g, err := gate.New(gate.Config{Authenticator: authn, Errors: writeError},
		[]gate.Route{{Name: "me", Method: http.MethodGet, Path: "/api/me", Class: gate.Session}},
		map[string]http.Handler{"me": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			p, _ := gate.Principal(r.Context())
			_ = json.NewEncoder(w).Encode(map[string]string{"user": p.User.Username})
		})})
	if err != nil {
		log.Fatal(err)
	}
	mux := http.NewServeMux()
	mux.Handle("/api/", g)

	w := httptest.NewRecorder()
	mux.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "https://app.example/api/me", nil))
	fmt.Println(w.Code, w.Header().Get("WWW-Authenticate"), w.Body.String())
}
Output:
401 Bearer realm="access" {"code":"auth_required"}

func (*Gate) ServeHTTP

func (g *Gate) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves r on the row its method and path match, and answers every other request through Config.Errors: 404 auth_not_found for a path that is not canonical or that no row has, and 405 auth_method_not_allowed with Allow for a path whose rows want another method.

type Route

type Route struct {
	Name    string // unique; the app's name for the route
	Method  string // GET, POST, PUT, PATCH or DELETE; a GET row also answers HEAD
	Path    string // a ServeMux path: starts with "/", clean, no host, no trailing "/"; the root alone is "/{$}"
	Scope   string // required on Scoped, optional on Key, refused on Public and Session; one RFC 6750 scope-token
	Class   Class
	Passive bool // authenticate under access.Passive; refused on Public
	HTTPS   bool // admit only a secure request (access.ClientAddr.Secure); refused on Public
}

Route is one row of the app's endpoint table.

Jump to

Keyboard shortcuts

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