Documentation
¶
Overview ¶
Package server builds the http.Handler of /api/v1: panic recovery, request id, security headers, Origin check, body cap, then the route table of the contract drives module gating, authentication, role checks and CSRF before the request reaches the generated ogen server. The checks are generated from the contract tables (core/api/routes), not written per handler (API_CONVENTIONS 7.4).
Index ¶
- Constants
- Variables
- func Envelope(log *slog.Logger, next http.Handler) http.Handler
- func HostAllowlist(allowed []string, next http.Handler) http.Handler
- func HostAllowlistFunc(allowedHost func(host string) bool, next http.Handler) http.Handler
- func HostAllowlistWith(allowed []string, own func(netip.Addr) bool, next http.Handler) http.Handler
- func HostMatcher(allowed []string, own func(netip.Addr) bool) func(host string) bool
- func ModuleOf(op routes.Operation) string
- func New(cfg Config) (http.Handler, error)
- func RequestIDFrom(ctx context.Context) string
- func ValidWildcard(h string) bool
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- type AddrLimiter
- type Authenticator
- type Config
- type Exchange
- type Fallback
- type ModuleGate
- type Principal
Examples ¶
Constants ¶
const DefaultMaxBody = 1 << 20
DefaultMaxBody is the request body cap in bytes (1 MiB) when Config.MaxBody is 0.
const Prefix = "/api/v1"
Prefix is the root of the API.
const PublicPerMinuteDefault = 60
PublicPerMinuteDefault is the box's limit of requests without a session per client address (API_CONVENTIONS §8).
Variables ¶
var ErrNoSession = errors.New("server: no valid session")
ErrNoSession is what an Authenticator returns when the request carries no valid session: the response is 401 unauthenticated.
Functions ¶
func Envelope ¶
Envelope is the outermost layer of every response the process produces: panic recovery, a fresh request id and the security headers. New applies it to the API; cmd/vedette applies it again around the whole top-level handler so responses made outside the API (the ServeMux redirects, 404 for other paths) carry the same headers and id. The request id is kept when an outer Envelope already set it.
func HostAllowlist ¶
HostAllowlist answers 421 misdirected_request to every request whose Host header is not on the list, before any routing. This is the defence against DNS rebinding: a page on evil.example whose name an attacker later points at the box would otherwise be served as if it were the box, and could read the answers. Names compare case-insensitively without the port and without a trailing dot; IP literals compare in canonical form (an IPv6 literal in brackets). An entry that starts with "*." is a wildcard that matches like the one in a certificate: exactly one label (*.corp.example matches box.corp.example, not a.b.corp.example nor corp.example) and never an IP literal. A wildcard needs at least two labels after "*." (*.corp.example, not *.com) and is never IP-shaped; an entry that breaks this is ignored here (cmd/vedette refuses it when it parses -hosts). *.co.uk is accepted: no public-suffix list is shipped. "localhost", 127.0.0.1 and ::1 are always allowed: that is how a developer, and the box's own health check, reach it.
func HostAllowlistFunc ¶
HostAllowlistFunc is HostAllowlist with the test given as a function: HostMatcher's, or one that also accepts a name the box learns while it runs (cmd/vedette: the Box address an administrator saves). The refusal is the same for every client (421, nothing routed); only its body differs: a browser opening a page gets a short HTML page (misdirectedPage), an API client the JSON error.
func HostAllowlistWith ¶
HostAllowlistWith is HostAllowlist that also accepts a Host that is an IP literal (port optional) for which own returns true: the addresses the box itself has right now. After a change of the management address the admin opens the box at the new one, which the list fixed at start cannot know; names stay pinned to the list. A DNS rebinding page is reached by name, never by one of the box's own addresses. own may be nil.
func HostMatcher ¶
HostMatcher is the test HostAllowlistWith applies to the Host header, for code that must ask the same question again (the agent-intake install scripts put a Host into text a server will run, so they re-check it against the very list that let the request in).
func ModuleOf ¶
ModuleOf returns the id of the module that owns an operation. When that module is off its routes answer 404 as if they did not exist (SYS-5).
func New ¶
New returns the handler for URLs under Prefix. It refuses to build when the route table is inconsistent (INV-5): a role outside viewer/operator/admin/public, or an operation no module owns.
func RequestIDFrom ¶
RequestIDFrom returns the request id (also sent as X-Request-Id), or "" outside a request.
func ValidWildcard ¶
ValidWildcard reports whether h (lower case, "*." first) is a usable wildcard host: no other "*", at least two labels after "*." (so *.com is refused, *.corp.example is fine), and not IP-shaped (the last label, the top-level domain, is never all digits: *.168.1.10 would otherwise stand for 192.168.1.10).
Types ¶
type AddrLimiter ¶
type AddrLimiter struct {
// contains filtered or unexported fields
}
AddrLimiter is the same per-address sliding window for a public handler outside the API: the URL honey token, /t/<id>, which writes a hit per request and so must not be a way to make the box write or alert without end. Loopback is not counted.
func NewAddrLimiter ¶
func NewAddrLimiter(perMinute int, now func() time.Time) *AddrLimiter
NewAddrLimiter allows perMinute requests per client address (IPv6 per /64) and minute; now is the clock (nil: time.Now).
type Authenticator ¶
type Authenticator interface {
// Authenticate returns the principal of the request. ErrNoSession (or any error wrapping it)
// gives 401; an *apierr.Error is sent as it is (for example 403 disabled); anything else is a 500.
Authenticate(r *http.Request) (Principal, error)
// CheckCSRF is called for authenticated POST, PUT, PATCH and DELETE requests, after the role
// check. Any error refuses the request (403 csrf_invalid unless it is an *apierr.Error).
CheckCSRF(r *http.Request, p Principal) error
}
Authenticator is the hook the session layer implements with sessions and CSRF tokens.
type Config ¶
type Config struct {
API oas.Handler // the composite handler: see Fallback
Auth Authenticator // sessions and CSRF
Modules ModuleGate
Log *slog.Logger
MaxBody int64 // bytes; 0 = DefaultMaxBody
// BodyLimits raises (or lowers) the cap for single operations, by operationId, e.g. a 5 MiB
// sample upload (issue #39). Every other operation keeps MaxBody.
BodyLimits map[string]int64
// PublicPerMinute is the limit of public requests without a session per client address and minute (publimit.go): 429
// rate_limited past it. 0 = no limit (tests that are not about it, and a container-only install, where the port proxy may show
// every client as one address); cmd/vedette sets PublicPerMinuteDefault on an appliance.
PublicPerMinute int
}
Config is what New needs; every field except MaxBody is required.
type Exchange ¶
type Exchange struct {
R *http.Request
W http.ResponseWriter
}
Exchange is the raw HTTP exchange of the request being served.
func ExchangeFrom ¶
ExchangeFrom returns the HTTP exchange the server put in the context of an API request.
func (Exchange) ClientAddr ¶
ClientAddr is the address of the peer that opened the connection (r.RemoteAddr). Forwarded headers are never read: Vedette is not behind a proxy, and a header the client can write must not pick the key of a rate limit. The zero Addr is returned when the address cannot be parsed.
func (Exchange) SetContentType ¶
SetContentType makes the response a download of that media type, whatever the generated encoder sets. Call it before the handler returns, and only on success.
type Fallback ¶
type Fallback struct {
oas.UnimplementedHandler
Log *slog.Logger
}
Fallback is the base of the composite handler: it answers every operation with 501 not_implemented (through oas.UnimplementedHandler) and implements NewError, the default error response of the generated server. See ExampleFallback for how it sits in the composite handler.
Example ¶
ExampleFallback shows how modules plug into the server: each module's handler struct implements only its own operations; the composite embeds server.Fallback (which embeds oas.UnimplementedHandler one level deeper) and every module handler at the same depth, so
- an operation nobody implements answers 501 not_implemented,
- a module's method shadows the stub, and
- two modules that implement the same operation make the method ambiguous, the composite stops satisfying oas.Handler and the build fails (the assertion below is that compile-time check).
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/knt048/vedette/core/api/oas"
"github.com/knt048/vedette/core/server"
"github.com/knt048/vedette/core/server/servertest"
)
type statusModule struct{}
func (statusModule) FeedsGetFeedsStatus(context.Context) (*oas.FeedsGetFeedsStatusOK, error) {
return &oas.FeedsGetFeedsStatusOK{}, nil
}
// ExampleFallback shows how modules plug into the server: each module's handler struct implements only
// its own operations; the composite embeds server.Fallback (which embeds oas.UnimplementedHandler one
// level deeper) and every module handler at the same depth, so
// - an operation nobody implements answers 501 not_implemented,
// - a module's method shadows the stub, and
// - two modules that implement the same operation make the method ambiguous, the composite stops
// satisfying oas.Handler and the build fails (the assertion below is that compile-time check).
func main() {
type api struct {
server.Fallback // depth 1 (UnimplementedHandler is at depth 2)
statusModule // depth 1
}
var _ oas.Handler = api{} // does not compile when two embedded modules implement one operation
log := slog.New(slog.DiscardHandler)
h, err := server.New(server.Config{
API: api{Fallback: server.Fallback{Log: log}},
Auth: &servertest.Auth{Users: servertest.StandardUsers()},
Modules: servertest.NewGate(),
Log: log,
})
if err != nil {
fmt.Println(err)
return
}
get := func(path string) int {
r := httptest.NewRequestWithContext(context.Background(), http.MethodGet, server.Prefix+path, nil)
r.AddCookie(&http.Cookie{Name: servertest.CookieName, Value: "viewer", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode})
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code
}
fmt.Println(get("/feeds/status"), get("/me"))
}
Output: 200 501
type ModuleGate ¶
ModuleGate says whether a module is on; modreg.Registry satisfies it. An off module's routes are 404.
type Principal ¶
type Principal struct {
ID string
Email string
Role routes.Role
// PasswordChangeRequired: the session was opened with a password an administrator set. Every
// operation except those in limitedSessionOps answers 403 password_change_required.
PasswordChangeRequired bool
}
Principal is the signed-in user of a request. The session authenticator fills it; the role is read from the database on every request (API_CONVENTIONS 7.4), never from the cookie.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package servertest holds fakes for tests of code behind core/server: an Authenticator that needs no database and a module gate backed by a map.
|
Package servertest holds fakes for tests of code behind core/server: an Authenticator that needs no database and a module gate backed by a map. |