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 ¶
- func IsGoogleHost(host string) bool
- func NoteResource(ctx context.Context, resource string)
- func ParseTime(s string) time.Time
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- type Authenticator
- type Authorizer
- type CallInfo
- type CertManager
- type ClockObserver
- type Containers
- type Endpoints
- type Env
- func (e *Env) DeclareProject(id string) error
- func (e *Env) EnsureProject(id string) error
- func (e *Env) Listen(name string) (net.Listener, error)
- func (e *Env) ListenTCP(host string, port int) (net.Listener, error)
- func (e *Env) Lookup(name string) (Service, bool)
- func (e *Env) ServiceDir(name string) (string, error)
- func (e *Env) SetServices(s map[string]Service)
- type EnvVarer
- type IAMPermissionTester
- type IAMPolicyStore
- type IAMResourceParents
- type IDs
- type NEGEndpoint
- type OperationError
- type OperationInfo
- type OperationLister
- type PolicyAuthorizer
- func (a *PolicyAuthorizer) Authenticate(ctx context.Context, token string) (Principal, bool)
- func (a *PolicyAuthorizer) Check(ctx context.Context, permission, resource string) error
- func (a *PolicyAuthorizer) Install(authn Authenticator, eval PolicyEvaluator)
- func (a *PolicyAuthorizer) Mode() string
- type PolicyEvaluator
- type Principal
- type Publisher
- type Resetter
- type ResourceCounter
- type Router
- type Seeder
- type Service
- type ServiceAccountKeys
- type SubnetNet
- type VPC
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsGoogleHost ¶
IsGoogleHost reports whether host (optionally with a port) is one of Google's API, sign-in or token hosts.
func NoteResource ¶
NoteResource records the resource a call acts on (the first one wins).
Types ¶
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.
func WithCallInfo ¶
WithCallInfo returns ctx carrying a fresh CallInfo.
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 ¶
ClockObserver is implemented by services with time-driven behaviour (lifecycle rules, TTLs) that must re-evaluate after `gcpemu time advance`.
type Containers ¶
type Containers interface {
// Runtime detects the runtime on first use and reclaims orphans.
Runtime(ctx context.Context) (*runtime.Manager, error)
// Netplane returns the instance's services/external network manager.
Netplane(ctx context.Context) (*netplane.Plane, error)
}
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 Endpoints ¶
type Endpoints struct {
// contains filtered or unexported fields
}
Endpoints is a concurrency-safe name → address map.
func NewEndpoints ¶
func NewEndpoints() *Endpoints
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
// contains filtered or unexported fields
}
Env is the shared environment passed to every service.
func (*Env) DeclareProject ¶
DeclareProject records a project explicitly (seed files, config).
func (*Env) EnsureProject ¶
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) Listen ¶
Listen opens a TCP listener for a named port on the configured bind address and records it in Endpoints.
func (*Env) ListenTCP ¶
ListenTCP listens on host:port. Port 0 picks a free port, from --port-range when one is set (FR-CORE-042).
func (*Env) ServiceDir ¶
ServiceDir returns (creating) the data directory for a service.
func (*Env) SetServices ¶
SetServices installs the running service set for Lookup.
type EnvVarer ¶
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).
type NEGEndpoint ¶
NEGEndpoint is a GCE_VM_IP_PORT network endpoint.
type OperationError ¶ added in v0.2.0
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.
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 (*PolicyAuthorizer) Check ¶
func (a *PolicyAuthorizer) Check(ctx context.Context, permission, resource string) error
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
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 ¶
PrincipalFrom returns the caller stored in ctx.
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 Resetter ¶
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
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 Seeder ¶
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 SubnetNet ¶
type SubnetNet struct {
// Name is the runtime network name.
Name string
// Subnet is the CIDR actually used by the container network. It equals
// the subnetwork's ipCidrRange unless that range overlapped another
// network on the host, in which case the runtime chose one.
Subnet string
// Gateway is the host-side address (the subnet's .1, 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.
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
// EgressGateway 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).
EgressGateway(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 Cloud NAT egress gateway (FR-NAT-002) and owns network endpoint groups (FR-GKE-008).