auditgate

package
v0.35.2 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 18 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 auditgate is the deny-by-default allowlist behind the remote audit gateway. It decides which Wails calls and which backend events a remote, view-only browser may reach, and nothing else: it opens no listener, dials no network and depends only on the standard library.

The decisions live in policy.json, embedded in the binary and loaded with Default. A Policy answers three questions:

  • Policy.EvaluateRuntime checks one POST /wails/runtime request and, when the request may pass, returns the canonical body to forward upstream. The bytes the client sent are never forwarded.
  • Policy.FilterEventMessage checks one message of the /wails/events socket.
  • Policy.Verify checks that every method Wails would bind for a set of service instances is classified, so a new method cannot become reachable unreviewed.

docs/development-audit-gateway.md describes the table and how to classify a new method or event.

Index

Constants

View Source
const (
	// MaxEventMessageBytes bounds one /wails/events message the filter
	// inspects. Backend events can carry whole resource lists, so the bound
	// is generous; a larger message is dropped, never forwarded. A gateway
	// must also give its WebSocket connections a read limit of at least this
	// size (for coder/websocket: Conn.SetReadLimit), because the library
	// default is far smaller and closes the connection on a larger message.
	MaxEventMessageBytes = 32 << 20
)
View Source
const (
	// MaxRuntimeBodyBytes bounds a /wails/runtime request body the evaluator
	// inspects. Wails accepts 64 MiB; a read-only audit has no use for that.
	// Callers must read at most MaxRuntimeBodyBytes+1 bytes of the body.
	MaxRuntimeBodyBytes = 1 << 20
)

Variables

This section is empty.

Functions

func BoundMethodFQNs

func BoundMethodFQNs(instances ...any) ([]string, error)

BoundMethodFQNs returns, sorted, the fully qualified name of every method Wails binds for the given service instances. Each instance must be a pointer to a named, non-generic type, exactly as application.NewService requires; a typed nil pointer is enough because only the type is inspected.

The name is PkgPath.TypeName.Method, built the way Wails builds it: every exported method of the pointer type (promoted methods included) except ServiceName, ServiceStartup, ServiceShutdown and ServeHTTP.

func MethodID

func MethodID(fqn string) uint32

MethodID returns the identifier Wails assigns to a bound method: the 32-bit FNV-1a hash of its fully qualified name. The host registers no binding aliases and no registered IDs, so this is also the ID the generated bindings call by.

func ValidCallIDPrefix

func ValidCallIDPrefix(s string) bool

ValidCallIDPrefix reports whether s is acceptable as RuntimeRequest. CallIDPrefix: one or more characters of A-Z, a-z, 0-9, "_" and "-", then exactly one terminator from "/", ":" and ".", at most 32 bytes in all. The terminator cannot occur in a client call-id, so one prefix can never be a prefix of another session's forwarded IDs: with "s1/" and "s12/" the IDs "s1/2x" and "s12/x" stay distinct, which "s1" and "s12" would not keep.

func ValidClientID

func ValidClientID(s string) bool

ValidClientID reports whether s is acceptable as a Wails client identifier: 1 to 64 characters of A-Z, a-z, 0-9, "_" and "-". The runtime generates nanoid values, which use exactly that alphabet. The same rule applies to the x-wails-client-id header and to the clientId query parameter of the event socket.

Types

type Decision

type Decision string

Decision is the policy outcome for a bound method, a runtime call or an event. Anything the policy does not name is denied; a shipped table never contains a third, undecided state.

const (
	Allow Decision = "allow"
	Deny  Decision = "deny"
)

The two decisions a table may record.

type EventMatch

type EventMatch string

EventMatch selects how an EventRule compares against an event name.

const (
	MatchExact  EventMatch = "exact"
	MatchPrefix EventMatch = "prefix"
	MatchSuffix EventMatch = "suffix"
)

The ways an event rule can match a name.

type EventReason

type EventReason string

EventReason explains an event filter outcome. Values are stable machine codes that are safe to log.

const (
	EventAllowed         EventReason = "allowed"
	EventDeniedByRule    EventReason = "denied_by_rule"
	EventNotAllowed      EventReason = "not_allowed"
	EventInvalidMessage  EventReason = "invalid_message"
	EventMessageTooLarge EventReason = "message_too_large"
	EventNotText         EventReason = "not_text"
)

Event filter outcomes.

type EventRule

type EventRule struct {
	Match    EventMatch `json:"match"`
	Name     string     `json:"name"`
	Decision Decision   `json:"decision"`
	Reason   string     `json:"reason"`
}

EventRule classifies backend events by name. A name matched by any deny rule is dropped, a name matched by an allow rule is forwarded, and every other name is dropped.

type EventVerdict

type EventVerdict struct {
	// Forward is true only when the message may be sent to the remote client.
	Forward bool
	Reason  EventReason
	// Name is the event name when the message parsed, otherwise empty.
	Name string
	// Rule is the table rule that decided the outcome. It is meaningful only
	// when Matched is true; an invalid message or an unlisted name (the
	// default drop) has no deciding rule.
	Rule    EventRule
	Matched bool
}

EventVerdict is the outcome of filtering one backend event message.

type MessageKind

type MessageKind int

MessageKind is the WebSocket message type of a message handed to FilterEventMessage. It mirrors the text and binary types of the WebSocket protocol without importing a WebSocket library.

const (
	// MessageText is a text message. Wails sends every event as one.
	MessageText MessageKind = iota + 1
	// MessageBinary is a binary message. The host never sends one.
	MessageBinary
)

The WebSocket message types.

type MethodRule

type MethodRule struct {
	FQN      string   `json:"fqn"`
	Decision Decision `json:"decision"`
	Reason   string   `json:"reason"`
}

MethodRule classifies one Wails-bound Go method, keyed by the fully qualified name Wails derives: PkgPath.TypeName.Method.

type Policy

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

Policy is the immutable, deny-by-default classification table. It is safe for concurrent use.

func Default

func Default() (*Policy, error)

Default parses and validates the policy embedded in the binary (policy.json). The table is small, so every call parses it afresh; callers that need it repeatedly should keep the result.

func Parse

func Parse(data []byte) (*Policy, error)

Parse validates and indexes a policy table. It rejects repeated and case-variant keys, unknown fields, trailing data, an unsupported version, undecided or unexplained rows, duplicates, ID collisions and event allow rules that a deny rule shadows.

func (*Policy) ClassifyEvent

func (p *Policy) ClassifyEvent(name string) (Decision, EventRule, bool)

ClassifyEvent applies the event rules to a name: a matching deny rule wins, then a matching allow rule, and any other name is denied. The returned rule is the one that decided and matched reports whether there was one; a name that no rule matches, or that is not a plausible event name, is denied by default and has no deciding rule.

func (*Policy) Counts

func (p *Policy) Counts() (int, int)

Counts returns how many bound methods the table allows and denies.

func (*Policy) EvaluateRuntime

func (p *Policy) EvaluateRuntime(req RuntimeRequest) Verdict

EvaluateRuntime decides whether one POST /wails/runtime request may reach the host and, when it may, returns the canonical body to forward.

The evaluation fails closed at every step. In order it enforces:

  • POST to exactly /wails/runtime, with no query string (the empty-body query-string form of the Wails protocol is thereby unreachable);
  • a configured session: req.ClientID passes ValidClientID and req.CallIDPrefix passes ValidCallIDPrefix;
  • no x-wails-chunk-* header (a chunked call cannot be inspected in pieces) and no x-wails-window-* header (those choose the window Wails runs the call as, which only the gateway-assigned client ID may do);
  • a JSON content type and exactly one x-wails-client-id header, equal to req.ClientID;
  • a non-empty body of at most MaxRuntimeBodyBytes;
  • strict JSON: valid UTF-8, one value, bounded depth, no duplicate or case-folded duplicate keys at any depth;
  • an envelope of exactly {object, method[, args]};
  • the runtime object table: unknown objects and unlisted methods are denied, and Call is gated per bound method by the method table, where the method may be named by methodName or methodID but never both, and both forms resolve to the same fully qualified name.

Header names are matched case-insensitively across every key of req.Header. Which window Wails runs an allowed call as depends on the upstream events socket the gateway holds for req.ClientID; the evaluator cannot see that, so the gateway must (see docs/development-audit-gateway.md).

func (*Policy) EventRules

func (p *Policy) EventRules() []EventRule

EventRules returns a copy of the event rules in table order.

func (*Policy) FilterEventMessage

func (p *Policy) FilterEventMessage(kind MessageKind, payload []byte) EventVerdict

FilterEventMessage decides whether one message the host sent on the Wails event socket may be forwarded to the remote client. The payload must be a complete message: WebSocket libraries return whole messages, reassembled from however many frames the peer used, so the filter never sees a partial one. Only a text message holding the JSON of a Wails custom event, {"name":...,"data":...,"sender":...}, can pass. A binary message, an unknown kind, or text that is anything else is dropped, and a message is forwarded unchanged only when its name is allowed. The filter never closes the socket: dropping is the only negative outcome.

Only the envelope is interpreted; the data payload is validated as JSON and skipped. Event messages flow from the trusted host to the client, so unlike request bodies they need no canonical re-serialization.

func (*Policy) Method

func (p *Policy) Method(fqn string) (MethodRule, bool)

Method returns the rule for a fully qualified bound method name.

func (*Policy) MethodByID

func (p *Policy) MethodByID(id uint32) (MethodRule, bool)

MethodByID returns the rule for a Wails binding ID. The lookup covers every classified method, denied ones included, so a denied ID is reported as denied rather than unknown.

func (*Policy) Methods

func (p *Policy) Methods() []MethodRule

Methods returns a copy of every method rule, sorted by name.

func (*Policy) RuntimeMethod

func (p *Policy) RuntimeMethod(object, method int) (RuntimeMethodRule, bool)

RuntimeMethod returns the rule of one method of a Wails runtime object.

func (*Policy) RuntimeObject

func (p *Policy) RuntimeObject(object int) (RuntimeObjectRule, bool)

RuntimeObject returns the rule of a Wails runtime object by number.

func (*Policy) RuntimeObjects

func (p *Policy) RuntimeObjects() []RuntimeObjectRule

RuntimeObjects returns a copy of the runtime object rules, sorted by number.

func (*Policy) Verify

func (p *Policy) Verify(instances ...any) error

Verify checks that every method Wails will bind for the given service instances is classified. The host calls it before registering services so a conditional or build-tagged service cannot expose an unreviewed method.

func (*Policy) WailsVersion

func (p *Policy) WailsVersion() string

WailsVersion is the Wails module version whose runtime object and method numbering the table was reviewed against.

type Reason

type Reason string

Reason explains an evaluator outcome. Values are stable machine codes that never contain request data, so they are safe to log and to return.

const (
	ReasonAllowed Reason = "allowed"

	ReasonHTTPMethod   Reason = "http_method_not_allowed"
	ReasonRoute        Reason = "route_not_runtime"
	ReasonStream       Reason = "stream_denied"
	ReasonQuery        Reason = "query_forbidden"
	ReasonChunked      Reason = "chunked_forbidden"
	ReasonWindowHeader Reason = "window_header_forbidden"
	ReasonContentType  Reason = "content_type"
	ReasonClientID     Reason = "client_id"
	ReasonCallIDPrefix Reason = "call_id_prefix"
	ReasonEmptyBody    Reason = "empty_body"
	ReasonBodyTooLarge Reason = "body_too_large"

	ReasonInvalidUTF8   Reason = "invalid_utf8"
	ReasonMalformedJSON Reason = "malformed_json"
	ReasonTrailingData  Reason = "trailing_data"
	ReasonTooDeep       Reason = "too_deep"
	ReasonDuplicateKey  Reason = "duplicate_key"
	ReasonCaseFoldedKey Reason = "case_folded_key"

	ReasonEnvelope      Reason = "envelope"
	ReasonUnknownKey    Reason = "unknown_key"
	ReasonArgsForbidden Reason = "args_forbidden"

	ReasonUnknownObject Reason = "unknown_object"
	ReasonRuntimeDenied Reason = "runtime_denied"

	ReasonCallID          Reason = "call_id"
	ReasonCallArgs        Reason = "call_args"
	ReasonMethodSelector  Reason = "method_selector"
	ReasonMethodName      Reason = "method_name"
	ReasonMethodID        Reason = "method_id"
	ReasonUnknownMethod   Reason = "unknown_method"
	ReasonUnknownMethodID Reason = "unknown_method_id"
	ReasonMethodDenied    Reason = "method_denied"
)

Evaluator outcomes. Everything except ReasonAllowed is a denial.

type Route

type Route int

Route classifies a request path.

const (
	// PathOther is any path the evaluator does not handle itself.
	PathOther Route = iota
	// PathRuntime is exactly /wails/runtime.
	PathRuntime
	// PathEvents is exactly /wails/events, the backend event WebSocket.
	PathEvents
	// PathStream is anything under /wails/stream, the Wails stream
	// transport. The host registers no stream handler, so it is denied.
	PathStream
)

Request path classes.

func ClassifyPath

func ClassifyPath(rawPath string) Route

ClassifyPath classifies the raw request path. Only the exact, undecoded spellings of /wails/runtime and /wails/events match those routes; encoded, cleaned or differently cased variants are PathOther. Stream paths are recognized under percent-decoding and case folding too, so denial reasons stay accurate for disguised requests; they are denied either way.

PathOther is a classification, not a decision: the evaluator forwards nothing for it, and the gateway serves it only from its own static-route allowlist (see docs/development-audit-gateway.md) or answers 404/405.

type RuntimeMethodRule

type RuntimeMethodRule struct {
	Method   int      `json:"method"`
	Name     string   `json:"name"`
	Decision Decision `json:"decision"`
	Reason   string   `json:"reason"`
}

RuntimeMethodRule classifies one method of a Wails runtime object other than the bound-method dispatcher, for example Window.Name or Application.Quit.

type RuntimeObjectRule

type RuntimeObjectRule struct {
	Object  int                 `json:"object"`
	Name    string              `json:"name"`
	Reason  string              `json:"reason"`
	Methods []RuntimeMethodRule `json:"methods"`
}

RuntimeObjectRule lists the rules of one Wails runtime object. Methods the list does not name are denied.

type RuntimeRequest

type RuntimeRequest struct {
	// Method is the HTTP method.
	Method string
	// Path is the request path exactly as received on the request line, with
	// no decoding or cleaning: the request target cut at "?", never the
	// decoded URL.Path.
	Path string
	// RawQuery is the raw query string, without the leading "?".
	RawQuery string
	// Header holds the request headers.
	Header http.Header
	// Body is the complete request body, at most MaxRuntimeBodyBytes+1 bytes.
	Body []byte
	// ClientID is the Wails client ID that the gateway bound to this session
	// and that this request must carry. The page, not the gateway, chooses
	// its client ID: the Wails runtime generates one at load and sends it in
	// x-wails-client-id and as the clientId query parameter of its events
	// socket. The gateway binds a session to the IDs that appear on the
	// session's own sockets, and passes here the bound ID the request names.
	// The request must carry exactly this value in x-wails-client-id; an
	// absent or different header is denied, and so is a ClientID that fails
	// ValidClientID.
	ClientID string
	// CallIDPrefix is prepended to the call-id of every forwarded call and of
	// every CancelCall, so one remote session cannot cancel or collide with
	// another session's in-flight calls. It is required and must satisfy
	// ValidCallIDPrefix: the evaluator denies every request of a session
	// whose prefix does not.
	CallIDPrefix string
}

RuntimeRequest is the part of an inbound HTTP request the evaluator needs, plus the two facts about the session that only the gateway knows.

type UnclassifiedError

type UnclassifiedError struct {
	FQNs []string
}

UnclassifiedError reports bound methods that are missing from the table.

func (*UnclassifiedError) Error

func (e *UnclassifiedError) Error() string

type Verdict

type Verdict struct {
	Allowed bool
	Reason  Reason
	// Object and Method are the Wails runtime object and method numbers, or
	// -1 when the body did not get that far.
	Object int
	Method int
	// Subject names what the request would run: the bound method's fully
	// qualified name for a call, or "Object.Method" for a runtime object
	// call. It is set only when it resolved to an entry of the policy table,
	// so it never echoes unvetted request text.
	Subject string
	// FQN is the resolved bound method of a Call request, allowed or denied.
	FQN string
	// Forward is the canonical request body to send upstream. It is set only
	// when Allowed, and it is rebuilt from the parsed values: it never
	// contains the original bytes.
	Forward []byte
}

Verdict is the outcome of evaluating one runtime request.

Jump to

Keyboard shortcuts

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