emu

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 39 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 emu defines the contract between the emulator core and service modules (NFR-MNT-002) and the shared environment they run in.

Index

Constants

View Source
const AliasVLAN = 4000

AliasVLAN is the VLAN that carries Declared addresses on a Translated network's bridge. Tagged frames bypass the host's iptables (with the default bridge-nf-filter-vlan-tagged=0), so the host's rules for the network that holds the Declared range, such as its MASQUERADE, do not rewrite them.

View Source
const ContainerizedWait = 3 * time.Second

ContainerizedWait is how long a caller deciding at start waits for the container runtime to say whether the Instance is a Containerized Instance (Containerized).

View Source
const InvalidUniverse = "gcpemu.invalid"

InvalidUniverse is the Invalid universe (see CONTEXT.md): the universe domain clients are given so that an API without an endpoint override is addressed as <api>.gcpemu.invalid, which never resolves (RFC 6761), and fails instead of reaching Google.

View Source
const PublicRouteProto = 245

PublicRouteProto tags the routes PublicRoutesScript programs, so that a later script finds and removes the stale ones.

Variables

View Source
var ErrNoRuntime = errors.New("no container runtime")

ErrNoRuntime marks a permanent Containers.Runtime failure (see NoRuntime).

Functions

func CopyTree added in v0.6.0

func CopyTree(src, dst string) error

CopyTree copies the files under src beneath dst; a missing src is an empty tree.

func FormatUUID added in v0.9.0

func FormatUUID(h string) string

FormatUUID groups 32 hex digits as a UUID (8-4-4-4-12).

func IsGoogleHost

func IsGoogleHost(host string) bool

IsGoogleHost reports whether host (optionally with a port) is one of Google's API, sign-in or token hosts.

func LinkTree added in v0.6.0

func LinkTree(src, dst string) error

LinkTree recreates the files under src beneath dst as hard links, copying them where links are unsupported (across filesystems). It is for files that are never modified in place, such as blobs; a missing src is an empty tree.

func NoRuntime added in v0.9.0

func NoRuntime(err error) error

NoRuntime marks err as a permanent Containers.Runtime failure: it matches ErrNoRuntime as well as err, and keeps err's message.

func NoteResource

func NoteResource(ctx context.Context, resource string)

NoteResource records the resource a call acts on (the first one wins).

func ParseTime added in v0.2.0

func ParseTime(s string) time.Time

ParseTime parses an API timestamp (RFC 3339), returning the zero time for an empty or malformed one.

func PublicRoutesScript added in v0.6.0

func PublicRoutesScript(via string, ips []string) string

PublicRoutesScript returns idempotent sh commands (iproute2) that make the host routes to ips via via the only routes tagged PublicRouteProto. An empty via removes them all.

func WithPrincipal

func WithPrincipal(ctx context.Context, p Principal) context.Context

WithPrincipal stores the caller in ctx.

Types

type ADCKeyer added in v0.6.0

type ADCKeyer interface {
	// ADCKey returns a key file for the host metadata server's service
	// account. current is the previous one, returned unchanged while its
	// key is still valid.
	ADCKey(current []byte) ([]byte, error)
}

ADCKeyer is implemented by the service that issues the key file `gcpemu env` points GOOGLE_APPLICATION_CREDENTIALS at when gcloud's application-default credentials, which are Foreign credentials, would otherwise win over the metadata server (ADR 0010).

type AddressReserver added in v0.4.0

type AddressReserver interface {
	ReservedAddrs() []string
}

AddressReserver is implemented by services whose stored resources record container addresses and ask for them again when their containers are recreated (a Cloud SQL instance's public and private IP). Containers started without a fixed address never take one of them.

type Authenticator

type Authenticator interface {
	// Authenticate returns the principal for token, or ok=false if unknown.
	Authenticate(ctx context.Context, token string) (p Principal, ok bool)
}

Authenticator maps a bearer token to a principal (FR-CORE-051). It is provided by the IAM service.

type Authorizer

type Authorizer interface {
	// Check returns a PERMISSION_DENIED error when the caller in ctx lacks
	// permission on resource (a full resource name such as
	// "//storage.googleapis.com/projects/_/buckets/b") and enforcement is on.
	Check(ctx context.Context, permission, resource string) error
	// Authenticate resolves a bearer token.
	Authenticator
	// Mode returns the enforcement mode.
	Mode() string
}

Authorizer checks permissions (FR-IAM-004, FR-INT-012).

type CallInfo

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

CallInfo collects what the request log reports about a call beyond its method and status (FR-CORE-061): the resource whose permission was checked first. It also carries the call's Service and method, for the denial log.

func WithCallInfo

func WithCallInfo(ctx context.Context) (context.Context, *CallInfo)

WithCallInfo returns ctx carrying a fresh CallInfo.

func (*CallInfo) Resource

func (ci *CallInfo) Resource() string

Resource returns the recorded resource.

func (*CallInfo) SetCall added in v0.6.0

func (ci *CallInfo) SetCall(service, method string)

SetCall records the Service and method of the call, as the Request log names them.

type CertManager

type CertManager interface {
	// MapCertificate selects the certificate for sni from a certificate map
	// using Certificate Manager's matching rules (exact hostname, wildcard,
	// then PRIMARY entry). It returns nil without error when no entry matches.
	MapCertificate(ctx context.Context, certificateMap, sni string) (*tls.Certificate, error)
	// Certificate returns an ACTIVE Certificate Manager certificate.
	Certificate(ctx context.Context, name string) (*tls.Certificate, error)
	// BackendAuthentication resolves a BackendAuthenticationConfig: the client
	// certificate the LB presents to backends (nil if none) and the roots used
	// to verify backend server certificates (nil means "public roots" per
	// wellKnownRoots; an empty non-nil pool means none configured).
	BackendAuthentication(ctx context.Context, name string) (client *tls.Certificate, roots *x509.CertPool, err error)
	// ServerTLSPolicy resolves frontend mTLS settings: roots that validate
	// client certificates and the clientValidationMode
	// ("ALLOW_INVALID_OR_MISSING_CLIENT_CERT" or "REJECT_INVALID").
	ServerTLSPolicy(ctx context.Context, name string) (clientRoots *x509.CertPool, mode string, err error)
}

CertManager is provided by the "certs" service: Certificate Manager (certificates, certificate maps, trust configs, DNS authorizations) and Network Security (backend authentication configs, server TLS policies) as the load balancer data plane consumes them (FR-LB-004, FR-LB-006, FR-LB-009). Names are full resource names ("projects/P/locations/L/certificateMaps/M"); errors are *apierr.Error.

type ClockObserver

type ClockObserver interface {
	ClockAdvanced(ctx context.Context) error
}

ClockObserver is implemented by services with time-driven behaviour (lifecycle rules, TTLs) that must re-evaluate after `gcpemu time advance`.

type ConnectedRuntime added in v0.10.0

type ConnectedRuntime interface {
	Connected() *runtime.Manager
}

ConnectedRuntime is implemented by Containers that can report the runtime without connecting it: Connected is nil until a first Runtime call has connected it. Read-only views use it so that looking never detects the runtime or reclaims orphans.

type ContainerizedProbe added in v0.10.0

type ContainerizedProbe struct {
	Markers func() bool
	Self    func(ctx context.Context) (self string, found bool, err error)
}

ContainerizedProbe stands in for what Containerized asks, in tests: Markers for runtime.InContainer, and Self for the runtime's self container ("" on the host's network) and whether it found it (runtime.Client.SelfFound), an error being no runtime.

type Containers

type Containers interface {
	// Runtime detects the runtime on first use and reclaims orphans. An
	// error matching ErrNoRuntime is permanent: the instance has no usable
	// runtime and returns the same error on every later call. Any other
	// error is transient, and a later call tries again.
	Runtime(ctx context.Context) (*runtime.Manager, error)
	// Netplane returns the instance's services/external network manager.
	Netplane(ctx context.Context) (*netplane.Plane, error)
	// DialContext is the ContainerDialer (netplane.Plane.DialContext). It
	// dials directly until a service has used the netplane, since no
	// container can be running before then.
	DialContext(ctx context.Context, network, addr string) (net.Conn, error)
	// RelayIP is the VM relay's address on the services network, at which
	// containers reach emulator endpoints (netplane.Plane.Addr), or ""
	// when no relay runs.
	RelayIP() string
}

Containers gives services lazy access to the container runtime and the instance's container networks (Section 3.3). It is nil-safe: services that need a runtime call Netplane and report not-ready on error.

type Denial added in v0.6.0

type Denial struct {
	// ID is stable for the Principal, permission and resource.
	ID         string `json:"id"`
	Principal  string `json:"principal"`
	Permission string `json:"permission"`
	Resource   string `json:"resource"`
	// DenyPolicy names the deny policy that refused the call; it is empty
	// when no allow policy granted the permission.
	DenyPolicy string `json:"denyPolicy,omitempty"`
	// Service and Method are the latest denied call's, as the Request log
	// names them.
	Service string `json:"service,omitempty"`
	Method  string `json:"method,omitempty"`
	// Level is the IAM enforcement level of the latest denied call: audit
	// (allowed) or enforce (failed with PERMISSION_DENIED).
	Level     string    `json:"level"`
	Count     int       `json:"count"`
	FirstTime time.Time `json:"firstTime"`
	LastTime  time.Time `json:"lastTime"`
	// Role is the smallest predefined role granting Permission, and
	// RoleTitle its title; Project is the Project owning Resource, where
	// a binding of Role grants it. They and Granted are worked out when
	// the Denial is read. A deny policy's Denial has no Role, since no
	// grant overrides a deny.
	Role      string `json:"role,omitempty"`
	RoleTitle string `json:"roleTitle,omitempty"`
	Project   string `json:"project,omitempty"`
	// Granted reports that the Principal now holds Permission on Resource,
	// with no deny policy refusing it.
	Granted bool `json:"granted"`
	// contains filtered or unexported fields
}

Denial is a call that the audit IAM enforcement level would deny (FR-IAM-004, FR-UI-014): a Principal lacking a permission on a resource, or refused it by a deny policy (FR-IAM-010). Calls by the same Principal, for the same permission on the same resource, refused by the same deny policy or by none, are one Denial.

type DenialAdvisor added in v0.6.0

type DenialAdvisor interface {
	// AdviseGrant returns the smallest predefined role granting
	// permission, its title, and the Project owning resource ("" when
	// none is known).
	AdviseGrant(ctx context.Context, permission, resource string) (role, title, project string)
}

DenialAdvisor says how to grant a denied permission. The IAM service provides it.

type DenyEvaluator added in v0.6.0

type DenyEvaluator interface {
	// Denied returns the name of the deny policy refusing permission, or
	// ok=false when none does.
	Denied(ctx context.Context, p Principal, permission, resource string) (policy string, ok bool)
}

DenyEvaluator decides whether a deny policy refuses a principal a permission on a resource (FR-IAM-010). An evaluator that implements it is consulted before any allow policy.

type Endpoints

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

Endpoints is a concurrency-safe name → address map.

func NewEndpoints

func NewEndpoints() *Endpoints

func (*Endpoints) All

func (e *Endpoints) All() map[string]string

All returns a copy of the map.

func (*Endpoints) Delete added in v0.4.0

func (e *Endpoints) Delete(name string)

Delete removes an endpoint.

func (*Endpoints) Get

func (e *Endpoints) Get(name string) string

func (*Endpoints) Names

func (e *Endpoints) Names() []string

Names returns the endpoint names in sorted order.

func (*Endpoints) Set

func (e *Endpoints) Set(name, addr string)

type Env

type Env struct {
	Config *config.Config
	Store  store.Store
	Clock  clock.Clock
	IDs    *IDs
	Log    *slog.Logger
	// DataDir holds per-service file data (objects, blobs, caches).
	DataDir string
	// Auth authorizes callers (FR-IAM-004); never nil.
	Auth Authorizer
	// Endpoints records listener addresses for endpoints.json.
	Endpoints *Endpoints
	// Middleware wraps HTTP handlers on per-service ports with the same
	// auth/logging the gateway applies.
	Middleware func(service string, h http.Handler) http.Handler
	// GRPCOptions returns server options (interceptors) for per-service gRPC servers.
	GRPCOptions func(service string) []grpc.ServerOption
	// Containers provides the container runtime and networks (GKE, Cloud SQL, NAT).
	Containers Containers
	// CA is the instance's local certificate authority (Section 7.4).
	CA *ca.CA
	// RequestLog records data-plane requests in the instance's request log
	// (FR-CORE-061); nil-safe for callers that check it.
	RequestLog *reqlog.Log
	// LANBindWhere locates the Instance for the --*-bind addresses
	// (LANBind); nil decides as Containerized does.
	LANBindWhere func(ctx context.Context) lanbind.Where
	// ContainerizedProbe replaces what Containerized asks, in tests; nil
	// uses runtime.InContainer and Containers.
	ContainerizedProbe *ContainerizedProbe
	// contains filtered or unexported fields
}

Env is the shared environment passed to every service.

func (*Env) Containerized added in v0.10.0

func (e *Env) Containerized(ctx context.Context) bool

Containerized reports whether the Instance is a Containerized Instance (runtime.DecideContainerized, #502). When it may be one, it asks the container runtime, connecting it if needed, for as long as ctx allows; without an answer --containerized and the marker files decide. The guess and any conflict are logged once (NoteContainerized).

func (*Env) DeclareProject

func (e *Env) DeclareProject(id string) error

DeclareProject records a project explicitly (seed files, config).

func (*Env) EnsureProject

func (e *Env) EnsureProject(id string) error

EnsureProject implements FR-CORE-020: any valid project ID is auto-created on first use unless --strict-projects is set, in which case it must be declared in config or the seed.

func (*Env) ExplainBind added in v0.10.0

func (e *Env) ExplainBind(ctx context.Context, err error) error

ExplainBind is lanbind.Explain for err, the failure to bind a --*-bind address; it locates the Instance only when err needs it.

func (*Env) LANBind added in v0.10.0

func (e *Env) LANBind(ctx context.Context) lanbind.Where

LANBind reports where the Instance binds the --lb-bind, --gke-bind, --ar-bind and --gfe-bind addresses: in its own network namespace only in a Containerized Instance (Containerized's decision, without logging), which is Bridge only when the runtime found its container (#564). It asks the container runtime only when the Instance may be one, connecting it if needed.

func (*Env) Listen

func (e *Env) Listen(name string) (net.Listener, error)

Listen opens a TCP listener for a named port on the configured bind address and records it in Endpoints.

func (*Env) ListenTCP

func (e *Env) ListenTCP(host string, port int) (net.Listener, error)

ListenTCP listens on host:port. Port 0 picks a free port, from --port-range when one is set (FR-CORE-042).

func (*Env) Lookup

func (e *Env) Lookup(name string) (Service, bool)

Lookup returns a running service by name.

func (*Env) NoteContainerized added in v0.10.0

func (e *Env) NoteContainerized(d runtime.ContainerizedDecision)

NoteContainerized logs, once each, that d is a guess from the marker files or that --containerized disagrees with the runtime.

func (*Env) ProjectByNumber added in v0.3.0

func (e *Env) ProjectByNumber(num string) (string, bool)

ProjectByNumber maps a project number to a known project ID.

func (*Env) Projects added in v0.6.0

func (e *Env) Projects() []string

Projects returns the IDs of every Project the Instance knows, in order.

func (*Env) ServiceDir

func (e *Env) ServiceDir(name string) (string, error)

ServiceDir returns (creating) the data directory for a service.

func (*Env) SetServices

func (e *Env) SetServices(s map[string]Service)

SetServices installs the running service set for Lookup.

type EnvVarer

type EnvVarer interface {
	EnvVars(gateway string, endpoints map[string]string) map[string]string
}

EnvVarer is implemented by services that contribute client environment variables to `gcpemu env` (FR-CORE-004). gateway is the gateway host:port, endpoints the recorded listener addresses.

type IAMPermissionTester

type IAMPermissionTester interface {
	TestPermissions(ctx context.Context, resource string, permissions []string) []string
}

IAMPermissionTester is optionally provided by the "iam" service for resource-level testIamPermissions: it returns the subset of permissions the caller in ctx holds on resource (policy evaluation, ignoring mode).

type IAMPolicyStore

type IAMPolicyStore interface {
	GetPolicyJSON(ctx context.Context, resource string) ([]byte, error)
	SetPolicyJSON(ctx context.Context, resource string, policy []byte) ([]byte, error)
	DeletePolicy(ctx context.Context, resource string) error
}

IAMPolicyStore is provided by the "iam" service: resource-level IAM policies for services that support get/setIamPolicy (FR-IAM-003). resource is a full resource name, e.g. "//storage.googleapis.com/projects/_/buckets/b".

type IAMResourceParents

type IAMResourceParents interface {
	SetResourceParent(ctx context.Context, resource, parent string) error
}

IAMResourceParents is optionally provided by the "iam" service alongside IAMPolicyStore. Owning services call SetResourceParent when they create a resource whose full name does not contain its project (e.g. a bucket: SetResourceParent(ctx, "//storage.googleapis.com/projects/_/buckets/b", "projects/my-project")) so that project-level bindings apply to it. parent is "projects/P" or a full resource name. DeletePolicy also removes the parent mapping, so call it when the resource is deleted.

type IDs

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

IDs generates resource IDs. In deterministic mode IDs come from a counter so golden-file tests are reproducible (FR-CORE-022, NFR-REL-002).

func NewIDs

func NewIDs(deterministic bool) *IDs

NewIDs returns an ID generator.

func (*IDs) Hex

func (g *IDs) Hex(n int) string

Hex returns a random (or counter-derived) hex string of n bytes.

func (*IDs) Numeric

func (g *IDs) Numeric() string

Numeric returns Uint64 as a decimal string.

func (*IDs) Operation

func (g *IDs) Operation() string

Operation returns an operation name suffix like "operation-1700000000000-5f1a...".

func (*IDs) UUID added in v0.9.0

func (g *IDs) UUID() string

UUID returns Hex(16) formatted as a UUID.

func (*IDs) Uint64

func (g *IDs) Uint64() uint64

Uint64 returns a numeric ID in the 19-digit range GCP uses.

type LoadBalancerResources added in v0.6.0

type LoadBalancerResources interface {
	// PutLBResource creates the resource, or replaces every mutable field
	// of an existing one, with the API's validation and defaults, and
	// returns its stored form. A replaced forwarding rule keeps its address
	// unless the body gives one.
	PutLBResource(ctx context.Context, path string, body []byte) ([]byte, error)
	// LBResource returns a resource's stored form, or NOT_FOUND.
	LBResource(ctx context.Context, path string) ([]byte, error)
	// DeleteLBResource removes a resource; a missing one is not an error.
	// It fails with FAILED_PRECONDITION while another resource uses it.
	DeleteLBResource(ctx context.Context, path string) error
}

LoadBalancerResources is provided by the "lb" service: GKE's Ingress and Gateway controllers (FR-GKE-010) manage load-balancing resources through it, as GKE's service agent does through the compute API. path is a resource's relative name ("projects/P/global/urlMaps/M" or "projects/P/regions/R/backendServices/B"); bodies are its compute v1 JSON form. Errors are *apierr.Error.

type LoopbackHolder added in v0.6.0

type LoopbackHolder interface {
	LoopbackAddrs() []string
}

LoopbackHolder is implemented by services that serve host clients on 127.0.0.x addresses they allocate (LB forwarding rules, Cloud SQL instances and GKE LoadBalancer Services on a VM runtime), so that each avoids the others' addresses.

type NEGEndpoint

type NEGEndpoint struct {
	IP       string
	Port     int
	Instance string // node name
}

NEGEndpoint is a GCE_VM_IP_PORT network endpoint.

type NoVLANError added in v0.6.0

type NoVLANError struct {
	// Runtime names the container runtime (runtime.Info.String()).
	Runtime string
	// Network is the Translated network's runtime name.
	Network string
}

NoVLANError reports that the kernel of the container runtime cannot create the VLAN link that a Translated network carries its Declared addresses on (ADR 0004). Only that network fails; every other feature works.

func (*NoVLANError) Error added in v0.6.0

func (e *NoVLANError) Error() string

type ObjectStore added in v0.9.0

type ObjectStore interface {
	// ReadObject opens generation gen of an object, or its live
	// generation when gen is 0, and returns the generation it opened. An
	// object or generation that does not exist is NOT_FOUND.
	ReadObject(ctx context.Context, bucket, name string, gen int64) (io.ReadCloser, int64, error)
	// AppendObject adds data to the end of an object, creating it with
	// contentType when absent. Each call makes a new generation holding
	// everything appended so far, so a reader polling the live object
	// sees it grow, as with a log written while it is read.
	AppendObject(ctx context.Context, bucket, name, contentType string, data []byte) error
	// WriteObject stores r as the object, replacing any live generation,
	// and returns the new generation and the data's MD5.
	WriteObject(ctx context.Context, bucket, name, contentType string, r io.Reader) (gen int64, md5 []byte, err error)
	// EnsureServiceBucket creates a bucket in project unless it exists,
	// without the naming rule users are held to: a bucket Google itself
	// names, such as Cloud Build's default logs bucket, may contain
	// "google".
	EnsureServiceBucket(ctx context.Context, project, name string) error
}

ObjectStore is provided by the "gcs" service: Cloud Storage objects for other Services in process, such as Cloud Build's sources and logs. It makes no IAM checks; the calling Service checks its own permissions. Errors are *apierr.Error.

type OperationError added in v0.2.0

type OperationError struct {
	Code    string `json:"code,omitempty"`
	Message string `json:"message"`
}

OperationError is why an Operation failed.

type OperationInfo added in v0.2.0

type OperationInfo struct {
	// Service is the Service ID; the admin API fills it in.
	Service string `json:"service"`
	// Name is the Operation's resource name, e.g.
	// "projects/p/global/operations/operation-1".
	Name    string `json:"name"`
	Project string `json:"project,omitempty"`
	// Location is "global", a region, a zone or an API location.
	Location string `json:"location,omitempty"`
	// Type is what the Operation does, as its API names it ("insert",
	// "CREATE_CLUSTER", "change").
	Type string `json:"type,omitempty"`
	// Target is the resource the Operation acts on or produced.
	Target string `json:"target,omitempty"`
	// Status is the API's own status ("RUNNING", "pending", ...).
	Status    string          `json:"status,omitempty"`
	Done      bool            `json:"done"`
	Error     *OperationError `json:"error,omitempty"`
	StartTime time.Time       `json:"startTime,omitzero"`
	EndTime   time.Time       `json:"endTime,omitzero"`
	// Operation is the Operation as the Service's API returns it.
	Operation json.RawMessage `json:"operation,omitempty"`
}

OperationInfo summarises one Operation for the admin API.

type OperationLister added in v0.2.0

type OperationLister interface {
	Operations() []OperationInfo
}

OperationLister is implemented by services whose mutations run as Operations (admin API /_emu/v1/operations, the Web console Operations view). Every Service's Operations are one concept whatever their wire format (CONTEXT.md), so each one is summarised in the same shape.

type PolicyAuthorizer

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

PolicyAuthorizer implements Authorizer using pluggable authenticator and evaluator, applying the configured mode. The mode starts as configured and can be switched while the Instance runs (SetMode). It keeps a log of the calls it would deny (Denials).

func NewPolicyAuthorizer

func NewPolicyAuthorizer(mode string, log *slog.Logger) *PolicyAuthorizer

NewPolicyAuthorizer returns an authorizer that allows everything until an evaluator is installed.

func (*PolicyAuthorizer) Authenticate

func (a *PolicyAuthorizer) Authenticate(ctx context.Context, token string) (Principal, bool)

func (*PolicyAuthorizer) Check

func (a *PolicyAuthorizer) Check(ctx context.Context, permission, resource string) error

func (*PolicyAuthorizer) ClearDenials added in v0.6.0

func (a *PolicyAuthorizer) ClearDenials()

ClearDenials forgets every Denial.

func (*PolicyAuthorizer) Denials added in v0.6.0

func (a *PolicyAuthorizer) Denials(ctx context.Context, project string) []Denial

Denials returns the Denials seen since the Instance started or was last Reset, most recently denied first, with the advice of the installed evaluator and whether each is now granted. A non-empty project keeps only that Project's.

func (*PolicyAuthorizer) Install

func (a *PolicyAuthorizer) Install(authn Authenticator, eval PolicyEvaluator)

Install sets the authenticator and evaluator (called by the IAM service).

func (*PolicyAuthorizer) Mode

func (a *PolicyAuthorizer) Mode() string

func (*PolicyAuthorizer) OnDeny added in v0.6.0

func (a *PolicyAuthorizer) OnDeny(fn func(Denial))

OnDeny sets a function called with every denied call's Denial. Set it before the authorizer is used.

func (*PolicyAuthorizer) SetMode added in v0.6.0

func (a *PolicyAuthorizer) SetMode(mode string)

SetMode switches the enforcement mode; later checks apply it.

type PolicyEvaluator

type PolicyEvaluator interface {
	Allowed(ctx context.Context, p Principal, permission, resource string) bool
}

PolicyEvaluator decides whether a principal holds a permission on a resource. The IAM service provides the real one.

type Principal

type Principal string

Principal identifies an API caller, e.g. "user:dev@example.com" or "serviceAccount:sa@p.iam.gserviceaccount.com".

func PrincipalFrom

func PrincipalFrom(ctx context.Context) Principal

PrincipalFrom returns the caller stored in ctx.

func (Principal) Email

func (p Principal) Email() string

Email returns the principal without its type prefix.

type PublicRouter added in v0.6.0

type PublicRouter interface {
	RoutePublic(ctx context.Context, via string, ips []string) error
}

PublicRouter is implemented by services whose Managed containers send traffic for public addresses over the external network: GKE nodes with external IPs, and the NAT egress proxies. The external network's gateway is the host, which cannot serve the load balancer's forwarding rule addresses, so the load balancer has its Edge relay serve them on the external network at via and asks for host routes to ips via it (#187). An empty via removes the routes. Implementations apply the routes to containers they start later, too.

type Publisher

type Publisher interface {
	// PublishInternal publishes to topic ("projects/P/topics/T") and returns
	// the message ID.
	PublishInternal(ctx context.Context, topic string, data []byte, attrs map[string]string) (string, error)
	// TopicExists reports whether the topic exists.
	TopicExists(ctx context.Context, topic string) bool
}

Publisher is provided by the "pubsub" service (FR-GCS-007, FR-INT-010).

type RelayAddresser added in v0.7.0

type RelayAddresser interface {
	RelayAddr(network string) string
}

RelayAddresser is implemented by services that pin the address the VM relay holds on a container network: compute keeps the Host address of a VPC container network there across restarts (ADR 0014). RelayAddr returns "" for networks it does not pin.

type ResetFinisher added in v0.9.0

type ResetFinisher interface {
	ResetDone()
}

ResetFinisher is implemented by Resetters whose background work must not resume before the Store is reset as well: a pass started in between would read the state the Reset removes (#307). The instance calls ResetDone at the end of every Reset, after the Store's.

type Resetter

type Resetter interface {
	Reset(ctx context.Context) error
}

Resetter is implemented by services that hold state outside the Store (blob files, in-memory queues) and must clear it on `gcpemu reset`.

type ResourceCounter added in v0.2.0

type ResourceCounter interface {
	ResourceCounts() map[string]int
}

ResourceCounter is implemented by services that report how many resources they hold (admin API /_emu/v1/resources/counts, the Web console dashboard). Keys are user-facing resource types named like the API's collections ("buckets", "subscriptions"), not store namespaces.

type Router

type Router interface {
	// Mount serves h for the API: under the path prefix "/<api>/" (prefix
	// stripped), and at the root for requests whose Host matches one of hosts.
	Mount(api string, hosts []string, h http.Handler)
	// Handle registers an unambiguous root path pattern (net/http.ServeMux syntax).
	Handle(pattern string, h http.Handler)
	// GRPC returns the gateway's gRPC server.
	GRPC() *grpc.Server
	// Fallback serves h for gateway paths no other route matches (used by
	// GCS for XML-style /BUCKET/OBJECT reads). Only one service may set it.
	Fallback(h http.Handler)
}

Router is the gateway surface a service registers on (FR-CORE-040).

type SQLUsers added in v0.3.0

type SQLUsers interface {
	// InstanceRegion returns a Cloud SQL instance's region.
	InstanceRegion(project, instance string) (string, error)
	// SetUserPassword sets a built-in user's password on a running
	// Cloud SQL instance.
	SetUserPassword(ctx context.Context, project, instance, user, password string) error
}

SQLUsers is provided by the "sql" service for Secret Manager's managed rotation of Cloud SQL credentials.

type SecretAccessor added in v0.3.0

type SecretAccessor interface {
	// AccessSecretVersion returns the payload of a secret version
	// ("projects/P/[locations/L/]secrets/S/versions/V") and the version's
	// full name, checking secretmanager.versions.access for the Principal
	// in ctx.
	AccessSecretVersion(ctx context.Context, name string) (payload []byte, version string, err error)
}

SecretAccessor is provided by the "secrets" service for GKE's Secret Manager add-on and secret synchronization.

type SeedExporter added in v0.6.0

type SeedExporter interface {
	// ExportSeed returns the section, which is marshalled as YAML, or nil
	// when the Service holds nothing to export.
	ExportSeed(ctx context.Context) (any, error)
}

SeedExporter is implemented by Seeders that can write their resources back as their seed section (FR-CORE-013, the Web console's Seed file export). Applying the section to an empty Instance recreates the same resources. Server-assigned fields (IDs, timestamps, etags) and data that lives only in a data plane (Postgres rows, Kubernetes objects) are not exported.

type Seeder

type Seeder interface {
	ApplySeed(ctx context.Context, section *yaml.Node, baseDir string) error
}

Seeder is implemented by services that accept a section of the seed file (FR-CORE-011). The section is keyed by the service name. Applying a seed must be idempotent. baseDir resolves relative paths in the seed file.

type Service

type Service interface {
	// Name is the short service name used by --services (e.g. "gcs").
	Name() string
	// Register mounts REST handlers and gRPC services on the gateway.
	Register(r Router) error
	// Start starts the service's own listeners and background work.
	Start(ctx context.Context) error
	// Stop releases everything Start acquired.
	Stop(ctx context.Context) error
	// Ready returns nil when the service can take traffic, or the reason it can't.
	Ready() error
}

Service is one emulated GCP service.

type ServiceAccountKeys

type ServiceAccountKeys interface {
	// PublicKeys returns every active public key of a service account
	// (used to verify V4 signed URLs, FR-GCS-006).
	PublicKeys(ctx context.Context, email string) ([]*rsa.PublicKey, error)
	// SignBlob signs data with one of the account's keys (RSA-SHA256).
	SignBlob(ctx context.Context, email string, data []byte) (keyID string, sig []byte, err error)
	// IDToken mints an OIDC ID token for email with the given audience,
	// verifiable against the emulator's JWKS (FR-IAM-007, FR-PS-006).
	IDToken(ctx context.Context, email, audience string) (string, error)
	// AccessToken mints an access token for a principal (e.g. "serviceAccount:x").
	AccessToken(ctx context.Context, principal Principal) (token string, expirySeconds int, err error)
}

ServiceAccountKeys is provided by the "iam" service.

type Snapshotter added in v0.6.0

type Snapshotter interface {
	// Snapshot saves the state the Store does not hold into dir, an empty
	// directory of the service's own. The Instance is ready and no
	// Operation is running.
	Snapshot(ctx context.Context, dir string) error
	// Restore brings the service back to a State snapshot after Reset and
	// after the Store was loaded with the snapshot's contents. dir holds
	// what Snapshot saved; it may be missing for a snapshot taken without
	// this service.
	Restore(ctx context.Context, dir string) error
}

Snapshotter is implemented by services that take part in State snapshots (FR-CORE-012) beyond the Store, which the Instance saves and loads itself: services holding state outside it (blob files, Postgres data) or rebuilding in-memory state or data planes from it.

type StoreCacher added in v0.7.0

type StoreCacher interface {
	// IsStoreCache reports whether key of namespace ns is a cache entry.
	IsStoreCache(ns, key string) bool
}

StoreCacher is implemented by services that keep a cache in the Store, such as a pull-through cache filled whenever a client pulls. Cache entries are saved and restored with the rest of the Store, but a change to one while a State snapshot is saved does not count as the Instance's state changing: the snapshot keeps the entries as they were before the services saved theirs. A cache entry a restore lacks must be refetched when it is next needed.

type SubnetNet

type SubnetNet struct {
	// Name is the runtime network name.
	Name string
	// Subnet is the range that addresses from AllocateIP come from, and
	// that the emulator reports: the Declared range (the subnetwork's
	// ipCidrRange or the private services access allocation). Only when
	// the Declared range overlapped another network on the host and the
	// network could not be Translated is it the Fallback range.
	Subnet string
	// ContainerSubnet is the CIDR the container network actually uses. It
	// differs from Subnet only on a Translated network.
	ContainerSubnet string
	// Translated is set when the container network is on a Fallback range
	// while its Managed containers hold Declared addresses: such a
	// container attaches without a fixed address, needs NET_ADMIN, and
	// runs AliasScript once started (and again after a restart).
	Translated bool
	// Gateway is the host-side address of the container network (the
	// .1 of ContainerSubnet, like GCP's gateway).
	Gateway string
	// SubnetworkName is "projects/P/regions/R/subnetworks/S".
	SubnetworkName string
	// NetworkName is "projects/P/global/networks/N".
	NetworkName string
	Region      string
	// SecondaryRanges maps rangeName to CIDR (GKE pods/services ranges).
	SecondaryRanges map[string]string
}

SubnetNet is a VPC subnetwork realised as a container network.

Addresses are reported from Subnet, and the emulator dials a container at its address on the container network (as the runtime reports it), never at a reported address: on a Translated network only workloads on the VPC can reach those (ADR 0004).

func (SubnetNet) AliasError added in v0.6.0

func (n SubnetNet) AliasError(runtime, out string, err error) error

AliasError classifies the failure of n's AliasScript, given its output and the error running it: a kernel without VLAN support becomes a NoVLANError naming runtime, and anything else is err unchanged.

func (SubnetNet) AliasScript added in v0.4.0

func (n SubnetNet) AliasScript(ip, cip string, routes ...string) string

AliasScript returns sh commands (iproute2 or busybox ip) that give a Managed container on a Translated network its Declared address ip: on a VLAN (AliasVLAN) of the interface holding cip, its address on the container network, with an on-link route for the Declared range sourced from ip. Each of routes ("default", or a CIDR) then goes via the NAT egress proxy's Declared address, also sourced from ip. The commands are idempotent. It returns "" when n is not Translated.

type Subscriber added in v0.10.0

type Subscriber interface {
	// ServePushHost has h serve, in process, the pushes to
	// https://host/... instead of sending them over the network.
	ServePushHost(host string, h http.Handler)
	// EnsurePushSubscription creates the push subscription name on topic
	// with endpoint, or points an existing one at them. A topic that does
	// not exist is NOT_FOUND.
	EnsurePushSubscription(ctx context.Context, name, topic, endpoint string) error
	// DeleteSubscriptionInternal deletes a subscription; one that does
	// not exist is not an error.
	DeleteSubscriptionInternal(ctx context.Context, name string) error
}

Subscriber is provided by the "pubsub" service: push subscriptions that another Service owns and serves in process, such as those of Cloud Build's pubsubConfig Build triggers. No IAM checks are made.

type VPC

type VPC interface {
	// ResolveSubnetwork returns the canonical subnetwork name
	// ("projects/P/regions/R/subnetworks/S") for a workload in region that
	// names a network and/or subnetwork (short names, partial or full URLs).
	// With neither, the project's "default" auto-mode network is used and
	// created on first use, as in a new GCP project.
	ResolveSubnetwork(ctx context.Context, project, region, network, subnetwork string) (string, error)
	// SubnetNetwork realises a subnetwork as a container network on first use.
	SubnetNetwork(ctx context.Context, subnetwork string) (SubnetNet, error)
	// PrivateServicesNetwork realises a VPC's private services access range
	// (allocated by a servicenetworking connection) for Cloud SQL private IP.
	// It returns FAILED_PRECONDITION when the VPC has no such connection.
	PrivateServicesNetwork(ctx context.Context, network string) (SubnetNet, error)
	// AllocateIP reserves a free address in net for owner (idempotent per
	// owner); ReleaseIP frees it.
	AllocateIP(ctx context.Context, net SubnetNet, owner string) (string, error)
	ReleaseIP(ctx context.Context, net SubnetNet, owner string) error
	// EgressProxy returns the address workloads without external IPs on
	// subnetwork must use as their default route. Traffic is forwarded to the
	// internet only while a Cloud NAT covers the subnetwork (FR-NAT-002).
	EgressProxy(ctx context.Context, subnetwork string) (string, error)
	// UpsertNEG creates a zonal GCE_VM_IP_PORT NEG if absent; SetNEGEndpoints
	// replaces its endpoints; DeleteNEG removes it. Used by GKE NEG sync.
	UpsertNEG(ctx context.Context, project, zone, name, network, subnetwork string, defaultPort int, description string) error
	SetNEGEndpoints(ctx context.Context, project, zone, name string, eps []NEGEndpoint) error
	DeleteNEG(ctx context.Context, project, zone, name string) error
}

VPC is provided by the "compute" service. It realises VPC subnetworks as container networks (Section 3.3), runs the NAT egress proxy (FR-NAT-002) and owns network endpoint groups (FR-GKE-008).

type WaitCondition added in v0.10.0

type WaitCondition func(ctx context.Context, t WaitTarget) (WaitStatus, error)

WaitCondition evaluates one kind of Wait condition for a target. A resource that does not exist is pending, not failed: it may still be being created. An error means the target can never name a resource of the kind (e.g. a location the kind has none in).

type WaitConditioner added in v0.10.0

type WaitConditioner interface {
	// WaitConditions maps each kind the service evaluates, e.g.
	// "gke/cluster", to its WaitCondition.
	WaitConditions() map[string]WaitCondition
}

WaitConditioner is implemented by services that evaluate Wait conditions on their own resources (FR-CI-007, admin API /_emu/v1/conditions).

type WaitState added in v0.10.0

type WaitState string

WaitState is how a Wait condition (see CONTEXT.md) stands.

const (
	// WaitMet: the condition holds.
	WaitMet WaitState = "met"
	// WaitPending: the condition does not hold yet, but may.
	WaitPending WaitState = "pending"
	// WaitFailed: the condition can no longer hold.
	WaitFailed WaitState = "failed"
)

type WaitStatus added in v0.10.0

type WaitStatus struct {
	State  WaitState `json:"state"`
	Reason string    `json:"reason,omitempty"`
}

WaitStatus is a Wait condition's state and, unless it is met, why.

type WaitTarget added in v0.10.0

type WaitTarget struct{ Project, Location, Name string }

WaitTarget is a Wait condition's TARGET, PROJECT/LOCATION/NAME.

func ParseWaitCondition added in v0.10.0

func ParseWaitCondition(s string) (kind string, t WaitTarget, err error)

ParseWaitCondition splits a Wait condition written KIND=TARGET, where TARGET is PROJECT/LOCATION/NAME. It does not check that KIND exists.

Jump to

Keyboard shortcuts

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