diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 42a009f..27ee75b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,6 +66,9 @@ jobs: moby-integration: runs-on: ubuntu-latest timeout-minutes: 30 + permissions: + contents: read + pull-requests: read steps: - name: Checkout extensions @@ -73,12 +76,32 @@ jobs: 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=" 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 diff --git a/README.md b/README.md index dd32054..b565d55 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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. diff --git a/core.go b/core.go index 32c71ac..9f8ddcf 100644 --- a/core.go +++ b/core.go @@ -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 { diff --git a/docs/AUTHORING.md b/docs/AUTHORING.md index 3fc7e0a..0bb1f81 100644 --- a/docs/AUTHORING.md +++ b/docs/AUTHORING.md @@ -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 @@ -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 @@ -256,7 +256,7 @@ _, 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. @@ -264,19 +264,45 @@ A non-nil policy decides each use by identity and Point: - `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 @@ -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 @@ -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. @@ -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`. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 3782dec..6102b48 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -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. @@ -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: @@ -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. diff --git a/grpcproxy/proxy.go b/grpcproxy/proxy.go index a597e99..49c6a42 100644 --- a/grpcproxy/proxy.go +++ b/grpcproxy/proxy.go @@ -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{} + 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{}), @@ -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 } @@ -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) } @@ -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 "" +} diff --git a/grpcproxy/proxy_test.go b/grpcproxy/proxy_test.go index 1e93069..7268292 100644 --- a/grpcproxy/proxy_test.go +++ b/grpcproxy/proxy_test.go @@ -54,7 +54,7 @@ func TestProxyServerStreaming(t *testing.T) { backendSock := filepath.Join(shortTempDir(t), "backend.sock") backendConn := serve(t, backendSock, func(s *grpc.Server) { s.RegisterService(&streamerDesc, nil) }) - proxy := grpcproxy.New(map[string]grpc.ClientConnInterface{"test.Streamer": backendConn}) + proxy := grpcproxy.New(grpcproxy.Routes{Services: map[string]grpc.ClientConnInterface{"test.Streamer": backendConn}}) proxySock := filepath.Join(shortTempDir(t), "proxy.sock") lis, err := net.Listen("unix", proxySock) assert.NilError(t, err) @@ -110,6 +110,37 @@ func TestProxyUnary(t *testing.T) { assert.Equal(t, reply.GetValue(), "echo:hi") } +// TestProxyRoutesPackage verifies a package route forwards every service in +// that package without listing service names, and nothing outside it. +func TestProxyRoutesPackage(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + + backendConn := serve(t, filepath.Join(shortTempDir(t), "backend.sock"), func(s *grpc.Server) { s.RegisterService(&unaryDesc, nil) }) + proxy := grpcproxy.New(grpcproxy.Routes{Packages: map[string]grpc.ClientConnInterface{"test": backendConn}}) + assert.Check(t, proxy.Handles("test.Unary")) + assert.Check(t, !proxy.Handles("test.sub.Unary")) + assert.Check(t, !proxy.Handles("other.Unary")) + + proxySock := filepath.Join(shortTempDir(t), "proxy.sock") + lis, err := net.Listen("unix", proxySock) + assert.NilError(t, err) + + go func() { _ = proxy.Serve(lis) }() + + t.Cleanup(proxy.Stop) + + clientConn, err := grpc.NewClient("unix:"+proxySock, grpc.WithTransportCredentials(insecure.NewCredentials())) + assert.NilError(t, err) + t.Cleanup(func() { assert.NilError(t, clientConn.Close()) }) + + var reply wrapperspb.StringValue + assert.NilError(t, clientConn.Invoke(ctx, "/test.Unary/Echo", wrapperspb.String("hi"), &reply)) + assert.Equal(t, reply.GetValue(), "echo:hi") + err = clientConn.Invoke(ctx, "/other.Unary/Echo", wrapperspb.String("hi"), &reply) + assert.Equal(t, status.Code(err), codes.Unimplemented) +} + var statusDesc = grpc.ServiceDesc{ ServiceName: "test.Status", HandlerType: (*any)(nil), @@ -219,7 +250,7 @@ func startProxy(t *testing.T, service string, register func(*grpc.Server)) *grpc t.Helper() backendConn := serve(t, filepath.Join(shortTempDir(t), "backend.sock"), register) - proxy := grpcproxy.New(map[string]grpc.ClientConnInterface{service: backendConn}) + proxy := grpcproxy.New(grpcproxy.Routes{Services: map[string]grpc.ClientConnInterface{service: backendConn}}) proxySock := filepath.Join(shortTempDir(t), "proxy.sock") lis, err := net.Listen("unix", proxySock) assert.NilError(t, err) diff --git a/grpcproxy/routes_test.go b/grpcproxy/routes_test.go index e2c42ac..07e183b 100644 --- a/grpcproxy/routes_test.go +++ b/grpcproxy/routes_test.go @@ -20,10 +20,10 @@ func TestBuildRoutesDisjoint(t *testing.T) { {ID: "ext.b", Conn: b, Services: []string{"b.Svc"}}, }, nil) assert.NilError(t, err) - assert.Equal(t, len(routes), 3) - assert.Equal(t, routes["a.Svc1"], grpc.ClientConnInterface(a)) - assert.Equal(t, routes["a.Svc2"], grpc.ClientConnInterface(a)) - assert.Equal(t, routes["b.Svc"], grpc.ClientConnInterface(b)) + assert.Equal(t, routes.Len(), 3) + assert.Equal(t, routes.Services["a.Svc1"], grpc.ClientConnInterface(a)) + assert.Equal(t, routes.Services["a.Svc2"], grpc.ClientConnInterface(a)) + assert.Equal(t, routes.Services["b.Svc"], grpc.ClientConnInterface(b)) } func TestBuildRoutesRejectsExtensionConflict(t *testing.T) { @@ -46,5 +46,80 @@ func TestBuildRoutesRejectsReservedConflict(t *testing.T) { func TestBuildRoutesEmpty(t *testing.T) { routes, err := BuildRoutes(nil, nil) assert.NilError(t, err) - assert.Equal(t, len(routes), 0) + assert.Equal(t, routes.Len(), 0) +} + +func TestBuildRoutesPackages(t *testing.T) { + a := &connStub{} + routes, err := BuildRoutes([]Backend{ + {ID: "ext.a", Conn: a, Services: []string{"a.v1.Extra"}, Packages: []string{"a.v1"}}, + }, nil) + assert.NilError(t, err, "a backend may list services inside its own package") + assert.Equal(t, routes.Packages["a.v1"], grpc.ClientConnInterface(a)) + + for _, tc := range []struct { + name string + backends []Backend + reserved map[string]struct{} + want string + }{ + { + name: "runtime service", + backends: []Backend{ + {ID: "ext.a", Services: []string{"moby.extension.runtime.v1.Extension"}}, + }, + want: `backend "ext.a" cannot expose gRPC service "moby.extension.runtime.v1.Extension"`, + }, + { + name: "runtime package", + backends: []Backend{ + {ID: "ext.a", Packages: []string{"moby.extension.runtime.v1"}}, + }, + want: `backend "ext.a" cannot expose package "moby.extension.runtime.v1"`, + }, + { + name: "same package", + backends: []Backend{ + {ID: "ext.z", Conn: &connStub{}, Packages: []string{"shared.v1"}}, + {ID: "ext.a", Conn: &connStub{}, Packages: []string{"shared.v1"}}, + }, + want: `backends "ext.a" and "ext.z" both expose package "shared.v1"`, + }, + { + name: "package over another backend's service", + backends: []Backend{ + {ID: "ext.a", Conn: &connStub{}, Services: []string{"shared.v1.Svc"}}, + {ID: "ext.z", Conn: &connStub{}, Packages: []string{"shared.v1"}}, + }, + want: `backend "ext.z" cannot expose package "shared.v1": backend "ext.a" exposes its service "shared.v1.Svc"`, + }, + { + name: "service inside another backend's package", + backends: []Backend{ + {ID: "ext.a", Conn: &connStub{}, Packages: []string{"shared.v1"}}, + {ID: "ext.z", Conn: &connStub{}, Services: []string{"shared.v1.Svc"}}, + }, + want: `backend "ext.z" cannot expose gRPC service "shared.v1.Svc": backend "ext.a" exposes its package`, + }, + { + name: "package containing a reserved service", + backends: []Backend{ + {ID: "ext.evil", Conn: &connStub{}, Packages: []string{"moby.buildkit.v1"}}, + }, + reserved: map[string]struct{}{"moby.buildkit.v1.Control": {}}, + want: `backend "ext.evil" cannot expose package "moby.buildkit.v1": it contains already-served service "moby.buildkit.v1.Control"`, + }, + { + name: "empty package", + backends: []Backend{ + {ID: "ext.a", Conn: &connStub{}, Packages: []string{""}}, + }, + want: `backend "ext.a" cannot expose an empty package`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := BuildRoutes(tc.backends, tc.reserved) + assert.ErrorContains(t, err, tc.want) + }) + } } diff --git a/host/host.go b/host/host.go index b439a5b..9d73f96 100644 --- a/host/host.go +++ b/host/host.go @@ -23,7 +23,6 @@ import ( "github.com/moby/extensions/internal/broker" "github.com/moby/extensions/internal/launcher" "github.com/moby/extensions/serverpoint" - "github.com/moby/extensions/servicegrpc" "google.golang.org/grpc" ) @@ -85,9 +84,10 @@ func (result PointPolicyResult) resolve() (pointPolicyAction, error) { } // PointPolicy decides whether an extension identity may provide a Point. -// A decision on servicev0.Point.ID() controls publication of offered points -// whose providers were not dropped by policy. -// A nil policy allows ordinary providers and drops publication. +// A decision on servicev0.Point.ID() controls whether the extension's offers, +// limited to points whose providers were not dropped, resolve through +// servicev0.Point. +// A nil policy allows ordinary providers and drops offers. type PointPolicy interface { Decide(identity extensions.ExtensionIdentity, point extensions.PointID) PointPolicyResult } @@ -121,8 +121,6 @@ type options struct { dirs []string clientProviders []clientpoint.Registration providerPolicy PointPolicy - pointServers []serverpoint.Registration - reservedServices []string extensionConfig map[extensions.ExtensionID]extensions.Config dependencyProviders []serverpoint.Registration } @@ -162,32 +160,14 @@ func WithClientProviders(providers ...clientpoint.Registration) Option { } // WithProviderPolicy sets the policy deciding which providers are admitted. -// A decision on servicev0.Point.ID() controls publication. -// A nil policy admits all internally wired providers but drops publication. +// A decision on servicev0.Point.ID() controls offers. +// A nil policy admits all internally wired providers but drops offers. func WithProviderPolicy(policy PointPolicy) Option { return optionFunc(func(options *options) { options.providerPolicy = policy }) } -// WithPointServers adds generated adapters available for allowed in-process -// offers. -func WithPointServers(servers ...serverpoint.Registration) Option { - servers = append([]serverpoint.Registration(nil), servers...) - return optionFunc(func(options *options) { - options.pointServers = append(options.pointServers, servers...) - }) -} - -// WithReservedServices adds daemon-owned gRPC service names that extensions -// cannot publish. -func WithReservedServices(services ...string) Option { - services = append([]string(nil), services...) - return optionFunc(func(options *options) { - options.reservedServices = append(options.reservedServices, services...) - }) -} - // WithExtensionConfig sets configuration keyed by extension id. // A key without the version, such as org.example.myext, applies to every // version of that extension; a key with the full id takes precedence. @@ -216,19 +196,19 @@ func WithDependencyProviders(providers ...serverpoint.Registration) Option { // Host runs extensions and resolves their point providers. type Host struct { - broker *broker.Broker - // conns holds connections to launched extensions for socket proxying. - conns map[extensions.ExtensionID]grpc.ClientConnInterface + broker *broker.Broker + processes map[extensions.ExtensionID]processBackend // loaded owns resources acquired for executable extensions in load order. loaded []loadedExtension - // publishedServices contains only services approved by Host policy. - publishedServices map[extensions.ExtensionID]map[extensions.PointID][]string - // inProcessServices are approved and prevalidated for daemon registration. - inProcessServices []servicegrpc.Service // callback serves launched extensions' declared dependencies. callback *grpc.Server } +type processBackend struct { + conn grpc.ClientConnInterface + services map[extensions.PointID][]string +} + type loadedExtension struct { identity extensions.ExtensionIdentity extension extensions.Extension @@ -240,14 +220,6 @@ type registeredExtension struct { providers []extensions.Provider } -type publicationState struct { - policy PointPolicy - servers map[extensions.PointID]serverpoint.Registration - published map[extensions.ExtensionID]map[extensions.PointID][]string - owners map[string]extensions.ExtensionID - reserved map[string]bool -} - // hostedExtension is the runtime-neutral declaration and lifecycle surface // needed to adapt an externally hosted extension to the broker. type hostedExtension struct { @@ -263,28 +235,15 @@ type hostedExtension struct { // Conn returns the gRPC connection to a launched extension. func (h *Host) Conn(extension extensions.ExtensionID) (grpc.ClientConnInterface, bool) { - conn, ok := h.conns[extension] - return conn, ok -} - -// PublishedServicesForPoint returns process service names approved for external -// publication under point. -func (h *Host) PublishedServicesForPoint(point extensions.PointID) map[extensions.ExtensionID][]string { - out := make(map[extensions.ExtensionID][]string) - for id, services := range h.publishedServices { - if names := services[point]; len(names) > 0 { - out[id] = append([]string(nil), names...) - } - } - return out + process, ok := h.processes[extension] + return process.conn, ok } -// RegisterInProcessServices installs all policy-approved in-process Point -// services on registrar. -func (h *Host) RegisterInProcessServices(registrar grpc.ServiceRegistrar) { - for _, service := range h.inProcessServices { - service.Register(registrar) - } +// OfferedServices returns the gRPC service names for one admitted offer from a +// launched extension. +// It returns nil for in-process extensions and points not offered or admitted. +func (h *Host) OfferedServices(point extensions.PointID, extension extensions.ExtensionID) []string { + return slices.Clone(h.processes[extension].services[point]) } // New registers, launches, and initializes the configured extensions. It tears @@ -302,31 +261,16 @@ func New(ctx context.Context, optionList ...Option) (_ *Host, retErr error) { if err != nil { return nil, err } - pointServers, err := serverPointMap(opts.pointServers) - if err != nil { - return nil, err - } - reservedServices := make(map[string]bool, len(opts.reservedServices)) - for _, service := range opts.reservedServices { - if service == "" { - return nil, errors.New("reserved gRPC service name is empty") - } - reservedServices[service] = true - } + policy := opts.providerPolicy b := broker.New() - conns := make(map[extensions.ExtensionID]grpc.ClientConnInterface) - var loaded []loadedExtension - var registered []registeredExtension - publication := publicationState{ - policy: policy, - servers: pointServers, - published: make(map[extensions.ExtensionID]map[extensions.PointID][]string), - owners: make(map[string]extensions.ExtensionID), - reserved: reservedServices, - } - var inProcessServices []servicegrpc.Service - var callback *grpc.Server + processes := make(map[extensions.ExtensionID]processBackend) + + var ( + loaded []loadedExtension + registered []registeredExtension + callback *grpc.Server + ) // The broker only shuts down initialized extensions, so construction failures // also explicitly close loaded resources. defer func() { @@ -365,24 +309,16 @@ func New(ctx context.Context, optionList ...Option) (_ *Host, retErr error) { if err := broker.ValidateDeclaration(decl); err != nil { return nil, err } + // Dropping the extension must not hide malformed offers. + if err := validateInProcessOffers(decl); err != nil { + return nil, err + } + + admittedProviders = restrictOffers(decl.Providers, admittedProviders) if extensionFullyDropped(decl.Providers, admittedProviders) { - // Dropping the extension must not hide malformed offers or a policy rejection. - offered, err := offeredInProcessPoints(decl) - if err != nil { - return nil, err - } - if len(offered) > 0 { - if _, err := publicationPolicyAction(identity, policy); err != nil { - return nil, err - } - } continue } - services, err := collectInProcessPublications(identity, ext, &publication, droppedProviderPoints(decl.Providers, admittedProviders)) - if err != nil { - return nil, err - } - inProcessServices = append(inProcessServices, services...) + decl.Providers = admittedProviders if err := b.Register(identity, extensions.New(decl)); err != nil { return nil, err @@ -417,12 +353,11 @@ func New(ctx context.Context, optionList ...Option) (_ *Host, retErr error) { if err := broker.ValidateDeclaration(decl); err != nil { return nil, err } - if err := approveProcessPublications(identity, started, &publication, droppedProviderPoints(decl.Providers, admittedProviders)); err != nil { - return nil, err - } + + admittedProviders = restrictOffers(decl.Providers, admittedProviders) // Offered-only points have no provider for policy to drop, so they keep - // the process only when their offer is published. - if extensionFullyDropped(decl.Providers, admittedProviders) && len(publication.published[identity.ID]) == 0 { + // the process only while the offer is admitted. + if extensionFullyDropped(decl.Providers, admittedProviders) { // The process was launched for Describe; stop it before returning the host. if err := started.Close(context.WithoutCancel(ctx)); err != nil { return nil, fmt.Errorf("close dropped extension %q: %w", identity.ID, err) @@ -435,7 +370,7 @@ func New(ctx context.Context, optionList ...Option) (_ *Host, retErr error) { return nil, err } registered = append(registered, registeredExtension{identity: identity, providers: admittedProviders}) - conns[identity.ID] = started.Conn + processes[identity.ID] = processBackend{conn: started.Conn, services: admittedServices(admittedProviders, started.ProviderServices)} } } @@ -481,7 +416,27 @@ func New(ctx context.Context, optionList ...Option) (_ *Host, retErr error) { } log.G(ctx).WithFields(fields).Info("loaded extension") } - return &Host{broker: b, conns: conns, loaded: loaded, publishedServices: publication.published, inProcessServices: inProcessServices, callback: callback}, nil + + return &Host{broker: b, processes: processes, loaded: loaded, callback: callback}, nil +} + +func admittedServices(providers []extensions.Provider, inventory map[extensions.PointID][]string) map[extensions.PointID][]string { + for _, provider := range providers { + if provider.Point != servicev0.Point.ID() { + continue + } + + offered := provider.Impl.(servicev0.Provider).OfferedPoints() + + services := make(map[extensions.PointID][]string, len(offered)) + for _, point := range offered { + services[point] = inventory[point] + } + + return services + } + + return nil } func validateHostIdentity(identity extensions.ExtensionIdentity, decl extensions.Declaration) error { @@ -497,11 +452,12 @@ func validateHostIdentity(identity extensions.ExtensionIdentity, decl extensions func admitProviders(identity extensions.ExtensionIdentity, providers []extensions.Provider, policy PointPolicy) ([]extensions.Provider, error) { admitted := make([]extensions.Provider, 0, len(providers)) for _, provider := range providers { + result := Allow() if extensions.IsMetadataPoint(provider.Point) { - admitted = append(admitted, provider) - continue + // Offers stay private unless policy allows them. + result = Drop() } - result := Allow() + if policy != nil { result = policy.Decide(identity, provider.Point) } @@ -518,25 +474,10 @@ func admitProviders(identity extensions.ExtensionIdentity, providers []extension return admitted, nil } -// extensionFullyDropped ignores metadata providers and keeps extensions that -// declared no ordinary providers: policy had nothing to drop from them. +// extensionFullyDropped keeps extensions that declared no providers: policy had +// nothing to drop from them. func extensionFullyDropped(declared, admitted []extensions.Provider) bool { - hadProvider := false - for _, provider := range declared { - if !extensions.IsMetadataPoint(provider.Point) { - hadProvider = true - break - } - } - if !hadProvider { - return false - } - for _, provider := range admitted { - if !extensions.IsMetadataPoint(provider.Point) { - return false - } - } - return true + return len(declared) > 0 && len(admitted) == 0 } // droppedProviderPoints excludes offered-only process points, which have no @@ -555,103 +496,54 @@ func droppedProviderPoints(declared, admitted []extensions.Provider) map[extensi return dropped } -func approveProcessPublications(identity extensions.ExtensionIdentity, started *launcher.Launched, publication *publicationState, dropped map[extensions.PointID]bool) error { - if len(started.OfferedPoints) == 0 { - return nil - } - action, err := publicationPolicyAction(identity, publication.policy) - if err != nil { - return err - } - if action == pointPolicyActionDrop { - return nil - } - for _, point := range started.OfferedPoints { - if dropped[point] { +// restrictOffers limits the admitted servicev0 offer to points whose providers +// policy kept, removing the offer when none remain. +// Offered-only process points have no provider to drop and stay offered. +func restrictOffers(declared, admitted []extensions.Provider) []extensions.Provider { + dropped := droppedProviderPoints(declared, admitted) + + out := make([]extensions.Provider, 0, len(admitted)) + for _, provider := range admitted { + metadata, ok := provider.Impl.(servicev0.Provider) + if provider.Point != servicev0.Point.ID() || !ok { + out = append(out, provider) continue } - names := started.ProviderServices[point] - if len(names) == 0 { - return fmt.Errorf("extension %q offered point %q without a gRPC service", identity.ID, point) - } - for _, service := range names { - if publication.reserved[service] { - return fmt.Errorf("extension %q cannot publish reserved gRPC service %q", identity.ID, service) - } - if owner, exists := publication.owners[service]; exists { - return fmt.Errorf("extensions %q and %q both publish gRPC service %q", owner, identity.ID, service) + + var kept offers + + for _, point := range metadata.OfferedPoints() { + if !dropped[point] { + kept = append(kept, point) } - publication.owners[service] = identity.ID } - if publication.published[identity.ID] == nil { - publication.published[identity.ID] = make(map[extensions.PointID][]string) + + if len(kept) > 0 { + out = append(out, servicev0.Point.Provide(kept)) } - publication.published[identity.ID][point] = append([]string(nil), names...) } - return nil + + return out } -func collectInProcessPublications(identity extensions.ExtensionIdentity, ext extensions.Extension, publication *publicationState, dropped map[extensions.PointID]bool) ([]servicegrpc.Service, error) { - decl := ext.Declaration() - offered, err := offeredInProcessPoints(decl) - if err != nil { - return nil, err - } - if len(offered) == 0 { - return nil, nil - } - action, err := publicationPolicyAction(identity, publication.policy) - if err != nil { - return nil, err - } - if action == pointPolicyActionDrop { - return nil, nil - } +// offers implements servicev0.Provider for offers the host rebuilt. +type offers []extensions.PointID - providers := make(map[extensions.PointID]any, len(decl.Providers)) - for _, provider := range decl.Providers { - providers[provider.Point] = provider.Impl - } - var services []servicegrpc.Service - for _, point := range offered { - if dropped[point] { - continue - } - impl := providers[point] - registration, ok := publication.servers[point] - if !ok { - return nil, fmt.Errorf("extension %q: allowed in-process offer for point %q has no server registration", decl.ID, point) - } - service, err := servicegrpc.Adapt(registration, impl) - if err != nil { - return nil, fmt.Errorf("extension %q: publish point %q: %w", decl.ID, point, err) - } - if publication.reserved[service.Name] { - return nil, fmt.Errorf("extension %q cannot publish reserved gRPC service %q", decl.ID, service.Name) - } - if owner, exists := publication.owners[service.Name]; exists { - return nil, fmt.Errorf("extensions %q and %q both publish gRPC service %q", owner, decl.ID, service.Name) - } - publication.owners[service.Name] = decl.ID - services = append(services, service) - if publication.published[decl.ID] == nil { - publication.published[decl.ID] = make(map[extensions.PointID][]string) - } - publication.published[decl.ID][point] = []string{service.Name} - } - return services, nil +func (o offers) OfferedPoints() []extensions.PointID { + return slices.Clone(o) } -func offeredInProcessPoints(decl extensions.Declaration) ([]extensions.PointID, error) { +// validateInProcessOffers rejects malformed, duplicate, and unimplemented +// offers. +func validateInProcessOffers(decl extensions.Declaration) error { providers := make(map[extensions.PointID]any, len(decl.Providers)) for _, provider := range decl.Providers { if _, exists := providers[provider.Point]; exists { - return nil, fmt.Errorf("extension %q provides point %q more than once", decl.ID, provider.Point) + return fmt.Errorf("extension %q provides point %q more than once", decl.ID, provider.Point) } providers[provider.Point] = provider.Impl } - var offered []extensions.PointID seen := make(map[extensions.PointID]bool) for _, provider := range decl.Providers { if provider.Point != servicev0.Point.ID() { @@ -659,39 +551,26 @@ func offeredInProcessPoints(decl extensions.Declaration) ([]extensions.PointID, } metadata, ok := provider.Impl.(servicev0.Provider) if !ok { - return nil, fmt.Errorf("extension %q: point %q has incompatible offer metadata", decl.ID, provider.Point) + return fmt.Errorf("extension %q: point %q has incompatible offer metadata", decl.ID, provider.Point) } for _, point := range metadata.OfferedPoints() { if err := extensions.ValidatePointID(point); err != nil { - return nil, fmt.Errorf("extension %q: invalid offered point: %w", decl.ID, err) + return fmt.Errorf("extension %q: invalid offered point: %w", decl.ID, err) } if point == servicev0.Point.ID() { - return nil, fmt.Errorf("extension %q: publication metadata point %q cannot offer itself", decl.ID, point) + return fmt.Errorf("extension %q: publication metadata point %q cannot offer itself", decl.ID, point) } if seen[point] { - return nil, fmt.Errorf("extension %q: point %q is offered more than once", decl.ID, point) + return fmt.Errorf("extension %q: point %q is offered more than once", decl.ID, point) } seen[point] = true - _, implemented := providers[point] - if !implemented { - return nil, fmt.Errorf("extension %q: offered point %q is not implemented", decl.ID, point) + if _, implemented := providers[point]; !implemented { + return fmt.Errorf("extension %q: offered point %q is not implemented", decl.ID, point) } - offered = append(offered, point) } } - return offered, nil -} -func publicationPolicyAction(identity extensions.ExtensionIdentity, policy PointPolicy) (pointPolicyAction, error) { - result := Drop() - if policy != nil { - result = policy.Decide(identity, servicev0.Point.ID()) - } - action, cause := result.resolve() - if action == pointPolicyActionReject { - return action, policyRejectionError("publish offered points", identity, servicev0.Point.ID(), cause) - } - return action, nil + return nil } func policyRejectionError(operation string, identity extensions.ExtensionIdentity, point extensions.PointID, cause error) error { @@ -813,20 +692,6 @@ func clientProviderMap(regs []clientpoint.Registration) (map[extensions.PointID] return m, nil } -func serverPointMap(regs []serverpoint.Registration) (map[extensions.PointID]serverpoint.Registration, error) { - servers := make(map[extensions.PointID]serverpoint.Registration, len(regs)) - for _, registration := range regs { - if registration.Point == "" || registration.Register == nil { - return nil, errors.New("incomplete in-process server registration") - } - if _, exists := servers[registration.Point]; exists { - return nil, fmt.Errorf("duplicate in-process server registration for point %q", registration.Point) - } - servers[registration.Point] = registration - } - return servers, nil -} - // hostedExtensionFromLaunched adapts process declaration and lifecycle fields to // the runtime-neutral hosted extension contract. func hostedExtensionFromLaunched(launched *launcher.Launched) hostedExtension { @@ -876,7 +741,11 @@ func extensionFromHosted(hosted hostedExtension, providers map[extensions.PointI } for _, point := range hosted.points { if point == servicev0.Point.ID() { - // Publication metadata has no in-daemon provider or client adapter. + // Offers resolve locally from the declaration. + // Keep an empty offer so policy still decides on it; restrictOffers + // removes it after admission. + decl.Providers = append(decl.Providers, servicev0.Point.Provide(offers(slices.Clone(hosted.offered)))) + continue } build, ok := providers[point] @@ -891,5 +760,6 @@ func extensionFromHosted(hosted hostedExtension, providers map[extensions.PointI provider := build(hosted.conn) decl.Providers = append(decl.Providers, provider) } + return extensions.New(decl), nil } diff --git a/host/host_internal_test.go b/host/host_internal_test.go index 67efd42..7accc65 100644 --- a/host/host_internal_test.go +++ b/host/host_internal_test.go @@ -131,6 +131,18 @@ func TestExtensionFromHostedRejectsUnsupportedPoints(t *testing.T) { offered: []extensions.PointID{offered}, }, providers) assert.NilError(t, err) + + got := ext.Declaration().Providers + assert.Equal(t, len(got), 2) + assert.Equal(t, got[1].Point, servicev0.Point.ID()) + assert.DeepEqual(t, got[1].Impl.(servicev0.Provider).OfferedPoints(), []extensions.PointID{offered}) + + // An empty offer still reaches policy admission. + ext, err = extensionFromHosted(hostedExtension{ + identity: executableIdentity("org.example.ext.v1"), + points: []extensions.PointID{servicev0.Point.ID()}, + }, providers) + assert.NilError(t, err) assert.Equal(t, len(ext.Declaration().Providers), 1) } @@ -535,7 +547,7 @@ func TestExtensionDroppedByPolicy(t *testing.T) { } // TestProviderAndPublicationPolicyPoints verifies that provider admission and -// publication use their respective Point IDs. +// offers use their respective Point IDs. func TestProviderAndPublicationPolicyPoints(t *testing.T) { const id = extensions.ExtensionID("org.example.offered.v1") const realPoint = extensions.PointID("org.example.internal.v1") @@ -547,20 +559,11 @@ func TestProviderAndPublicationPolicyPoints(t *testing.T) { servicev0.Offer(pointDef), }, }) - server := serverpoint.Registration{ - Point: realPoint, - Register: func(registrar grpc.ServiceRegistrar, impl any) { - registrar.RegisterService(&grpc.ServiceDesc{ - ServiceName: "example.API", - HandlerType: (*any)(nil), - }, impl) - }, - } + var policyPoints []extensions.PointID h, err := New(t.Context(), WithRuntimeDir(t.TempDir()), WithExtensions(ext), - WithPointServers(server), WithProviderPolicy(PointPolicyFunc(func(_ extensions.ExtensionIdentity, point extensions.PointID) PointPolicyResult { policyPoints = append(policyPoints, point) if point == realPoint { @@ -575,7 +578,9 @@ func TestProviderAndPublicationPolicyPoints(t *testing.T) { provider, err := h.Provider(realPoint, id) assert.NilError(t, err) assert.Equal(t, provider, struct{}{}) - assert.DeepEqual(t, h.PublishedServicesForPoint(realPoint), map[extensions.ExtensionID][]string{}) + + _, err = h.Provider(servicev0.Point.ID(), id) + assert.ErrorContains(t, err, "does not provide point") } // TestLaunchedExtensionCarriesShutdown verifies launched extensions participate @@ -810,187 +815,22 @@ func TestHostShutdownJoinsSemanticAndResourceErrors(t *testing.T) { assert.Assert(t, errors.Is(err, resourceErr)) } -func TestApproveProcessPublications(t *testing.T) { - const point = extensions.PointID("org.example.api.v1") - const otherPoint = extensions.PointID("org.example.other.v1") - launched := &launcher.Launched{ - ID: "org.example.first.v1", - OfferedPoints: []extensions.PointID{point, otherPoint}, - ProviderServices: map[extensions.PointID][]string{ - point: {"example.API"}, - otherPoint: {"example.Other"}, - }, - } - identity := executableIdentity(launched.ID) - allow := PointPolicyFunc(func(extensions.ExtensionIdentity, extensions.PointID) PointPolicyResult { return Allow() }) - drop := PointPolicyFunc(func(extensions.ExtensionIdentity, extensions.PointID) PointPolicyResult { return Drop() }) - newPublication := func(policy PointPolicy) *publicationState { - return &publicationState{ - policy: policy, - published: make(map[extensions.ExtensionID]map[extensions.PointID][]string), - owners: make(map[string]extensions.ExtensionID), - } - } - - t.Run("nil policy drops", func(t *testing.T) { - publication := newPublication(nil) - assert.NilError(t, approveProcessPublications(identity, launched, publication, nil)) - assert.Equal(t, len(publication.published), 0) - }) - - t.Run("nil function policy rejects", func(t *testing.T) { - publication := newPublication(PointPolicyFunc(nil)) - err := approveProcessPublications(identity, launched, publication, nil) - assert.ErrorContains(t, err, "point policy rejected the requested use") - assert.Equal(t, len(publication.published), 0) - }) - - t.Run("dropped offer is omitted", func(t *testing.T) { - publication := newPublication(drop) - assert.NilError(t, approveProcessPublications(identity, launched, publication, nil)) - assert.Equal(t, len(publication.published), 0) - }) - - t.Run("rejected offer fails with cause", func(t *testing.T) { - cause := errors.New("publication denied") - policy := PointPolicyFunc(func(extensions.ExtensionIdentity, extensions.PointID) PointPolicyResult { - return Reject(cause) - }) - err := approveProcessPublications(identity, launched, newPublication(policy), nil) - assert.Assert(t, errors.Is(err, cause)) - assert.ErrorContains(t, err, `publish offered points for extension "org.example.first.v1"`) - assert.ErrorContains(t, err, `origin "executable"`) - assert.ErrorContains(t, err, `point "org.mobyproject.extension.service.v0"`) - }) - - t.Run("allowed offers are copied", func(t *testing.T) { - publication := newPublication(allow) - assert.NilError(t, approveProcessPublications(identity, launched, publication, nil)) - assert.DeepEqual(t, publication.published[launched.ID][point], []string{"example.API"}) - assert.DeepEqual(t, publication.published[launched.ID][otherPoint], []string{"example.Other"}) - launched.ProviderServices[point][0] = "changed" - assert.DeepEqual(t, publication.published[launched.ID][point], []string{"example.API"}) - launched.ProviderServices[point][0] = "example.API" - }) - - t.Run("a dropped wired provider cannot publish but an offered-only point can", func(t *testing.T) { - publication := newPublication(allow) - dropped := droppedProviderPoints( - []extensions.Provider{{Point: point}, {Point: "org.example.internal.v1"}}, - []extensions.Provider{{Point: "org.example.internal.v1"}}, - ) - assert.NilError(t, approveProcessPublications(identity, launched, publication, dropped)) - assert.DeepEqual(t, publication.published[launched.ID], map[extensions.PointID][]string{ - otherPoint: {"example.Other"}, - }) - }) - - t.Run("provider policy is called once with service metadata", func(t *testing.T) { - var policyPoints []extensions.PointID - policy := PointPolicyFunc(func(_ extensions.ExtensionIdentity, point extensions.PointID) PointPolicyResult { - policyPoints = append(policyPoints, point) - if point == servicev0.Point.ID() { - return Allow() - } - return Drop() - }) - publication := newPublication(policy) - assert.NilError(t, approveProcessPublications(identity, launched, publication, nil)) - assert.DeepEqual(t, policyPoints, []extensions.PointID{servicev0.Point.ID()}) - assert.Equal(t, len(publication.published[launched.ID]), 2) - }) - - t.Run("missing service is rejected", func(t *testing.T) { - missing := &launcher.Launched{ID: launched.ID, OfferedPoints: []extensions.PointID{point}} - err := approveProcessPublications(identity, missing, newPublication(allow), nil) - assert.ErrorContains(t, err, "without a gRPC service") - }) - - t.Run("reserved service is rejected", func(t *testing.T) { - publication := newPublication(allow) - publication.reserved = map[string]bool{"example.API": true} - err := approveProcessPublications(identity, launched, publication, nil) - assert.ErrorContains(t, err, `cannot publish reserved gRPC service "example.API"`) - }) - - t.Run("service collision is rejected", func(t *testing.T) { - publication := newPublication(allow) - publication.owners["example.API"] = "org.example.other.v1" - err := approveProcessPublications(identity, launched, publication, nil) - assert.ErrorContains(t, err, `extensions "org.example.other.v1" and "org.example.first.v1" both publish gRPC service "example.API"`) - }) -} - -func TestInProcessPublicationValidation(t *testing.T) { - pointDefinition := extensions.DefinePoint[any]("org.example.api.v1") - point := pointDefinition.ID() - ext := extensions.New(extensions.Declaration{ - ID: "org.example.extension.v1", - Providers: []extensions.Provider{ - pointDefinition.Provide(struct{}{}), - servicev0.Offer(pointDefinition), - }, - }) - identity := extensions.ExtensionIdentity{ID: ext.Declaration().ID, Origin: extensions.ExtensionOrigin{Kind: extensions.ExtensionOriginBuiltin}} - allow := PointPolicyFunc(func(extensions.ExtensionIdentity, extensions.PointID) PointPolicyResult { return Allow() }) - drop := PointPolicyFunc(func(extensions.ExtensionIdentity, extensions.PointID) PointPolicyResult { return Drop() }) - newPublication := func(policy PointPolicy, servers map[extensions.PointID]serverpoint.Registration) *publicationState { - return &publicationState{ - policy: policy, - servers: servers, - published: make(map[extensions.ExtensionID]map[extensions.PointID][]string), - owners: make(map[string]extensions.ExtensionID), - } - } - - t.Run("dropped offer needs no adapter", func(t *testing.T) { - services, err := collectInProcessPublications(identity, ext, newPublication(drop, nil), nil) - assert.NilError(t, err) - assert.Equal(t, len(services), 0) - }) - - t.Run("allowed offer needs adapter", func(t *testing.T) { - _, err := collectInProcessPublications(identity, ext, newPublication(allow, nil), nil) - assert.ErrorContains(t, err, "has no server registration") - }) - - registration := serverpoint.Registration{ - Point: point, - Register: func(registrar grpc.ServiceRegistrar, impl any) { - registrar.RegisterService(&grpc.ServiceDesc{ServiceName: "example.API", HandlerType: (*any)(nil)}, impl) - }, - } - servers := map[extensions.PointID]serverpoint.Registration{point: registration} - - t.Run("reserved service is rejected", func(t *testing.T) { - publication := newPublication(allow, servers) - publication.reserved = map[string]bool{"example.API": true} - _, err := collectInProcessPublications(identity, ext, publication, nil) - assert.ErrorContains(t, err, `cannot publish reserved gRPC service "example.API"`) - }) +// TestRestrictOffersKeepsOfferedOnlyPoints verifies a process offer loses +// points whose wired provider policy dropped, but keeps offered-only points, +// which have no provider to drop. +func TestRestrictOffersKeepsOfferedOnlyPoints(t *testing.T) { + const ( + wired = extensions.PointID("org.example.wired.v1") + offeredOnly = extensions.PointID("org.example.offered.v1") + ) - t.Run("process service collision is rejected", func(t *testing.T) { - publication := newPublication(allow, servers) - publication.owners["example.API"] = "org.example.process.v1" - _, err := collectInProcessPublications(identity, ext, publication, nil) - assert.ErrorContains(t, err, `extensions "org.example.process.v1" and "org.example.extension.v1" both publish gRPC service "example.API"`) - }) + offer := servicev0.Point.Provide(offers{wired, offeredOnly}) + declared := []extensions.Provider{{Point: wired}, offer} - t.Run("in-process service collision is rejected", func(t *testing.T) { - publication := newPublication(allow, servers) - _, err := collectInProcessPublications(identity, ext, publication, nil) - assert.NilError(t, err) - other := extensions.New(extensions.Declaration{ - ID: "org.example.other.v1", - Providers: []extensions.Provider{ - pointDefinition.Provide(struct{}{}), - servicev0.Offer(pointDefinition), - }, - }) - otherIdentity := extensions.ExtensionIdentity{ID: other.Declaration().ID, Origin: extensions.ExtensionOrigin{Kind: extensions.ExtensionOriginBuiltin}} - _, err = collectInProcessPublications(otherIdentity, other, publication, nil) - assert.ErrorContains(t, err, `extensions "org.example.extension.v1" and "org.example.other.v1" both publish gRPC service "example.API"`) - }) + got := restrictOffers(declared, []extensions.Provider{offer}) + assert.Equal(t, len(got), 1) + assert.DeepEqual(t, got[0].Impl.(servicev0.Provider).OfferedPoints(), []extensions.PointID{offeredOnly}) + assert.Equal(t, len(restrictOffers(declared, nil)), 0) } func TestInProcessPublicationPolicy(t *testing.T) { @@ -1004,34 +844,24 @@ func TestInProcessPublicationPolicy(t *testing.T) { servicev0.Offer(pointDefinition), }, }) - server := serverpoint.Registration{ - Point: point, - Register: func(registrar grpc.ServiceRegistrar, impl any) { - registrar.RegisterService(&grpc.ServiceDesc{ServiceName: "example.API", HandlerType: (*any)(nil)}, impl) - }, - } - t.Run("nil policy keeps provider and drops publication", func(t *testing.T) { + t.Run("nil policy keeps provider and drops offers", func(t *testing.T) { h, err := New(t.Context(), WithRuntimeDir(t.TempDir()), WithExtensions(ext), - WithPointServers(server), ) assert.NilError(t, err) defer func() { assert.NilError(t, h.Shutdown(context.WithoutCancel(t.Context()))) }() assert.Equal(t, len(h.Providers(point)), 1) - assert.Equal(t, len(h.PublishedServicesForPoint(point)), 0) + assert.Equal(t, len(h.Providers(servicev0.Point.ID())), 0) }) - t.Run("dropping the only provider drops the extension entirely, publication included", func(t *testing.T) { - // Metadata providers are always admitted and must not rescue an - // extension from being fully dropped: the extension's only ordinary - // provider is dropped here, so publication must not happen either, - // even though the publication policy call itself would allow it. + t.Run("dropping the only provider drops the extension entirely, offers included", func(t *testing.T) { + // An allowed offer must not rescue an extension whose only offered + // provider is dropped. h, err := New(t.Context(), WithRuntimeDir(t.TempDir()), WithExtensions(ext), - WithPointServers(server), WithProviderPolicy(PointPolicyFunc(func(_ extensions.ExtensionIdentity, policyPoint extensions.PointID) PointPolicyResult { if policyPoint == servicev0.Point.ID() { return Allow() @@ -1042,7 +872,7 @@ func TestInProcessPublicationPolicy(t *testing.T) { assert.NilError(t, err) defer func() { assert.NilError(t, h.Shutdown(context.WithoutCancel(t.Context()))) }() assert.Equal(t, len(h.Providers(point)), 0) - assert.DeepEqual(t, h.PublishedServicesForPoint(point), map[extensions.ExtensionID][]string{}) + assert.Equal(t, len(h.Providers(servicev0.Point.ID())), 0) }) t.Run("dropping one provider keeps only the other offer", func(t *testing.T) { @@ -1056,22 +886,9 @@ func TestInProcessPublicationPolicy(t *testing.T) { servicev0.Offer(keptPoint, droppedPoint), }, }) - keptServer := serverpoint.Registration{ - Point: keptPoint.ID(), - Register: func(registrar grpc.ServiceRegistrar, impl any) { - registrar.RegisterService(&grpc.ServiceDesc{ServiceName: "example.Kept", HandlerType: (*any)(nil)}, impl) - }, - } - droppedServer := serverpoint.Registration{ - Point: droppedPoint.ID(), - Register: func(registrar grpc.ServiceRegistrar, impl any) { - registrar.RegisterService(&grpc.ServiceDesc{ServiceName: "example.Dropped", HandlerType: (*any)(nil)}, impl) - }, - } h, err := New(t.Context(), WithRuntimeDir(t.TempDir()), WithExtensions(partial), - WithPointServers(keptServer, droppedServer), WithProviderPolicy(PointPolicyFunc(func(_ extensions.ExtensionIdentity, policyPoint extensions.PointID) PointPolicyResult { if policyPoint == keptPoint.ID() || policyPoint == servicev0.Point.ID() { return Allow() @@ -1083,11 +900,12 @@ func TestInProcessPublicationPolicy(t *testing.T) { defer func() { assert.NilError(t, h.Shutdown(context.WithoutCancel(t.Context()))) }() assert.Equal(t, len(h.Providers(keptPoint.ID())), 1) assert.Equal(t, len(h.Providers(droppedPoint.ID())), 0) - assert.DeepEqual(t, h.PublishedServicesForPoint(keptPoint.ID()), map[extensions.ExtensionID][]string{id: {"example.Kept"}}) - assert.DeepEqual(t, h.PublishedServicesForPoint(droppedPoint.ID()), map[extensions.ExtensionID][]string{}) + offer, err := h.Provider(servicev0.Point.ID(), id) + assert.NilError(t, err) + assert.DeepEqual(t, offer.(servicev0.Provider).OfferedPoints(), []extensions.PointID{keptPoint.ID()}) }) - t.Run("rejecting publication still fails when the provider is dropped", func(t *testing.T) { + t.Run("rejecting offers still fails when the provider is dropped", func(t *testing.T) { cause := errors.New("publication denied") _, err := New(t.Context(), WithRuntimeDir(t.TempDir()), @@ -1107,7 +925,6 @@ func TestInProcessPublicationPolicy(t *testing.T) { h, err := New(t.Context(), WithRuntimeDir(t.TempDir()), WithExtensions(ext), - WithPointServers(server), WithProviderPolicy(PointPolicyFunc(func(_ extensions.ExtensionIdentity, policyPoint extensions.PointID) PointPolicyResult { if policyPoint == servicev0.Point.ID() { return Reject(cause) @@ -1117,27 +934,7 @@ func TestInProcessPublicationPolicy(t *testing.T) { ) assert.Assert(t, h == nil) assert.Assert(t, errors.Is(err, cause)) - assert.ErrorContains(t, err, `publish offered points for extension "org.example.extension.v1"`) - }) -} - -func TestPublishedServicesForPointUsesPolicyFilteredIndex(t *testing.T) { - const point = extensions.PointID("org.example.publication.v1") - h := &Host{publishedServices: map[extensions.ExtensionID]map[extensions.PointID][]string{ - "org.example.first.v1": { - point: {"example.First", "example.Second"}, - }, - "org.example.empty.v1": { - point: nil, - }, - }} - - got := h.PublishedServicesForPoint(point) - assert.DeepEqual(t, got, map[extensions.ExtensionID][]string{ - "org.example.first.v1": {"example.First", "example.Second"}, + assert.ErrorContains(t, err, `admit provider for extension "org.example.extension.v1"`) + assert.ErrorContains(t, err, `point "org.mobyproject.extension.service.v0"`) }) - got["org.example.first.v1"][0] = "changed" - assert.Equal(t, h.publishedServices["org.example.first.v1"][point][0], "example.First") - assert.DeepEqual(t, h.PublishedServicesForPoint("org.example.unknown.v1"), - map[extensions.ExtensionID][]string{}) } diff --git a/host/socket_test.go b/host/socket_test.go index f14a760..9f3cad2 100644 --- a/host/socket_test.go +++ b/host/socket_test.go @@ -18,16 +18,27 @@ import ( servicev0 "github.com/moby/extensions/extpoints/service/v0" "github.com/moby/extensions/grpcproxy" "github.com/moby/extensions/host" - echov1 "github.com/moby/extensions/internal/launcher/echo/v1" echopb "github.com/moby/extensions/internal/launcher/echo/v1/protogen" + "github.com/moby/extensions/serverpoint" + "github.com/moby/extensions/servicegrpc" "github.com/moby/extensions/testdata/greeter" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "gotest.tools/v3/assert" ) +// offeredPoints returns the points each extension offers through servicev0. +func offeredPoints(h *host.Host) map[extensions.ExtensionID][]extensions.PointID { + out := map[extensions.ExtensionID][]extensions.PointID{} + for _, provider := range h.Providers(servicev0.Point.ID()) { + out[provider.Identity.ID] = provider.Impl.(servicev0.Provider).OfferedPoints() + } + + return out +} + // TestPointSocketExposure verifies an out-of-process published Point is -// reachable by name through a proxy. +// reachable when its gRPC service lives outside the Point ID's package. func TestPointSocketExposure(t *testing.T) { if testing.Short() { t.Skip("builds and launches a helper binary") @@ -69,24 +80,34 @@ func TestPointSocketExposure(t *testing.T) { }) assert.DeepEqual(t, policyPoints, []extensions.PointID{servicev0.Point.ID()}) - services := h.PublishedServicesForPoint(greeterv0.Point.ID()) - assert.DeepEqual(t, services, map[extensions.ExtensionID][]string{ - greeter.ID: {"org.mobyproject.extension.example.greeter.v0.Greeter"}, + offered := offeredPoints(h) + assert.DeepEqual(t, offered, map[extensions.ExtensionID][]extensions.PointID{ + greeter.ID: {greeter.Point.ID()}, }) - routes := map[string]grpc.ClientConnInterface{} - for ext, names := range services { + + var backends []grpcproxy.Backend + + for ext, points := range offered { conn, ok := h.Conn(ext) - assert.Check(t, ok, "no connection for extension %q", ext) - for _, name := range names { - routes[name] = conn + assert.Assert(t, ok, "no connection for extension %q", ext) + + backend := grpcproxy.Backend{ID: string(ext), Conn: conn} + for _, point := range points { + backend.Services = append(backend.Services, h.OfferedServices(point, ext)...) } + + backends = append(backends, backend) } - assert.Check(t, routes["org.mobyproject.extension.example.greeter.v0.Greeter"] != nil) + + routes, err := grpcproxy.BuildRoutes(backends, nil) + assert.NilError(t, err) sock := filepath.Join(shortTempDir(t), "api.sock") lis, err := net.Listen("unix", sock) assert.NilError(t, err) proxy := grpcproxy.New(routes) + + assert.Check(t, !proxy.Handles("org.mobyproject.extension.example.greeter.v0.Other")) go func() { _ = proxy.Serve(lis) }() defer proxy.Stop() @@ -125,7 +146,8 @@ func TestProcessOfferIsDroppedByDefault(t *testing.T) { assert.NilError(t, err) defer func() { assert.NilError(t, h.Shutdown(context.WithoutCancel(ctx))) }() - assert.Check(t, h.PublishedServicesForPoint(echov1.Point.ID())[id] == nil) + assert.Check(t, offeredPoints(h)[id] == nil) + assert.Check(t, len(h.OfferedServices(echopb.ClientPoint.Point, id)) == 0) conn, ok := h.Conn(id) assert.Check(t, ok) @@ -165,7 +187,7 @@ func TestProcessOfferPolicy(t *testing.T) { defer func() { assert.NilError(t, h.Shutdown(context.WithoutCancel(ctx))) }() assert.Equal(t, policyCalls, 1) - assert.Check(t, h.PublishedServicesForPoint(echov1.Point.ID())[id] == nil) + assert.Check(t, offeredPoints(h)[id] == nil) }) t.Run("reject", func(t *testing.T) { @@ -179,12 +201,13 @@ func TestProcessOfferPolicy(t *testing.T) { ) assert.Assert(t, h == nil) assert.Assert(t, errors.Is(err, cause)) - assert.ErrorContains(t, err, `publish offered points for extension "org.example.exthook.v1"`) + assert.ErrorContains(t, err, `admit provider for extension "org.example.exthook.v1"`) }) } -// TestInProcessPointExposure verifies a published Point can be collected and -// registered directly on a gRPC server without a process boundary. +// TestInProcessPointExposure verifies an in-process offered Point can be +// resolved and registered directly on a gRPC server without a process +// boundary. func TestInProcessPointExposure(t *testing.T) { ctx := t.Context() var policyIdentity extensions.ExtensionIdentity @@ -192,11 +215,10 @@ func TestInProcessPointExposure(t *testing.T) { h, err := host.New(ctx, host.WithRuntimeDir(shortTempDir(t)), host.WithExtensions(greeter.Extension), - host.WithPointServers(greeterpb.ServerPoint), host.WithProviderPolicy(host.PointPolicyFunc(func(identity extensions.ExtensionIdentity, point extensions.PointID) host.PointPolicyResult { policyPoints = append(policyPoints, point) policyIdentity = identity - if identity.ID == greeter.ID && (point == greeterv0.Point.ID() || point == servicev0.Point.ID()) { + if identity.ID == greeter.ID && (point == greeter.Point.ID() || point == servicev0.Point.ID()) { return host.Allow() } return host.Drop() @@ -204,19 +226,20 @@ func TestInProcessPointExposure(t *testing.T) { ) assert.NilError(t, err) defer func() { assert.NilError(t, h.Shutdown(context.WithoutCancel(ctx))) }() - assert.DeepEqual(t, policyPoints, []extensions.PointID{greeterv0.Point.ID(), servicev0.Point.ID()}) + + assert.DeepEqual(t, policyPoints, []extensions.PointID{greeter.Point.ID(), servicev0.Point.ID()}) assert.Equal(t, policyIdentity, extensions.ExtensionIdentity{ ID: greeter.ID, Origin: extensions.ExtensionOrigin{Kind: extensions.ExtensionOriginBuiltin}, }) - _, err = h.Provider(greeterv0.Point.ID(), greeter.ID) - assert.NilError(t, err) - assert.DeepEqual(t, h.PublishedServicesForPoint(greeterv0.Point.ID()), map[extensions.ExtensionID][]string{ - greeter.ID: {"org.mobyproject.extension.example.greeter.v0.Greeter"}, + assert.DeepEqual(t, offeredPoints(h), map[extensions.ExtensionID][]extensions.PointID{ + greeter.ID: {greeter.Point.ID()}, }) + impl, err := h.Provider(greeter.Point.ID(), greeter.ID) + assert.NilError(t, err) srv := grpc.NewServer() - h.RegisterInProcessServices(srv) + assert.NilError(t, servicegrpc.Register(srv, greeter.ServerPoint, impl)) sock := filepath.Join(shortTempDir(t), "api.sock") lis, err := net.Listen("unix", sock) assert.NilError(t, err) @@ -231,3 +254,94 @@ func TestInProcessPointExposure(t *testing.T) { assert.NilError(t, err) assert.Equal(t, resp.Message, "hello world") } + +// serveUnix serves on a fresh Unix socket and returns a client connection to +// it. +func serveUnix(t *testing.T, serve func(net.Listener) error, stop func()) *grpc.ClientConn { + t.Helper() + sock := filepath.Join(shortTempDir(t), "api.sock") + lis, err := net.Listen("unix", sock) + assert.NilError(t, err) + + go func() { _ = serve(lis) }() + + t.Cleanup(stop) + + conn, err := grpc.NewClient("unix:"+sock, grpc.WithTransportCredentials(insecure.NewCredentials())) + assert.NilError(t, err) + t.Cleanup(func() { assert.NilError(t, conn.Close()) }) + + return conn +} + +// TestOffersReachableForBuiltinAndProcessExtensions verifies offers of builtin +// and launched extensions in one Host are reachable by clients: launched ones +// through a proxy on their connection, builtin ones served in-process. +func TestOffersReachableForBuiltinAndProcessExtensions(t *testing.T) { + if testing.Short() { + t.Skip("builds and launches a helper binary") + } + + dir := t.TempDir() + + const processID = "org.example.exthook.v1" + + bin := extensionBinaryPath(dir, processID) + + build := exec.Command("go", "build", "-o", bin, "github.com/moby/extensions/internal/launcher/testdata/exthook") + if out, err := build.CombinedOutput(); err != nil { + t.Fatalf("build exthook extension: %v\n%s", err, out) + } + + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + + h, err := host.New(ctx, + host.WithRuntimeDir(shortTempDir(t)), + host.WithDirs(dir), + host.WithExtensions(greeter.Extension), + host.WithProviderPolicy(host.PointPolicyFunc(func(extensions.ExtensionIdentity, extensions.PointID) host.PointPolicyResult { + return host.Allow() + })), + ) + + assert.NilError(t, err) + defer func() { assert.NilError(t, h.Shutdown(context.WithoutCancel(ctx))) }() + + servers := map[extensions.PointID]serverpoint.Registration{greeter.Point.ID(): greeter.ServerPoint} + inProcess := grpc.NewServer() + + var backends []grpcproxy.Backend + + for id, points := range offeredPoints(h) { + if conn, ok := h.Conn(id); ok { + 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 + } + + for _, point := range points { + impl, err := h.Provider(point, id) + assert.NilError(t, err) + assert.NilError(t, servicegrpc.Register(inProcess, servers[point], impl)) + } + } + + routes, err := grpcproxy.BuildRoutes(backends, nil) + assert.NilError(t, err) + + proxy := grpcproxy.New(routes) + + greet, err := greeterpb.NewClient(serveUnix(t, inProcess.Serve, inProcess.Stop)).Greet(ctx, &greeterv0.HelloRequest{Name: "world"}) + assert.NilError(t, err) + assert.Equal(t, greet.Message, "hello world") + + echo, err := echopb.NewEchoClient(serveUnix(t, proxy.Serve, proxy.Stop)).Echo(ctx, &echopb.EchoRequest{Message: "offered"}) + assert.NilError(t, err) + assert.Equal(t, echo.GetMessage(), "offered") +} diff --git a/internal/extensiondecl/declaration.go b/internal/extensiondecl/declaration.go index 3a00e7e..8936116 100644 --- a/internal/extensiondecl/declaration.go +++ b/internal/extensiondecl/declaration.go @@ -114,13 +114,22 @@ func ValidateServices(name string, points []extensions.PointID, services map[ext return nil } -// ValidateOffers rejects malformed, duplicate, unimplemented, and unserved -// offered Points. +// ValidateOffers requires the servicev0 provider for nonempty offers and +// rejects malformed, duplicate, unimplemented, and unserved offered Points. func ValidateOffers(name string, points, offered []extensions.PointID, services map[extensions.PointID][]string) error { + if len(offered) == 0 { + return nil + } + declared := make(map[extensions.PointID]bool, len(points)) for _, point := range points { declared[point] = true } + + if !declared[servicev0.Point.ID()] { + return fmt.Errorf("extension %q offered points without declaring provider %q", name, servicev0.Point.ID()) + } + seen := make(map[extensions.PointID]bool, len(offered)) for _, point := range offered { if err := extensions.ValidatePointID(point); err != nil { diff --git a/internal/extensiondecl/declaration_test.go b/internal/extensiondecl/declaration_test.go index dbf8fa1..d473f4e 100644 --- a/internal/extensiondecl/declaration_test.go +++ b/internal/extensiondecl/declaration_test.go @@ -38,6 +38,7 @@ func TestParseConvertsDeclaration(t *testing.T) { Providers: []sdkapi.PointDeclaration{ {ID: "org.example.one.v1"}, {ID: "org.example.two.v1"}, + {ID: "org.mobyproject.extension.service.v0"}, }, Dependencies: []sdkapi.Dependency{ {Point: "org.example.one.v1", Extension: "provider", Optional: true}, @@ -52,7 +53,7 @@ func TestParseConvertsDeclaration(t *testing.T) { assert.NilError(t, err) assert.Assert(t, is.DeepEqual(decl, &Declaration{ ID: extensions.ExtensionID("example"), - Points: []extensions.PointID{"org.example.one.v1", "org.example.two.v1"}, + Points: []extensions.PointID{"org.example.one.v1", "org.example.two.v1", "org.mobyproject.extension.service.v0"}, OfferedPoints: []extensions.PointID{"org.example.one.v1"}, Dependencies: []extensions.Dependency{{Point: "org.example.one.v1", Extension: "provider", Optional: true}}, Conflicts: []extensions.ExtensionID{"conflict"}, @@ -72,11 +73,12 @@ func TestParseRejectsInvalidOffers(t *testing.T) { services []sdkapi.ProviderServices want string }{ - {name: "invalid", offers: []string{"not-versioned"}, want: "offered an invalid point"}, - {name: "duplicate", providers: []sdkapi.PointDeclaration{{ID: point}}, offers: []string{point, point}, services: []sdkapi.ProviderServices{{Point: point, Services: []string{"example.API"}}}, want: "more than once"}, - {name: "unimplemented", offers: []string{point}, want: "without implementing it"}, + {name: "missing offer marker", providers: []sdkapi.PointDeclaration{{ID: point}}, offers: []string{point}, services: []sdkapi.ProviderServices{{Point: point, Services: []string{"example.API"}}}, want: `offered points without declaring provider "org.mobyproject.extension.service.v0"`}, + {name: "invalid", providers: []sdkapi.PointDeclaration{{ID: metadata}}, offers: []string{"not-versioned"}, want: "offered an invalid point"}, + {name: "duplicate", providers: []sdkapi.PointDeclaration{{ID: point}, {ID: metadata}}, offers: []string{point, point}, services: []sdkapi.ProviderServices{{Point: point, Services: []string{"example.API"}}}, want: "more than once"}, + {name: "unimplemented", providers: []sdkapi.PointDeclaration{{ID: metadata}}, offers: []string{point}, want: "without implementing it"}, {name: "metadata point", providers: []sdkapi.PointDeclaration{{ID: metadata}}, offers: []string{metadata}, services: []sdkapi.ProviderServices{{Point: metadata, Services: []string{"example.Metadata"}}}, want: "cannot offer publication metadata"}, - {name: "missing service", providers: []sdkapi.PointDeclaration{{ID: point}}, offers: []string{point}, want: "without reporting a service"}, + {name: "missing service", providers: []sdkapi.PointDeclaration{{ID: point}, {ID: metadata}}, offers: []string{point}, want: "without reporting a service"}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { diff --git a/sdk/sdkapi/runtime.go b/sdk/sdkapi/runtime.go index e2d9fc0..337bc4d 100644 --- a/sdk/sdkapi/runtime.go +++ b/sdk/sdkapi/runtime.go @@ -50,6 +50,7 @@ type Declaration struct { Conflicts []string `pb:"4"` // OfferedPoints lists implemented Points eligible for Host-controlled // publication. + // A nonempty list requires the servicev0 Point in Providers. OfferedPoints []string `pb:"5"` // ProviderServices records the fully-qualified gRPC service names registered // while serving each provider point. All of these services are available on diff --git a/sdk/sdkapi/runtime_test.go b/sdk/sdkapi/runtime_test.go index b27157a..98e76bc 100644 --- a/sdk/sdkapi/runtime_test.go +++ b/sdk/sdkapi/runtime_test.go @@ -58,6 +58,7 @@ func TestDeclarationOfferProtocolRoundTrip(t *testing.T) { ID: "org.example.extension.v1", Providers: []sdkapi.PointDeclaration{ {ID: "org.example.api.v1"}, + {ID: "org.mobyproject.extension.service.v0"}, }, OfferedPoints: []string{"org.example.api.v1"}, ProviderServices: []sdkapi.ProviderServices{ diff --git a/testdata/greeter/cmd/greeter/main.go b/testdata/greeter/cmd/greeter/main.go index 4fa29a3..0f23d53 100644 --- a/testdata/greeter/cmd/greeter/main.go +++ b/testdata/greeter/cmd/greeter/main.go @@ -6,11 +6,10 @@ package main import ( - greeterpb "github.com/moby/extensions/example/greeter/v0/protogen" "github.com/moby/extensions/sdk" "github.com/moby/extensions/testdata/greeter" ) func main() { - sdk.Main(greeter.Extension, sdk.WithServerPoints(greeterpb.ServerPoint)) + sdk.Main(greeter.Extension, sdk.WithServerPoints(greeter.ServerPoint)) } diff --git a/testdata/greeter/greeter.go b/testdata/greeter/greeter.go index e043d45..add68e7 100644 --- a/testdata/greeter/greeter.go +++ b/testdata/greeter/greeter.go @@ -9,12 +9,19 @@ import ( "github.com/moby/extensions" greeterv0 "github.com/moby/extensions/example/greeter/v0" + greeterpb "github.com/moby/extensions/example/greeter/v0/protogen" servicev0 "github.com/moby/extensions/extpoints/service/v0" + "github.com/moby/extensions/serverpoint" ) // ID is the extension id and binary name. const ID = "org.mobyproject.example.greeter.v1" +// Point deliberately differs from the proto package serving Greeter. +var Point = extensions.DefinePoint[greeterv0.Greeter]("org.example.greeting.v1") + +var ServerPoint = serverpoint.Registration{Point: Point.ID(), Register: greeterpb.ServerPoint.Register} + type greeter struct{} func (greeter) Greet(_ context.Context, req *greeterv0.HelloRequest) (*greeterv0.HelloReply, error) { @@ -25,7 +32,7 @@ func (greeter) Greet(_ context.Context, req *greeterv0.HelloRequest) (*greeterv0 var Extension = extensions.New(extensions.Declaration{ ID: ID, Providers: []extensions.Provider{ - greeterv0.Point.Provide(greeter{}), - servicev0.Offer(greeterv0.Point), + Point.Provide(greeter{}), + servicev0.Offer(Point), }, })