-
Notifications
You must be signed in to change notification settings - Fork 142
node, router: one client for the control plane's pull endpoints #456
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| // Package client is how a mesh component reads from its control plane. Node | ||
| // and router share it, so the body cap, the status handling and the signature | ||
| // check on /keys are a single code path. It depends on api/ only: importing it | ||
| // pulls in none of the control plane server. | ||
| package client | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/ed25519" | ||
| "encoding/base64" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "google.golang.org/protobuf/proto" | ||
|
|
||
| "github.com/google/sam/api" | ||
| ) | ||
|
|
||
| // MaxBodyBytes caps every response body read from a control plane: a | ||
| // misbehaving or impersonated server must not be able to make a client | ||
| // buffer arbitrary amounts of memory. It is sized for the largest legitimate | ||
| // answer, the ban set in /info at roughly 55 bytes per peer ID, so about | ||
| // 150k banned peers fit; the policy is bounded by the control plane's own | ||
| // 1 MiB cap on POST /policies, and /keys is a few hundred bytes. | ||
| const MaxBodyBytes = 8 << 20 | ||
|
|
||
| // ErrBodyTooLarge marks an answer over MaxBodyBytes. It is an error, never a | ||
| // prefix: a protobuf message cut at a field boundary still decodes, so a | ||
| // truncated ban set or router list would be read as a smaller, valid one. | ||
| var ErrBodyTooLarge = errors.New("control plane answer exceeds the body cap") | ||
|
|
||
| // ReadBody reads a control plane response body of at most MaxBodyBytes and | ||
| // reports ErrBodyTooLarge for anything larger. | ||
| func ReadBody(r io.Reader) ([]byte, error) { | ||
| body, err := io.ReadAll(io.LimitReader(r, MaxBodyBytes+1)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read response body: %w", err) | ||
| } | ||
| if len(body) > MaxBodyBytes { | ||
| return nil, fmt.Errorf("%w (%d bytes)", ErrBodyTooLarge, MaxBodyBytes) | ||
| } | ||
| return body, nil | ||
| } | ||
|
|
||
| // transport applies api.ValidateControlPlaneTransport to every request, | ||
| // redirects included, so a plaintext hop is refused wherever the URL came | ||
| // from. allowInsecure is read per request: the node learns the operator's | ||
| // choice after its clients exist. | ||
| type transport struct { | ||
| allowInsecure func() bool | ||
| } | ||
|
|
||
| func (t transport) RoundTrip(req *http.Request) (*http.Response, error) { | ||
| if err := api.ValidateControlPlaneTransport(req.URL.String(), t.allowInsecure()); err != nil { | ||
| return nil, err | ||
| } | ||
| return http.DefaultTransport.RoundTrip(req) | ||
| } | ||
|
|
||
| // NewHTTPClient is the HTTP client for every request a mesh component makes | ||
| // to its control plane. A nil allowInsecure never allows plaintext. | ||
| func NewHTTPClient(timeout time.Duration, allowInsecure func() bool) *http.Client { | ||
| if allowInsecure == nil { | ||
| allowInsecure = func() bool { return false } | ||
| } | ||
| return &http.Client{Timeout: timeout, Transport: transport{allowInsecure: allowInsecure}} | ||
| } | ||
|
|
||
| // Client reads the pull side of the mesh protocol from one control plane. | ||
| type Client struct { | ||
| baseURL string | ||
| http *http.Client | ||
| } | ||
|
|
||
| // New normalizes baseURL, https:// when no scheme is given and no trailing | ||
| // slash, and speaks through httpClient, which the caller builds with | ||
| // NewHTTPClient so its own transport policy applies. | ||
| func New(baseURL string, httpClient *http.Client) *Client { | ||
| if !strings.HasPrefix(baseURL, "http://") && !strings.HasPrefix(baseURL, "https://") { | ||
| baseURL = "https://" + baseURL | ||
| } | ||
| return &Client{baseURL: strings.TrimSuffix(baseURL, "/"), http: httpClient} | ||
| } | ||
|
|
||
| // FetchInfo is GET /info: the router addresses, the ban set and the OIDC | ||
| // details a node needs to enroll. | ||
| func (c *Client) FetchInfo(ctx context.Context) (*api.ControlPlaneInfoResponse, error) { | ||
| var info api.ControlPlaneInfoResponse | ||
| if err := c.get(ctx, "/info", nil, &info); err != nil { | ||
| return nil, err | ||
| } | ||
| return &info, nil | ||
| } | ||
|
|
||
| // FetchKeys is GET /keys: the control plane's currently valid signing keys. | ||
| // The set is accepted only if signed by a key in trusted | ||
| // (api.VerifyKeysResponse): whoever answers the URL must already be the | ||
| // control plane, not become it. | ||
| func (c *Client) FetchKeys(ctx context.Context, trusted []ed25519.PublicKey) ([]ed25519.PublicKey, error) { | ||
| var resp api.KeysResponse | ||
| if err := c.get(ctx, "/keys", nil, &resp); err != nil { | ||
| return nil, err | ||
| } | ||
| keys, err := api.VerifyKeysResponse(&resp, trusted, time.Now()) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("/keys response rejected: %w", err) | ||
| } | ||
| return keys, nil | ||
| } | ||
|
|
||
| // FetchPolicy is GET /policies, authenticated with the caller's biscuit: the | ||
| // roles and bindings a node compiles into its authorization rules. | ||
| func (c *Client) FetchPolicy(ctx context.Context, biscuit []byte) (*api.PolicyConfigGetResponse, error) { | ||
| var policy api.PolicyConfigGetResponse | ||
| if err := c.get(ctx, "/policies", biscuit, &policy); err != nil { | ||
| return nil, err | ||
| } | ||
| return &policy, nil | ||
| } | ||
|
|
||
| func (c *Client) get(ctx context.Context, path string, biscuit []byte, msg proto.Message) error { | ||
| req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to create HTTP request: %w", err) | ||
| } | ||
| if len(biscuit) > 0 { | ||
| req.Header.Set("Authorization", "Bearer "+base64.StdEncoding.EncodeToString(biscuit)) | ||
| } | ||
| resp, err := c.http.Do(req) | ||
| if err != nil { | ||
| return fmt.Errorf("HTTP request failed: %w", err) | ||
| } | ||
| defer func() { _ = resp.Body.Close() }() | ||
|
|
||
| body, err := ReadBody(resp.Body) | ||
| if err != nil { | ||
| return fmt.Errorf("%s: %w", path, err) | ||
| } | ||
| if resp.StatusCode != http.StatusOK { | ||
| return fmt.Errorf("control plane returned status %s: %s", resp.Status, string(body)) | ||
| } | ||
| if err := proto.Unmarshal(body, msg); err != nil { | ||
| return fmt.Errorf("failed to decode %s response: %w", path, err) | ||
| } | ||
| return nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.