httpapi

package
v0.0.0-...-0c72368 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 27 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 httpapi builds the HTTP handlers of the two listeners: the public port (web UI, API, badges, LLM surface, webhook) and the admin port (probes, metrics, profiling, status).

Index

Constants

View Source
const (

	// DefaultMaxBody caps request bodies on routes that set no limit of their own.
	DefaultMaxBody = 64 << 10
)
View Source
const (
	// EventsPattern is the route of the snapshot event stream.
	EventsPattern = "GET /api/v1/events"
)

Variables

View Source
var ErrUnauthenticated = errors.New("unauthenticated")

ErrUnauthenticated is a credential that names nobody: the request is refused, never served anonymously.

Functions

func Admin

func Admin(o Options, alive, ready func() bool, routes ...Route) http.Handler

Admin returns the handler of the admin listener. ready reports whether the portal serves a catalogue, alive whether the sync dispatcher is running; routes are the operator handlers (metrics, status, profiling).

func AdminOnly

func AdminOnly(h http.Handler) http.Handler

AdminOnly answers 401 to an anonymous viewer and 403 to a viewer who is not an admin; admins reach h.

func DecodeStrict

func DecodeStrict(w http.ResponseWriter, r *http.Request, v any, badBody string) bool

DecodeStrict reads r's body into v, with no field v does not have; otherwise it has answered 400 with badBody.

func Matches

func Matches(inm, etag string) bool

Matches reports whether an If-None-Match header names etag (the weak comparison of RFC 9110) or is "*".

func PortalOrigin

func PortalOrigin(r *http.Request, publicURL string, forwardedHTTPS bool) string

PortalOrigin is the origin the portal answers as: the public URL's, else the request's own (https when it came in over TLS, or forwardedHTTPS: a trusted proxy said so). Everything that tells or compares the portal's origin shares this one; a guard that does not know the proxies (SameOrigin, the MCP one) passes false, so behind a TLS-terminating proxy it needs server.public_url.

func Private

func Private(ctx context.Context) bool

Private reports whether the request's viewer sees private repositories.

func Public

func Public(o Options, pages http.Handler, contract []byte, api oapi.StrictServerInterface, routes ...Route) http.Handler

Public returns the handler of the public listener. pages answers the paths no other handler has (Options.Pages); contract is api/openapi.yaml, served at /api/v1/openapi.yaml; api implements it; routes are the features' other handlers.

func RequireJSON

func RequireJSON(w http.ResponseWriter, r *http.Request, what string) bool

RequireJSON says whether r's body is application/json; otherwise it has answered 415. what is "the layout", "the announcements": what the caller is sent.

func SameOrigin

func SameOrigin(r *http.Request, publicURL string) bool

SameOrigin reports whether a state-changing request comes from the portal's own pages (design/auth.md): Sec-Fetch-Site is same-origin, or absent with an Origin equal to the public origin (the request's own when publicURL is empty). A request without a cookie (a bearer client) needs neither.

func Server

func Server(h http.Handler, log *slog.Logger) *http.Server

Server returns an http.Server with the fixed timeouts both listeners use.

func ShowForks

func ShowForks(ctx context.Context) bool

ShowForks reports whether the request asked for the forks the default views leave out (?forks=show). It names the URL, so a cache keeps the two answers apart.

func WithViewer

func WithViewer(ctx context.Context, v Viewer) context.Context

WithViewer returns ctx carrying v, for tests of handlers that read the viewer.

func WriteProblem

func WriteProblem(w http.ResponseWriter, status int, code, detail string)

WriteProblem writes an RFC 9457 problem with fixed text; the instance is the request id the middleware set.

Types

type Access

type Access struct {
	UserHeader, GroupsHeader string
	PrivateGroups            []string
	AdminEmails, AdminGroups []string
	Vary                     bool // private repositories are admitted: every response varies on the identity headers
}

Access says who sees what: the user and groups headers a trusted authenticating proxy sets, the groups whose members see private repositories ("*" admits every identified viewer), and who is an admin.

type Authenticator

type Authenticator interface {
	Identify(w http.ResponseWriter, r *http.Request) (Identity, bool, error)
}

Authenticator identifies a request by its bearer token or session cookie (design/auth.md). It reports false when the request carries neither, and ErrUnauthenticated when it carries a credential that names nobody. It may refresh the session on w.

type Events

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

Events streams server-sent events: the SnapshotInfo of the viewer's view when the stream opens and whenever a snapshot with another version is published, a comment every 25 s.

func NewEvents

func NewEvents(current func(context.Context) *snapshot.Snapshot, published func() <-chan struct{}) *Events

NewEvents returns the stream over the viewer's view (current) and the publisher's announcement (published: closed at the next publish).

func (*Events) Close

func (e *Events) Close()

Close ends every stream; register it with the server's shutdown.

func (*Events) Route

func (e *Events) Route() Route

Route is the stream's route.

func (*Events) ServeHTTP

func (e *Events) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Events) Streams

func (e *Events) Streams() int64

Streams is the number of open streams.

type Identity

type Identity struct {
	User   string   // the stable id: the provider's subject, the proxy's user, token:<name>
	Name   string   // what the web UI shows
	Email  string   // matched against Access.AdminEmails
	Groups []string // matched against the group lists
	Admin  bool     // granted by the credential itself (an admin token)
	Via    string   // proxy, oidc, token
	Login  string   // the viewer's GitHub login, when the credential knows it (a token configured with one); it only picks "mine" in lists
}

Identity is who a request comes from, as a proxy, the session or a token names it.

type MeAPI

type MeAPI struct {
	SignIn func() (oidc, token bool) // the ways of signing in; nil: none
}

MeAPI implements getMe.

type Options

type Options struct {
	Log       *slog.Logger
	Build     func() string // the web UI bundle's build, sent as X-SCP-Build on every response, so open pages notice a new one
	HSTS      bool          // the public URL is https
	PublicURL string        // server.public_url: the origin of canonical URLs; empty: the request's
	WebToken  string        // the secret the web UI server shows on its API calls to name the page's viewer (Pages)
	// NoIndex says whether the page at a request's address is kept out of search engines (design/visibility.md): it answers with
	// X-Robots-Tag: noindex, nofollow. nil: none is.
	NoIndex        func(*http.Request) bool
	FormTargets    []string       // origins a page's form may end at beyond the portal: the sign-in provider's end session
	TrustedProxies []netip.Prefix // peers whose X-Forwarded-For, and the Access headers, are believed
	Access         Access
	Auth           Authenticator // SCP's own sign-in and bearer tokens; nil without them
	RequireAuth    bool          // access.require_auth: the public listener refuses anonymous requests (but the open paths)
	// Observe, when set, receives every request: listener, matched pattern ("unmatched" when none), method, status, duration.
	Observe func(listener, pattern, method string, status int, d time.Duration)
	// ObservePrivate, when set, receives every request of the private view (the ones that leave an audit line): the matched pattern and
	// the status. Never the path, the viewer or the repository.
	ObservePrivate func(pattern string, status int)
}

Options configures what both listeners share.

func (Options) ClientIP

func (o Options) ClientIP(r *http.Request) string

ClientIP is the address of the client of r: see clientIP.

func (Options) Origin

func (o Options) Origin(r *http.Request) string

Origin is the portal's public origin: server.public_url, else the scheme and host the request arrived with (the scheme from a trusted proxy's X-Forwarded-Proto).

func (Options) Pages

func (o Options) Pages(upstream *url.URL) http.Handler

Pages returns the handler of the web UI's pages: a reverse proxy to the web UI server at upstream (nil: no web UI, every page answers 503). Each request gets a CSP nonce, set on the response and, for the server to put on its scripts, on the request; the request carries the viewer with o.WebToken, the request id and the origin.

type Route

type Route struct {
	Pattern  string
	Handler  http.Handler
	MaxBody  int64
	Markdown bool
	Stream   bool
}

Route is a handler a feature serves outside the API contract (badges, the webhook, Markdown). MaxBody caps the request body (0: DefaultMaxBody). A Markdown route shares its address with a page of the UI: Handler answers when the path ends in .md or the client prefers text/markdown to text/html, the page answers otherwise. A Stream route has no request deadline and, under /api/, none of the API's buffering.

type SnapshotAPI

type SnapshotAPI struct {
	Current func(context.Context) *snapshot.Snapshot // the viewer's view
}

SnapshotAPI implements getSnapshot.

type Viewer

type Viewer struct {
	Identity
	Private bool // sees private repositories
	Admin   bool // sees the operator surfaces; implies Private
	// contains filtered or unexported fields
}

Viewer is the request's viewer with its roles. The zero value is an anonymous viewer of the public view.

func ViewerOf

func ViewerOf(ctx context.Context) Viewer

ViewerOf returns the request's viewer, decided once per request by the middleware.

func (Viewer) SignedIn

func (v Viewer) SignedIn() bool

SignedIn reports whether the viewer is identified.

Directories

Path Synopsis
Package oapi is generated from api/openapi.yaml: the API types and the strict server interface.
Package oapi is generated from api/openapi.yaml: the API types and the strict server interface.

Jump to

Keyboard shortcuts

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