Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,42 @@ jobs:
moby-integration:
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
pull-requests: read
steps:
-
name: Checkout extensions
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
path: extensions
ref: ${{ github.event.pull_request.head.sha || github.sha }}
-
name: Resolve Moby ref
id: moby-ref
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
ref=master
if [[ -n "$PR_NUMBER" ]]; then
# A breaking change names the Moby PR that adapts to it with a
# "/moby-pr=<number>" line in its description.
# Read the body at run time so re-runs see edits.
body=$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}" --jq '.body // ""')
pr=$(tr -d '\r' <<<"$body" | sed -nE 's|^[[:space:]]*/moby-pr=([0-9]+)[[:space:]]*$|\1|p' | head -n1)
if [[ -n "$pr" ]]; then
ref="refs/pull/${pr}/head"
fi
fi
echo "ref=${ref}" >>"$GITHUB_OUTPUT"
echo "Testing against moby/moby \`${ref}\`." | tee -a "$GITHUB_STEP_SUMMARY"
-
name: Checkout Moby
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: moby/moby
ref: master
ref: ${{ steps.moby-ref.outputs.ref }}
path: moby
-
name: Set up Go
Expand Down
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,14 @@ Publishing a Point requires three things:

* The extension offers it using `servicev0.Offer`.
* Host policy permits it through `host.WithProviderPolicy`.
* The generated server wiring is registered.
* The embedder exposes it.

For an in-process provider, supply the server wiring through `host.WithPointServers`.
Permitted offers resolve through `servicev0.Point`, for in-process and out-of-process extensions alike.
The embedder decides how to expose each offered Point, for example by serving an in-process provider with its generated server wiring, or by proxying a separate process with `grpcproxy`.
A provider running in a separate process registers its `ServerPoint` with the SDK.

An offer is only a request to publish a Point; it does not grant access or register the transport.
If no provider policy is configured, external publication is disabled, while providers remain available to internal consumers.
If no provider policy is configured, offers are dropped, while providers remain available to internal consumers.

Published services are responsible for enforcing their own access control.

Expand All @@ -127,6 +128,11 @@ It may run inside the Host or in a separate process.
The framework component embedded in a daemon or application.
It registers extensions, resolves their dependencies, and manages their lifecycle.

### Embedder

The daemon or application that embeds the Host.
It configures the Host and decides how to expose offered Points to external callers.

### Provider

An extension that implements a Point.
Expand Down
4 changes: 2 additions & 2 deletions core.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ type PointID string

// IsMetadataPoint reports whether point carries framework metadata rather than
// a callable capability.
// Host provider admission skips metadata points; the servicev0 marker controls
// publication.
// Host provider admission drops metadata points unless policy allows them; the
// servicev0 marker lists offered points.
// Currently the servicev0 offer marker is the only metadata point; its package
// tests keep this ID in sync with the point definition.
func IsMetadataPoint(point PointID) bool {
Expand Down
47 changes: 37 additions & 10 deletions docs/AUTHORING.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ Use `host.WithProviderPolicy` to restrict which extensions may provide internall
See [DESIGN.md#discovery-security](./DESIGN.md#discovery-security).

A Point that only external callers use does not need `ClientPoint` wiring.
Offer it for publication instead: the proxy forwards calls to the extension by gRPC service name without decoding them.
Offer it for publication instead: the proxy forwards calls for the offered Point's services to the extension without decoding them.
For example, a naming Point that the daemon calls needs `ClientPoint`, while a job API that only external tools call needs only an offer.

### Publishing an ordinary Point
Expand Down Expand Up @@ -241,7 +241,7 @@ Providers: []extensions.Provider{
}
```

The Host drops publication by default.
The Host drops offers by default.
Allow an offer only through explicit policy:

```go
Expand All @@ -256,27 +256,53 @@ _, err := host.New(ctx, host.WithProviderPolicy(host.PointPolicyFunc(func(identi

Publication authorization uses `servicev0.Point.ID()` and receives the host-attested identity.
Internal provider admission uses the same policy with ordinary Point IDs.
A nil policy allows every internally wired provider and drops all publication.
A nil policy allows every internally wired provider and drops all offers.
A non-nil policy decides each use by identity and Point:

- `Allow` admits the provider or publication.
- `Drop` omits an ordinary provider and its offer.
- `Reject` fails Host construction and preserves its error cause.

A zero result and a typed nil `PointPolicyFunc` reject the request.
The `servicev0` offer marker itself is exempt from provider admission.
The `servicev0` offer marker goes through the same admission and is limited to offered Points whose providers policy kept.
Offered-only process Points have no internal provider, so the policy sees them only through `servicev0.Point.ID()`.

If policy drops every ordinary provider of an extension, the Host skips the extension instead of initializing it.
A launched extension stays loaded while it publishes an offered-only Point, because external callers still reach that Point through the proxy.
A launched extension stays loaded while its offer of an offered-only Point is admitted, because external callers still reach that Point through the proxy.
For example, when policy drops the naming Point an extension provides to the daemon but allows publication, the extension keeps serving its offered-only job API.

For an in-process extension, supply generated adapters at Host composition:
Extension code is the same whether it runs in-process or as a separate binary, and admitted offers resolve through `servicev0.Point` either way.
Only the embedder's wiring differs, because an in-process provider is a Go value while a launched extension already serves gRPC over its connection:

```go
host.WithPointServers(greeterpb.ServerPoint),
var backends []grpcproxy.Backend
for _, offer := range h.Providers(servicev0.Point.ID()) {
id := offer.Identity.ID
points := offer.Impl.(servicev0.Provider).OfferedPoints()
if conn, ok := h.Conn(id); ok {
// Launched: route only the services reported for each admitted offer.
backend := grpcproxy.Backend{ID: string(id), Conn: conn}
for _, point := range points {
backend.Services = append(backend.Services, h.OfferedServices(point, id)...)
}
backends = append(backends, backend)
continue
}
// In-process: serve the provider with its generated adapter.
for _, point := range points {
impl, err := h.Provider(point, id)
// ...
err = servicegrpc.Register(srv, serverPoints[point], impl)
// ...
}
}
routes, err := grpcproxy.BuildRoutes(backends, reserved)
proxy := grpcproxy.New(routes)
```

`serverPoints` maps each Point the embedder publishes to its generated `ServerPoint`, such as `greeterpb.ServerPoint`.
Pass daemon-owned service names as `reserved` so an extension cannot shadow them.

A separate binary passes every ordinary provider's generated `ServerPoint` to the SDK, whether the Point is internal, offered, or both:

```go
Expand All @@ -291,7 +317,8 @@ reply, err := client.Greet(ctx, &greeterv0.HelloRequest{Name: "world"})
```

The current backend is gRPC.
For a launched extension, the SDK registers the generated service, the daemon records its fully qualified name, and the proxy forwards the raw gRPC stream, including metadata and status.
For a launched extension, use the reported service names rather than inferring a proto package from the Point ID.
The proxy forwards the raw gRPC stream, including metadata and status.
Arbitrary raw gRPC publication is not part of the extension API.

## Writing an extension
Expand Down Expand Up @@ -502,7 +529,7 @@ See the [lifecycle limitations](./DESIGN.md#resolution-ordering-and-lifecycle).
- [ ] Register every ordinary provider's `ServerPoint` in a separate binary.
- [ ] Implement every published API as an ordinary `Point.Provide(impl)` provider.
- [ ] Offer selected implemented Points with `servicev0.Offer`.
- [ ] Add Host `WithProviderPolicy` and in-process `WithPointServers` wiring as needed.
- [ ] Add Host `WithProviderPolicy`, and expose admitted offers resolved through `servicev0.Point`.
- [ ] Keep handshake output on stdout and logs on stderr.
- [ ] Install one correctly named, non-world-writable binary (not a symlink) in the trusted extension directory.

Expand All @@ -518,6 +545,6 @@ See the [lifecycle limitations](./DESIGN.md#resolution-ordering-and-lifecycle).
- Supply configuration by extension id, or by the id without its version for every version, with `host.WithExtensionConfig`.
- Resolve Points through the Host and call their contract helpers.
- Restrict internal providers with `host.WithProviderPolicy` using ordinary Point IDs.
- Offer implemented Points with `servicev0.Offer`, authorize publication through policy on `servicev0.Point.ID()`, and supply `host.WithPointServers` for in-process offers.
- Offer implemented Points with `servicev0.Offer`, authorize publication through policy on `servicev0.Point.ID()`, and expose admitted offers resolved through `servicev0.Point`.
- Call published Points with the generated `NewClient(hostConn)`.
- Release lifecycle resources with `Host.Shutdown`.
20 changes: 11 additions & 9 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ These names are distinct:
Socket routing uses the full service name, never the bare point id.
- **CLI / API route** is a separate client-facing name, such as `docker compose up` or a REST path; the framework does not generate it.

Publishing a point id means publishing the generated gRPC service in its proto package.
Publishing a point id means publishing the services registered for that point.
Socket routing takes the full service name.
`servicev0.Point` carries the extension's offers, while policy on `servicev0.Point.ID()` makes the final publication decision.

Expand Down Expand Up @@ -138,14 +138,16 @@ The same policy admits providers wired for internal Host use by ordinary Point I
An `Allow` decision keeps the provider use, `Drop` omits it, and `Reject` fails Host construction while preserving its error cause.
The zero result rejects as invalid or unspecified, and a typed nil `PointPolicyFunc` rejects with a generic cause.
An offered-only process Point without Host client wiring is governed only by the servicev0 policy decision.
The servicev0 marker is exempt from provider admission and controls publication of the extension's offered Points.
The servicev0 marker goes through the same admission and is limited to offered Points whose providers policy kept.
Admitted offers resolve through `servicev0.Point` for in-process and out-of-process extensions alike.
The Host rejects a launched extension's declaration if `OfferedPoints` is nonempty but `Providers` omits `servicev0.Point.ID()`.

An out-of-process extension passes every ordinary provider's generated `ServerPoint` to `sdk.Main` or `Server.Register`.
The SDK records service names under the ordinary Point and serializes offered Point IDs separately.
The Host may omit `ClientPoint` wiring for an offered-only Point; add it when the daemon also calls that Point internally.

For in-process offers, Host composition supplies generated adapters through `WithPointServers`.
The Host resolves the implementation from the same extension, applies policy, and preflights daemon-reserved, process, and in-process service name collisions before registration.
The embedder decides how to expose each offered Point.
For an in-process offer, it resolves the provider from the same extension and serves it with the generated `ServerPoint`, for example through `servicegrpc.Register`.

External callers use the generated client directly over an existing host or proxy connection:

Expand All @@ -154,12 +156,12 @@ client := greeterpb.NewClient(hostConn)
reply, err := client.Greet(ctx, &greeterv0.HelloRequest{Name: "world"})
```

For an out-of-process extension, the SDK registers generated services on the extension server and reports their fully qualified names.
The daemon proxies matching calls by name and forwards the raw gRPC stream, including metadata and status.
For an out-of-process extension, the SDK registers generated services on the extension server.
The daemon uses `Host.OfferedServices` to route the exact gRPC service names reported for each admitted Point.
This also works for services registered in a proto package other than the Point ID and does not expose unrelated services in the same package.
`grpcproxy` forwards the raw gRPC stream, including metadata and status.

Generated service names are captured from generated registration, not listed manually.
The extension must provide the shared publication point before publishing its service inventory.
A name cannot collide with another extension or a service already served by the daemon; collision fails startup rather than shadowing the existing service.
`grpcproxy.BuildRoutes` rejects a package or service that another backend or a reserved daemon service already occupies; collision fails startup rather than shadowing the existing service.

The embedding application chooses the gRPC endpoint used for publication; the framework does not create a Docker API endpoint.
An exposed service must enforce any access control it needs.
Expand Down
114 changes: 99 additions & 15 deletions grpcproxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,44 +47,113 @@ func (passthroughCodec) Unmarshal(data mem.BufferSlice, v any) error {
return nil
}

// Proxy forwards calls for a set of gRPC service names.
// Proxy forwards calls for a set of gRPC service names and proto packages.
type Proxy struct {
routes map[string]grpc.ClientConnInterface
routes Routes
server *grpc.Server
}

// Backend identifies a gRPC backend and the services it serves.
// Packages route every service in each proto package to the backend.
type Backend struct {
ID string
Conn grpc.ClientConnInterface
Services []string
Packages []string
}

// BuildRoutes assembles a service-name to connection map, rejecting conflicts.
// Routes maps gRPC service names and proto packages to backend connections.
// An exact service route takes precedence over its package.
type Routes struct {
Services map[string]grpc.ClientConnInterface
Packages map[string]grpc.ClientConnInterface
}

// Len reports the number of routes.
func (r Routes) Len() int {
return len(r.Services) + len(r.Packages)
}

func (r Routes) lookup(service string) (grpc.ClientConnInterface, bool) {
if conn, ok := r.Services[service]; ok {
return conn, true
}

conn, ok := r.Packages[packageName(service)]

return conn, ok
}

// BuildRoutes assembles service and package routes, rejecting conflicts.
// A package conflicts with reserved services and with services of other
// backends inside it.
// No route may reach the SDK runtime package, which every SDK extension serves
// on its connection.
// Backends are processed in ID order for deterministic conflict errors.
func BuildRoutes(backends []Backend, reserved map[string]struct{}) (map[string]grpc.ClientConnInterface, error) {
func BuildRoutes(backends []Backend, reserved map[string]struct{}) (Routes, error) {
sorted := append([]Backend(nil), backends...)
slices.SortFunc(sorted, func(a, b Backend) int { return strings.Compare(a.ID, b.ID) })

routes := map[string]grpc.ClientConnInterface{}
owner := map[string]string{}
routes := Routes{Services: map[string]grpc.ClientConnInterface{}, Packages: map[string]grpc.ClientConnInterface{}}
serviceOwner := map[string]string{}
packageOwner := map[string]string{}
Comment thread
vvoland marked this conversation as resolved.
Resolved

for _, be := range sorted {
for _, svc := range be.Services {
if packageName(svc) == runtimePackage {
return Routes{}, fmt.Errorf("grpcproxy: backend %q cannot expose gRPC service %q: package %q is the SDK runtime", be.ID, svc, runtimePackage)
}

if _, taken := reserved[svc]; taken {
return nil, fmt.Errorf("grpcproxy: backend %q cannot expose gRPC service %q: that name is reserved by an already-served service", be.ID, svc)
return Routes{}, fmt.Errorf("grpcproxy: backend %q cannot expose gRPC service %q: that name is reserved by an already-served service", be.ID, svc)
}

if other, taken := serviceOwner[svc]; taken {
return Routes{}, fmt.Errorf("grpcproxy: backends %q and %q both expose gRPC service %q", other, be.ID, svc)
}

if other, taken := packageOwner[packageName(svc)]; taken && other != be.ID {
return Routes{}, fmt.Errorf("grpcproxy: backend %q cannot expose gRPC service %q: backend %q exposes its package", be.ID, svc, other)
}

serviceOwner[svc] = be.ID
routes.Services[svc] = be.Conn
}

for _, pkg := range be.Packages {
if pkg == "" {
return Routes{}, fmt.Errorf("grpcproxy: backend %q cannot expose an empty package", be.ID)
}
if other, taken := owner[svc]; taken {
return nil, fmt.Errorf("grpcproxy: backends %q and %q both expose gRPC service %q", other, be.ID, svc)

if pkg == runtimePackage {
return Routes{}, fmt.Errorf("grpcproxy: backend %q cannot expose package %q: it is the SDK runtime", be.ID, pkg)
}
owner[svc] = be.ID
routes[svc] = be.Conn

for svc := range reserved {
if packageName(svc) == pkg {
return Routes{}, fmt.Errorf("grpcproxy: backend %q cannot expose package %q: it contains already-served service %q", be.ID, pkg, svc)
}
}

if other, taken := packageOwner[pkg]; taken {
return Routes{}, fmt.Errorf("grpcproxy: backends %q and %q both expose package %q", other, be.ID, pkg)
}

for svc, other := range serviceOwner {
if other != be.ID && packageName(svc) == pkg {
return Routes{}, fmt.Errorf("grpcproxy: backend %q cannot expose package %q: backend %q exposes its service %q", be.ID, pkg, other, svc)
}
}

packageOwner[pkg] = be.ID
routes.Packages[pkg] = be.Conn
}
}
return routes, nil
}

// New builds a proxy that forwards each service in routes to its connection.
func New(routes map[string]grpc.ClientConnInterface) *Proxy {
// New builds a proxy that forwards each route to its connection.
func New(routes Routes) *Proxy {
p := &Proxy{routes: routes}
p.server = grpc.NewServer(
grpc.ForceServerCodecV2(passthroughCodec{}),
Expand All @@ -95,7 +164,7 @@ func New(routes map[string]grpc.ClientConnInterface) *Proxy {

// Handles reports whether the proxy forwards the gRPC service.
func (p *Proxy) Handles(service string) bool {
_, ok := p.routes[service]
_, ok := p.routes.lookup(service)
return ok
}

Expand All @@ -119,7 +188,8 @@ func (p *Proxy) forward(_ any, serverStream grpc.ServerStream) error {
if !ok {
return status.Error(codes.Internal, "grpcproxy: no method in stream")
}
conn, ok := p.routes[serviceName(fullMethod)]

conn, ok := p.routes.lookup(serviceName(fullMethod))
if !ok {
return status.Errorf(codes.Unimplemented, "grpcproxy: no backend for %s", fullMethod)
}
Expand Down Expand Up @@ -223,3 +293,17 @@ func serviceName(fullMethod string) string {
}
return s
}

// runtimePackage is the proto package of the SDK runtime service
// (sdk/sdkapi), which serves the Host's lifecycle calls on every extension
// connection.
const runtimePackage = "moby.extension.runtime.v1"

// packageName extracts the proto package from a "pkg.Service" name.
func packageName(service string) string {
if i := strings.LastIndex(service, "."); i >= 0 {
return service[:i]
}

return ""
}
Loading