From 17c7d36f6957bc7378d0b5fff09c7c4728e52ae4 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 12:33:10 -0600 Subject: [PATCH 01/24] docs: propose secure customer BMC access --- README.md | 3 + docs/enhancements/secure-bmc-access.md | 578 +++++++++++++++++++++++++ 2 files changed, 581 insertions(+) create mode 100644 docs/enhancements/secure-bmc-access.md diff --git a/README.md b/README.md index 1cfe3895..8b359b73 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,9 @@ guest agent. Provisioning engines and provider integrations remain pluggable. source proposals, and unresolved design questions. - [Implementation roadmap](docs/roadmap.md): proposed milestones and evidence required before enabling infrastructure effects. +- [Secure customer BMC access](docs/enhancements/secure-bmc-access.md): proposed + product experience, allocation-scoped Redfish session architecture, security, + routing, and provisional API design. - [Contributor guidance](AGENTS.md): repository conventions and key invariants. The foundation comes from open `datum-cloud/infra` PRs diff --git a/docs/enhancements/secure-bmc-access.md b/docs/enhancements/secure-bmc-access.md new file mode 100644 index 00000000..974d94bf --- /dev/null +++ b/docs/enhancements/secure-bmc-access.md @@ -0,0 +1,578 @@ +--- +status: provisional +stage: alpha +latest-milestone: "unplanned" +--- + +# Secure customer BMC access + +This enhancement proposes allocation-scoped customer access to a narrow Redfish +API without exposing a BMC, its management network, or its credentials directly. +It extends the provisional [Fleet design context](../design.md) and the pinned +[bare-metal provisioning proposal][fleet-provisioning]. No API or behavior in +this document is implemented or verified in Fleet today. + +The architecture borrows the session and data-path separation used by Datum +Compute's provisional [instance shell sessions][compute-shell]: the platform +authenticates and authorizes a short-lived session, binds it to an authoritative +placement, and then keeps the central control plane out of the request data path. +The transport and resource names below remain design proposals; adopting this +pattern does not require Fleet to reuse Compute resources or deployment +components. + +## Summary + +Customers with an active `MachineClaim` can request a short-lived management +session for the machine allocated to that claim. Datum authenticates the caller +with the normal platform identity, authorizes the requested capability against +the current allocation, and binds the session to the consumer project, principal, +Claim UID, Machine UID, binding identifier and binding epoch. + +After admission, Redfish traffic travels through an encrypted relay path to a +location-local Redfish gateway. The gateway exposes a small, provider-neutral +Redfish profile, resolves the private BMC target for the retained allocation, +and reaches the BMC through the location's management network. For the initial +Supermicro integration, that network is expected to be reachable through an +operator-managed OpenVPN connection. Customers do not receive VPN access, a BMC +address, or BMC credentials. + +The central API handles session admission, binding, status, audit and revocation. +It does not proxy each Redfish request. Relay capacity and location gateways +scale independently, and a location can continue serving already admitted, +still-valid sessions during a bounded control-plane interruption. + +## Motivation + +Some customers already operate bare-metal provisioning systems and need to keep +using them while Fleet's installation and cluster automation is developed. PXE +boot, power control and machine inspection are enough to integrate many of these +systems, but direct BMC or management-VPN access would expose a large and +vendor-specific administrative surface. + +A central Redfish reverse proxy would hide BMC credentials, but it would also +place every hardware request and response on a global service. That creates an +unnecessary availability, latency and scaling dependency and requires the global +service to maintain routes into every management network. + +Fleet instead needs an access contract that: + +- reuses the existing MachineClaim allocation authority; +- preserves a standard Redfish API for customer provisioning software; +- keeps BMC endpoints, credentials and management networks private; +- routes once when a session is admitted instead of globally routing every + Redfish request; +- fences stale sessions when a machine is released or reassigned; and +- retains exact authority and inputs before power or boot effects. + +## Goals + +- Let an authorized human or service identity operate the machine currently + allocated to its `MachineClaim` through a documented Redfish interoperability + profile. +- Support customer-controlled PXE provisioning through one-time boot selection + and bounded power actions before full Fleet installation automation exists. +- Use Datum identity and IAM for session admission without requiring customer + accounts to be created on each BMC. +- Keep the central Fleet API out of the Redfish data path. +- Keep location management connections outbound-only where the selected relay + transport permits it. +- Prevent a session, delayed request or recovered worker from affecting a later + allocation of the same machine. +- Record mutating operation authority before effects and report uncertain + outcomes as unknown. +- Provide the same public contract across qualified BMC vendors while allowing + vendor-specific adapters behind the location gateway. + +## Non-goals + +- General BMC administration or unrestricted pass-through to a vendor API. +- Customer access to the BMC web UI, SSH service, IPMI, management VPN, OEM + endpoints, account management, firmware update or BMC network configuration. +- Selecting a final relay implementation, state store, API group version, + provisioning engine or Supermicro model matrix. +- Replacing brokered serial or graphical console access. Console remains a + separately authorized capability with its own transport and recording policy. +- Making Redfish the internal contract for every Fleet hardware provider. +- Treating BMC command acceptance as proof that a requested hardware state was + reached. + +## Consumer experience + +### Prerequisites + +The consumer has: + +- an active `MachineClaim` bound through Fleet's allocator; +- an IAM grant that permits creation of management sessions for that claim; +- a machine offering that advertises the requested Redfish access profile; and +- a supported client connector, supplied as a CLI command, sidecar or SDK + component. + +The caller never supplies a Machine, BMC address, location route or provider +credential. Those are resolved from the claim's private retained binding. + +### Manual access + +The exact command is illustrative: + +```console +$ datumctl fleet machine-management proxy db-01 +Session db-01-k7m2p is ready until 2026-11-11T19:15:00Z +Redfish endpoint: https://127.0.0.1:9443/redfish/v1 +``` + +The connector creates an ephemeral key pair in memory, creates a management +session containing the public key, waits for the location endpoint, and opens an +encrypted tunnel. It exposes a loopback Redfish endpoint for ordinary Redfish +tools. Closing the connector deletes or closes the session and clears the private +key. + +The loopback TLS and Redfish login-session behavior must be qualified with the +initial client tools. The connector may issue a one-time local login credential +and a per-session CA bundle, then implement Redfish `SessionService` locally and +return an `X-Auth-Token`. Those credentials authorize only the local connector; +they are never forwarded to or created on the BMC. The connector must not write +the transport private key or a reusable BMC credential to disk by default. + +### Customer provisioning automation + +An automated provisioner uses a Datum service identity to create a session for a +specific MachineClaim UID. A connector sidecar owns the ephemeral transport key +and presents the provisioner with the same Redfish base URL for the session's +lifetime. The provisioner can then: + +1. read the Redfish service root and computer-system state; +2. set a one-time PXE boot override; +3. request a supported reset or power transition; +4. follow a returned Redfish task when the operation is asynchronous; and +5. return boot selection to local disk if its workflow requires it. + +The customer continues to own its PXE, DHCP, image and installation workflow. +This enhancement supplies only the admitted hardware-management operations. +Networking and IPAM remain responsible for customer and provisioning network +attachments. + +### Compatibility boundary + +The HTTP resources and payloads exposed after connection follow Redfish. Session +admission, location rendezvous and the encrypted relay are Datum-specific. A +generic Redfish tool therefore works through the connector, not by connecting +directly to a BMC or to a global Fleet proxy. + +If requiring a connector proves incompatible with important customer tooling, a +future deployment may expose the same gateway through regional HTTPS ingress and +short-lived scoped credentials. That is a transport alternative, not a reason to +change the allocation, authorization, operation or Redfish contracts. + +## Proposed Redfish profile + +The gateway presents a virtual Redfish service rather than forwarding the BMC's +entire resource tree. Resource identifiers are stable within the session and do +not reveal private device identifiers. The initial profile is intentionally +small: + +| Method and resource | Initial behavior | +| --- | --- | +| `GET /redfish/v1/` | Service discovery for the exposed profile. | +| `GET /redfish/v1/SessionService` and its session collection | Redfish login-session discovery. | +| `POST /redfish/v1/SessionService/Sessions` and `DELETE` of the resulting member | A session local to the connector or virtual gateway; no account or session is created on the BMC. | +| `GET /redfish/v1/Systems` | A collection containing the one allocated system. | +| `GET /redfish/v1/Systems/{id}` | Permitted system, power and boot observations. | +| `PATCH /redfish/v1/Systems/{id}` | One-time boot override for qualified targets such as PXE or local disk. Other fields are rejected. | +| `POST /redfish/v1/Systems/{id}/Actions/ComputerSystem.Reset` | Qualified reset and power actions. Unsupported `ResetType` values are rejected rather than substituted. | +| `GET /redfish/v1/TaskService` and task members | Progress and outcome for asynchronous gateway operations. | + +The gateway does not expose `AccountService`, `Managers`, `UpdateService`, BMC +network configuration, virtual media, log deletion, OEM actions, arbitrary +`Actions` targets or links outside the allowlisted virtual resource tree. Later +profiles require explicit review, capability publication and authorization. + +Redfish supports HTTP Basic, Redfish login sessions, and optional delegated +OAuth 2.0 bearer authentication. This proposal does not depend on the physical +BMC implementing Datum OAuth. Platform identity authorizes creation of the Fleet +session; possession of its ephemeral private key authorizes the location data +path; the gateway authenticates to the BMC with operator-held credentials. + +## Architecture + +### Request and data paths + +```text + control and status path + client ── OAuth ──> Fleet project API ──> session admission and binding + │ │ + │ v + │ location-local session projection + │ │ + │ encrypted Redfish data path v + └────────> Datum relay ───────────────> location Redfish gateway + │ + │ private target and credential + v + OpenVPN / management network + │ + v + BMC +``` + +The exact projection mechanism is not selected here. It must deliver the bound +session and revocations to the authoritative location without giving the +location agent broad credentials to the consumer project API. Status returns +through the same controlled synchronization contract. A location cannot choose +itself or replace an already bound endpoint through status. + +### Responsibilities + +- **Fleet project API:** authenticates the user or service identity, authorizes + the requested session, validates immutable input and exposes lifecycle status. +- **Management-session admission:** resolves the private active allocation, + checks current capability and conflicts, retains the exact binding and chooses + the authoritative location from trusted allocation state. +- **Session projection:** carries the least-privileged location-local session + copy and revocation state. It is not the Redfish request path. +- **Relay endpoint:** maintains outbound connectivity from the location and + forwards an end-to-end encrypted stream. It has no BMC credential and may + reach only the location gateway. +- **Location Redfish gateway:** verifies possession of the session key, consumes + or attaches the session, enforces its profile, virtualizes Redfish resources, + retains mutating operations and calls the selected adapter. +- **BMC adapter:** translates the profile to a qualified physical BMC, holds or + obtains its credentials from location-scoped secret custody, and normalizes + supported observations and results. +- **Operation journal:** durably records admitted mutating requests, exact + binding, target, normalized request body, idempotency identity, execution route + and evidence before effects. + +The gateway and adapter may be one deployment initially, but their responsibilities +and credential boundaries remain distinct. The relay endpoint must not become an +unrestricted HTTP CONNECT service to the management network. + +### Authentication and authorization + +Session admission uses Datum's existing human and service identity flows. IAM +defines a management-session create permission separately from ordinary +MachineClaim read or update. Admission evaluates that permission against the +consumer project and target MachineClaim and then resolves the private binding; +possession of a claim name or UID is not authorization. + +The client generates an ephemeral Ed25519 key pair. Only the public key enters +the proposed session resource. On connection, the gateway verifies a signature +covering at least the session UID, protocol version, connection timestamp and +gateway audience. The first accepted connection consumes the connection window. +Replay, a changed route or a second concurrent connector is rejected. + +The admitted access profile is selected from provider-published capabilities and +the caller's grant. The caller cannot supply an arbitrary path allowlist or ask +the gateway to forward unknown Redfish resources. A narrower request can be +accepted; it cannot expand the offering. + +The physical BMC sees only the gateway's location-scoped identity. BMC credentials +must never appear in the public session, its status, audit events, client errors +or relay configuration. Credential rotation does not change Machine identity or +create a customer session. + +### Binding and routing + +Routing is a one-time admission decision, not a lookup on each Redfish request. +The protected session binding retains: + +- consumer and provider Project UIDs; +- requesting principal identity; +- MachineClaim name and UID; +- Machine name and UID; +- allocation binding identifier and epoch; +- selected location UID and location-service revision; +- selected BareMetalMachine and adapter identity; +- admitted access-profile revision; +- client public key, creation time, connect deadline and expiry; and +- session and operation correlation identifiers. + +The consumer-visible object does not reveal the provider project, Machine, +BareMetalMachine, BMC endpoint or adapter route. The location gateway resolves +the retained target through its private provider records and verifies that every +request still matches the projected binding epoch. + +If an allocation moves, is released or is replaced, a new session is required. +The old endpoint cannot be rebound to the successor. A location-revision change +requires controlled handover or session replacement; mutable discovery must not +silently redirect an active session. + +### Session lifecycle + +A session progresses through `Pending`, `Ready` and `Connected`, then reaches one +terminal reason. Proposed terminal reasons include `Completed`, `Expired`, +`Revoked`, `NotConnected`, `AllocationEnded`, `LocationUnavailable`, `Rejected`, +`Disconnected` and `CleanupUnconfirmed`. + +`Ready` means a gateway accepted the projected session and published a usable +endpoint before the connection deadline. It does not mean the BMC is healthy or +that any requested hardware state was reached. `Connected` means the ephemeral +client key was accepted. Session expiry and command outcome remain separate. + +Deleting or closing a session immediately denies new central admission and +propagates revocation to the location. Release of the MachineClaim has higher +priority: it fences new operations, revokes all sessions for that binding and +waits for active gateways to confirm teardown or records the result as unknown. +The allocator must not make the Machine available to a later consumer until the +release contract has accounted for those sessions. + +The gateway fails closed when its allocation/session projection exceeds its +freshness limit. A partition does not turn cached authorization into an +indefinite management grant. An already admitted operation may continue only +under its retained authority and bounded expiry. + +### Mutating operations + +Read-only Redfish requests can be served from current BMC observations within +the session profile. Before forwarding a boot or power mutation, the gateway +retains a protected operation containing: + +- the session and allocation identities; +- the normalized Redfish method, virtual target and exact accepted body; +- the physical target resolved by the adapter; +- an idempotency identity and operation epoch; +- current binding, session and conflict preconditions; and +- the selected adapter route and credential revision without secret material. + +The operation journal is the authority for the effect. A gateway process lease +or an open relay stream is not sufficient. Installation, release, power intent +and other hardware operations serialize through the same asset-level conflict +contract. + +If the BMC response is lost, the result is `Unknown`. Recovery queries the +existing operation and physical state before deciding whether another request +is safe. The gateway must not translate an uncertain failure into a successful +Redfish response or blindly submit the same reset again. A Redfish task can +remain incomplete or finish with an explicit exception while recovery continues. + +### Availability and scaling + +Central load is proportional to session creation, status transitions, revocation +and audit events, not to Redfish request volume or response size. Relays provide +generic transport capacity and can scale independently. Each location gateway +handles only sessions for machines managed in that location. + +The location gateway and its operation state must be recoverable independently +of the workload machines it manages. The management path cannot depend on a +guest OS, customer cluster or the server being powered on. A location that +cannot establish current allocation authority stops accepting new connections +and mutations rather than falling back to raw BMC access. + +### Audit and observability + +The project activity log records session creation with the requesting human or +service identity. Lifecycle events record the session UID, project, claim UID, +access profile, bound location, start and end times, and terminal reason. It must +not record private keys, session-local bearer values, BMC credentials, raw +provider endpoints or secret-bearing response bodies. + +Every mutating request receives a Fleet operation correlation identifier. Audit +records include its normalized operation type and outcome. Request bodies are +retained in protected operation state when needed for recovery; customer-facing +activity uses a safe summary. Session byte streams and Redfish response bodies +are not recorded by default. + +Metrics cover admission latency and denial reasons, session readiness, active +connections, revocation latency, gateway/BMC reachability, operation outcome and +age of unknown results. Metrics must not label by customer-controlled high-cardinality +values or expose machine-management addresses. + +## Proposed API design + +All names, groups and fields in this section are illustrative. The proposal uses +`MachineManagementSession` to distinguish the customer contract from a BMC login +session. It is a consumer-project resource and does not expose a raw BMC handle. + +### MachineManagementSession + +Each resource represents one short-lived connection to one immutable claim +binding. The spec is immutable; changing the claim, key, profile or TTL requires +a new resource. + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: MachineManagementSession +metadata: + generateName: db-01- + namespace: acme +spec: + machineClaimRef: + name: db-01 + uid: 9ec01bc8-1d45-4dd6-8601-df63c9687047 + protocol: Redfish + accessProfile: Provisioning + clientPublicKey: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + ttl: 15m +status: + connection: + endpointID: abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 + relayURLs: + - https://relay.us-central-1.example.invalid + target: redfish-gateway-0.machine-access-system.svc:8443 + connectBefore: "2026-11-11T19:01:00Z" + expiresAt: "2026-11-11T19:15:00Z" + conditions: + - type: Ready + status: "True" + reason: SessionReady + message: Connect before 2026-11-11T19:01:00Z + observedGeneration: 1 + lastTransitionTime: "2026-11-11T19:00:01Z" +``` + +`machineClaimRef.uid` prevents a name reused after deletion from receiving the +old session. Admission requires the claim to be bound and active. `protocol` is +initially only `Redfish`. `accessProfile` refers to a versioned platform-defined +profile; arbitrary methods or paths are not accepted in the spec. `ttl` begins +no later than connection acceptance and is capped by policy. + +`status.connection` is rendezvous information, not a bearer capability. Holding +the matching ephemeral private key is required to connect. The target is a +virtual gateway service and must not contain a BMC address. Generally readable +status contains neither the private allocation binding nor credentials. + +Deleting the resource requests revocation. Finalization or equivalent retained +service state keeps the private session binding until the location confirms +teardown or the platform records that confirmation as unknown. Deletion alone +is not teardown evidence. + +### Protected session binding + +Admission creates a private service-owned binding record outside the consumer +project's deletion domain. It contains the routing and fencing fields listed in +[Binding and routing](#binding-and-routing). Only the session admission service +can create it; the location gateway can observe only the sessions routed to its +location and can update only their location-local status. + +This record is intentionally separate from `MachineClaim.status`. A public +session may be short-lived or deleted while its audit, revocation and release +obligations remain. The claim remains the allocation authority; creating a +session cannot alter the binding or machine lifecycle. + +### Permission model + +The initial permission model should distinguish at least: + +- reading session status; +- creating a provisioning-profile session; +- revoking one's own or project sessions; +- operator inspection of protected routing and operation evidence; and +- operator override or recovery actions. + +Default viewer access does not imply session creation. Service identities receive +an explicit grant. The admission service rechecks current source capability, +claim authority and allocation state at creation; an old IAM decision or copied +session object is not sufficient. + +### API and Redfish errors + +Session admission uses normal Datum API errors and conditions. Once connected, +the gateway returns Redfish status codes and extended error bodies for profile, +capability and operation failures. Errors must distinguish unsupported behavior, +conflict with another admitted operation, expired/revoked authority, unreachable +BMC and unknown execution outcome without disclosing the physical route. + +## Security considerations + +- **Compromised customer credential:** IAM limits session creation to authorized + claims; quotas, short connection windows and activity alerts bound abuse. +- **Stolen ephemeral private key:** keys live only in connector memory, have a + short lifetime and are bound to one session, gateway audience and allocation. +- **Compromised relay:** end-to-end encryption prevents the relay from reading or + modifying Redfish traffic; the relay holds no allocation or BMC credential. +- **Replay or stale allocation:** session UID, Claim UID, Machine UID, binding + epoch, key proof, timestamps and gateway audience are checked together. Release + propagates revocation and blocks reuse until sessions are accounted for. +- **Confused deputy:** the gateway resolves targets only from retained bindings, + never from a customer URL, host header, Redfish link or BMC identifier. +- **Compromised location gateway:** network policy and credentials limit it to + machines in its location. Credential isolation and one authoritative adapter + reduce blast radius; a compromised gateway remains a high-severity management + incident requiring credential rotation and allocation review. +- **BMC response injection:** the adapter validates TLS trust and the enrolled + physical identity. Redirects or links outside the virtual allowlist are not + followed or returned as customer routes. +- **Persistent firmware state:** the narrow profile excludes account, network, + firmware and OEM mutation. Release still evaluates applicable BMC and firmware + restoration obligations before reuse. + +## Rollout plan + +1. **Contract prototype:** implement the virtual Redfish profile against a + virtualized or simulated Supermicro-compatible BMC. Exercise common Redfish + clients through a local connector and verify that unlisted resources and + fields cannot be reached. +2. **Location transport prototype:** establish outbound relay connectivity from + a lab location, project a synthetic bound session, and prove direct client-to-location + traffic without placing the central API in the Redfish data path. +3. **Physical lab qualification:** connect the gateway to disposable Supermicro + hardware over the management OpenVPN path. Verify correct-host identity, + one-time PXE boot, supported power actions, task recovery, credential rotation, + rate limits and network isolation. +4. **Allocation integration:** authorize sessions against real MachineClaims and + retain the private binding epoch. Exercise concurrent allocation/release, + project deletion, location loss, stale session replay and uncertain BMC + responses. +5. **Customer pilot:** enable an explicit IAM grant and session quota for selected + projects. Integrate one existing customer provisioner without giving it BMC + or VPN credentials. Review audit records and operational load before expansion. + +## Acceptance gates + +- A standard Redfish client, using the supported connector, can inspect the + allocated system, select one-time PXE boot and perform each offered power action. +- The central API is absent from the Redfish request and response data path. +- The customer cannot discover or reach the BMC address, management VPN, another + machine, an OEM endpoint or an unlisted Redfish field/action through the gateway. +- Human and service identities use normal Datum authentication; an explicit IAM + grant and current MachineClaim binding are required for session creation. +- Two claims, projects or overlapping classes cannot cause a session to bind the + wrong Machine. A reused claim name or stale binding epoch is rejected. +- Release and project deletion deny new operations, actively close sessions and + prevent capacity reuse until teardown is confirmed or represented as unknown. +- A mutating request is retained before the BMC effect. Lost responses and gateway + restarts recover the existing operation without blindly repeating it. +- Gateway, relay and BMC credential failure produce actionable but non-secret + status and never become false readiness. +- The same public Redfish profile can be implemented by another qualified adapter + without changing the consumer session contract. + +## Open questions + +- Whether the first connector is embedded in `datumctl`, shipped as a sidecar, + exposed through an SDK, or provided in more than one form. +- Which existing Redfish clients must be supported and what loopback TLS and + session-login behavior they require. +- The exact first-version access profile, allowed `ResetType` values and boot + targets for each qualified Supermicro model and firmware revision. +- Whether an established Datum Connect deployment can satisfy browser, CLI and + service automation requirements, or whether a dedicated relay profile is + needed. +- The session projection and revocation transport, freshness limit and behavior + during control-plane or location partitions. +- Durable storage and concurrency boundaries between Fleet admission, the + location operation journal and provider adapters. +- Whether future regional HTTPS ingress is needed for customers that cannot run + a connector, and how its bearer credentials would be scoped and revoked. +- Session quotas, TTLs, per-machine concurrency, request rate limits and activity + alert thresholds for the initial pilot. +- Ownership and deployment boundaries for the gateway, relay endpoint, BMC + adapter and management OpenVPN connection. + +## References + +- [DMTF Redfish Specification DSP0266 v1.22.1][redfish-spec] +- [DMTF Redfish schema and developer resources][redfish-resources] +- [Datum Compute instance shell session proposal][compute-shell] +- [Datum Compute session protocol][compute-session-protocol] +- [Datum Compute client-to-location tunnel][compute-tunnel] +- [Pinned Fleet infrastructure management proposal][fleet-proposal] +- [Pinned Fleet bare-metal provisioning proposal][fleet-provisioning] + +[compute-session-protocol]: https://github.com/datum-cloud/compute/blob/fe85e3c619d2a774fc9ad45b2d362ced32a43c28/internal/consolesession/protocol.go +[compute-shell]: https://github.com/datum-cloud/compute/blob/fe85e3c619d2a774fc9ad45b2d362ced32a43c28/docs/enhancements/instance-shell-sessions/README.md +[compute-tunnel]: https://github.com/datum-cloud/compute/blob/fe85e3c619d2a774fc9ad45b2d362ced32a43c28/internal/consoleclient/tunnel.go +[fleet-proposal]: https://github.com/datum-cloud/infra/tree/51781e2456367be82281e1443ca56d0686311133/docs/enhancements/fleet-management +[fleet-provisioning]: https://github.com/datum-cloud/infra/blob/51781e2456367be82281e1443ca56d0686311133/docs/enhancements/fleet-management/bare-metal-provisioning.md +[redfish-resources]: https://redfish.dmtf.org/essentials +[redfish-spec]: https://www.dmtf.org/sites/default/files/standards/documents/DSP0266_1.22.1.pdf From 14ff0fba61520ee1b88fb428efe1db6244189643 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 12:42:14 -0600 Subject: [PATCH 02/24] docs: keep allocation UIDs internal --- docs/enhancements/secure-bmc-access.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/enhancements/secure-bmc-access.md b/docs/enhancements/secure-bmc-access.md index 974d94bf..eb314b13 100644 --- a/docs/enhancements/secure-bmc-access.md +++ b/docs/enhancements/secure-bmc-access.md @@ -137,8 +137,8 @@ the transport private key or a reusable BMC credential to disk by default. ### Customer provisioning automation An automated provisioner uses a Datum service identity to create a session for a -specific MachineClaim UID. A connector sidecar owns the ephemeral transport key -and presents the provisioner with the same Redfish base URL for the session's +MachineClaim in its project. A connector sidecar owns the ephemeral transport +key and presents the provisioner with the same Redfish base URL for the session's lifetime. The provisioner can then: 1. read the Redfish service root and computer-system state; @@ -398,7 +398,6 @@ metadata: spec: machineClaimRef: name: db-01 - uid: 9ec01bc8-1d45-4dd6-8601-df63c9687047 protocol: Redfish accessProfile: Provisioning clientPublicKey: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef @@ -420,11 +419,18 @@ status: lastTransitionTime: "2026-11-11T19:00:01Z" ``` -`machineClaimRef.uid` prevents a name reused after deletion from receiving the -old session. Admission requires the claim to be bound and active. `protocol` is -initially only `Redfish`. `accessProfile` refers to a versioned platform-defined -profile; arbitrary methods or paths are not accepted in the spec. `ttl` begins -no later than connection acceptance and is capped by policy. +`machineClaimRef.name` is a consumer lookup handle in the authenticated project; +the consumer does not supply or manage allocation identities. During session +admission, Fleet resolves the name and retains the current Claim UID, Machine UID, +binding identifier and binding epoch in the protected session binding before the +session can become Ready or authorize an effect. Admission requires the resolved +claim to be bound and active. If the claim or binding changes before that commit, +admission fails or restarts resolution rather than following stale state. A later +claim that reuses the same name cannot receive an already admitted session. + +`protocol` is initially only `Redfish`. `accessProfile` refers to a versioned +platform-defined profile; arbitrary methods or paths are not accepted in the +spec. `ttl` begins no later than connection acceptance and is capped by policy. `status.connection` is rendezvous information, not a bearer capability. Holding the matching ephemeral private key is required to connect. The target is a From 274064527e88d7dd01e474e8e210ea11ab754f4e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 19:50:16 -0600 Subject: [PATCH 03/24] prototype secure machine management access --- .github/workflows/test-e2e.yml | 55 ++ .gitignore | 8 + Dockerfile | 14 + README.md | 40 +- Taskfile.yaml | 60 ++ api/v1alpha1/doc.go | 6 + api/v1alpha1/groupversion_info.go | 28 + api/v1alpha1/types.go | 219 +++++++ api/v1alpha1/zz_generated.deepcopy.go | 58 ++ cmd/datumctl-fleet/main.go | 28 + cmd/fleet-controller/main.go | 62 ++ cmd/fleet-gateway/main.go | 70 +++ cmd/fleet-relay/main.go | 34 ++ config/base/kustomization.yaml | 4 + config/base/namespaces.yaml | 17 + ...tumapis.com_machineallocationbindings.yaml | 122 ++++ .../fleet.datumapis.com_machineclaims.yaml | 116 ++++ ....com_machinemanagementsessionbindings.yaml | 234 ++++++++ ...tumapis.com_machinemanagementsessions.yaml | 169 ++++++ ...om_projectedmachinemanagementsessions.yaml | 212 +++++++ config/crd/kustomization.yaml | 8 + config/location/access.yaml | 108 ++++ config/location/kustomization.yaml | 6 + config/location/networkpolicy.yaml | 43 ++ config/manager/controller.yaml | 88 +++ config/manager/kustomization.yaml | 6 + config/manager/networkpolicy.yaml | 20 + config/rbac/controller.yaml | 96 +++ config/rbac/projector-location.yaml | 32 + config/redfish/FleetProvisioning.v1_0_0.json | 47 ++ docs/design.md | 15 +- .../machine-management-prototype.md | 194 +++++++ docs/roadmap.md | 9 +- go.mod | 72 +++ go.sum | 192 ++++++ hack/e2e/diagnostics.sh | 24 + hack/e2e/down.sh | 14 + hack/e2e/openvpn-up.sh | 29 + hack/e2e/test.sh | 326 +++++++++++ hack/e2e/up.sh | 181 ++++++ hack/e2e/validators.sh | 39 ++ internal/cmd/fleet/root.go | 547 ++++++++++++++++++ internal/cmd/fleet/root_test.go | 76 +++ internal/controller/admission.go | 59 ++ internal/controller/admission_test.go | 36 ++ internal/controller/projection.go | 184 ++++++ internal/controller/projection_test.go | 54 ++ internal/controller/session.go | 290 ++++++++++ internal/controller/session_test.go | 79 +++ internal/gateway/gateway.go | 371 ++++++++++++ internal/gateway/gateway_test.go | 34 ++ internal/journal/journal.go | 200 +++++++ internal/journal/journal_test.go | 29 + internal/metrics/metrics.go | 21 + internal/protocol/proof.go | 76 +++ internal/protocol/proof_test.go | 37 ++ internal/redfish/adapter.go | 131 +++++ internal/redfish/handler.go | 354 ++++++++++++ internal/redfish/handler_test.go | 147 +++++ internal/relay/relay.go | 143 +++++ internal/relay/relay_test.go | 30 + .../machine-management/compose.openvpn.yaml | 4 + test/e2e/machine-management/compose.yaml | 21 + test/e2e/machine-management/generic-client.py | 29 + .../e2e/machine-management/kind-location.yaml | 11 + .../machine-management/kind-management.yaml | 4 + .../e2e/machine-management/openvpn/Dockerfile | 5 + .../machine-management/openvpn/client.yaml | 26 + .../machine-management/openvpn/entrypoint.sh | 12 + .../machine-management/seed/allocation.yaml | 24 + test/e2e/machine-management/seed/claim.yaml | 7 + .../seed/test-identities.yaml | 25 + test/e2e/machine-management/tools/Dockerfile | 9 + .../machine-management/virtual-bmc/Dockerfile | 15 + .../virtual-bmc/callback.py | 44 ++ .../virtual-bmc/emulator.conf | 6 + .../virtual-bmc/entrypoint.sh | 143 +++++ 77 files changed, 6380 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/test-e2e.yml create mode 100644 Dockerfile create mode 100644 Taskfile.yaml create mode 100644 api/v1alpha1/doc.go create mode 100644 api/v1alpha1/groupversion_info.go create mode 100644 api/v1alpha1/types.go create mode 100644 api/v1alpha1/zz_generated.deepcopy.go create mode 100644 cmd/datumctl-fleet/main.go create mode 100644 cmd/fleet-controller/main.go create mode 100644 cmd/fleet-gateway/main.go create mode 100644 cmd/fleet-relay/main.go create mode 100644 config/base/kustomization.yaml create mode 100644 config/base/namespaces.yaml create mode 100644 config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml create mode 100644 config/crd/bases/fleet.datumapis.com_machineclaims.yaml create mode 100644 config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml create mode 100644 config/crd/bases/fleet.datumapis.com_machinemanagementsessions.yaml create mode 100644 config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml create mode 100644 config/crd/kustomization.yaml create mode 100644 config/location/access.yaml create mode 100644 config/location/kustomization.yaml create mode 100644 config/location/networkpolicy.yaml create mode 100644 config/manager/controller.yaml create mode 100644 config/manager/kustomization.yaml create mode 100644 config/manager/networkpolicy.yaml create mode 100644 config/rbac/controller.yaml create mode 100644 config/rbac/projector-location.yaml create mode 100644 config/redfish/FleetProvisioning.v1_0_0.json create mode 100644 docs/implementation/machine-management-prototype.md create mode 100644 go.mod create mode 100644 go.sum create mode 100755 hack/e2e/diagnostics.sh create mode 100755 hack/e2e/down.sh create mode 100755 hack/e2e/openvpn-up.sh create mode 100755 hack/e2e/test.sh create mode 100755 hack/e2e/up.sh create mode 100755 hack/e2e/validators.sh create mode 100644 internal/cmd/fleet/root.go create mode 100644 internal/cmd/fleet/root_test.go create mode 100644 internal/controller/admission.go create mode 100644 internal/controller/admission_test.go create mode 100644 internal/controller/projection.go create mode 100644 internal/controller/projection_test.go create mode 100644 internal/controller/session.go create mode 100644 internal/controller/session_test.go create mode 100644 internal/gateway/gateway.go create mode 100644 internal/gateway/gateway_test.go create mode 100644 internal/journal/journal.go create mode 100644 internal/journal/journal_test.go create mode 100644 internal/metrics/metrics.go create mode 100644 internal/protocol/proof.go create mode 100644 internal/protocol/proof_test.go create mode 100644 internal/redfish/adapter.go create mode 100644 internal/redfish/handler.go create mode 100644 internal/redfish/handler_test.go create mode 100644 internal/relay/relay.go create mode 100644 internal/relay/relay_test.go create mode 100644 test/e2e/machine-management/compose.openvpn.yaml create mode 100644 test/e2e/machine-management/compose.yaml create mode 100755 test/e2e/machine-management/generic-client.py create mode 100644 test/e2e/machine-management/kind-location.yaml create mode 100644 test/e2e/machine-management/kind-management.yaml create mode 100644 test/e2e/machine-management/openvpn/Dockerfile create mode 100644 test/e2e/machine-management/openvpn/client.yaml create mode 100755 test/e2e/machine-management/openvpn/entrypoint.sh create mode 100644 test/e2e/machine-management/seed/allocation.yaml create mode 100644 test/e2e/machine-management/seed/claim.yaml create mode 100644 test/e2e/machine-management/seed/test-identities.yaml create mode 100644 test/e2e/machine-management/tools/Dockerfile create mode 100644 test/e2e/machine-management/virtual-bmc/Dockerfile create mode 100755 test/e2e/machine-management/virtual-bmc/callback.py create mode 100644 test/e2e/machine-management/virtual-bmc/emulator.conf create mode 100755 test/e2e/machine-management/virtual-bmc/entrypoint.sh diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml new file mode 100644 index 00000000..b028064e --- /dev/null +++ b/.github/workflows/test-e2e.yml @@ -0,0 +1,55 @@ +name: machine-management-e2e + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + virtual-bmc: + runs-on: ubuntu-24.04 + timeout-minutes: 50 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: Install pinned tools + run: | + curl -fsSL https://github.com/kubernetes-sigs/kind/releases/download/v0.33.0/kind-linux-amd64 -o /usr/local/bin/kind + curl -fsSL https://github.com/kubernetes-sigs/kind/releases/download/v0.33.0/kind-linux-amd64.sha256sum -o /tmp/kind.sha256 + sed 's#kind-linux-amd64#/usr/local/bin/kind#' /tmp/kind.sha256 | sha256sum -c - + chmod 0755 /usr/local/bin/kind + curl -fsSL https://dl.k8s.io/release/v1.37.0/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl + curl -fsSL https://dl.k8s.io/release/v1.37.0/bin/linux/amd64/kubectl.sha256 -o /tmp/kubectl.sha256 + echo "$(cat /tmp/kubectl.sha256) /usr/local/bin/kubectl" | sha256sum -c - + chmod 0755 /usr/local/bin/kubectl + go install github.com/go-task/task/v3/cmd/task@v3.41.0 + install -m 0755 "$(go env GOPATH)/bin/task" /usr/local/bin/task + - name: Portable tests + run: task test + - name: Start virtual-BMC environment + run: task e2e:up + - name: End-to-end scenarios + run: task e2e:test + - name: Collect diagnostics + if: failure() + run: task e2e:diagnostics + - name: Upload diagnostics and validator reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: fleet-machine-management-evidence + path: | + .e2e/diagnostics + .e2e/validators + .e2e/virtual-bmc/evidence + .e2e/*.log + if-no-files-found: ignore + - name: Tear down + if: always() + run: task e2e:down diff --git a/.gitignore b/.gitignore index 05020c7f..4fe1fec2 100644 --- a/.gitignore +++ b/.gitignore @@ -17,10 +17,18 @@ /servers.com.txt # Local outputs and scratch work +/bin/ +/.e2e/ +/.task/ /tmp/ /dist/ /coverage/ /worktrees/ +coverage.out +*.kubeconfig +credentials.json +ready.json +ca.pem # Local agent settings .claude/settings.local.json diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..ae0801ba --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +FROM golang:1.26.1-bookworm AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +ARG PACKAGE +ARG BINARY +RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/${BINARY} ${PACKAGE} + +FROM debian:12.12-slim +ARG BINARY +COPY --from=build /out/${BINARY} /usr/local/bin/app +USER 65532:65532 +ENTRYPOINT ["/usr/local/bin/app"] diff --git a/README.md b/README.md index 8b359b73..92af5d77 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,11 @@ It brings physical inventory, machine allocation, provisioning, operating system configuration, managed clusters, and node services into a shared service with explicit ownership and lifecycle boundaries. -This repository is the starting point for building that platform. It currently -contains design context and an implementation roadmap. There are no implemented -APIs, controllers, deployment manifests, or build/test commands yet. +This repository contains design context, an implementation roadmap, and one +deliberately narrow working prototype: allocation-scoped customer Redfish access. +The prototype is not a complete Fleet allocator, installer, or production BMC +service. Its synthetic allocation records preserve those proposed authority and +identity boundaries while exercising the access path end to end. ## Scope @@ -35,6 +37,38 @@ guest agent. Provisioning engines and provider integrations remain pluggable. product experience, allocation-scoped Redfish session architecture, security, routing, and provisional API design. - [Contributor guidance](AGENTS.md): repository conventions and key invariants. +- [Machine-management prototype](docs/implementation/machine-management-prototype.md): + implemented architecture, exact commands, trust boundaries, E2E environment, + verified behavior, troubleshooting, and production gaps. + +## Build and test + +Go 1.26.1 is the selected prototype toolchain. The module path is +`go.datum.net/fleet`; it follows Datum's current Go import convention without +asserting that the provisional APIs are a stable external contract. + +```console +task generate +task test +task build +``` + +The complete path requires Linux, Docker with Compose, Kind, kubectl, jq, +OpenSSL, curl, and Task. It builds all images locally and loads them into Kind; +it does not require a registry. + +```console +task e2e:up +task e2e:test +task e2e:test:path DIR=machine-management +task e2e:diagnostics +task e2e:openvpn:up +task e2e:down +``` + +`e2e:up` and `e2e:down` are idempotent. The latter removes only the two named +Kind clusters, the `fleet-bmc-e2e` Compose project, its isolated network, and +the repository-local `.e2e` directory. The foundation comes from open `datum-cloud/infra` PRs [#5782](https://github.com/datum-cloud/infra/pull/5782) and diff --git a/Taskfile.yaml b/Taskfile.yaml new file mode 100644 index 00000000..d9e48ff8 --- /dev/null +++ b/Taskfile.yaml @@ -0,0 +1,60 @@ +version: '3' + +vars: + GO_CACHE: '{{default "/tmp/fleet-go-cache" .GO_CACHE}}' + +tasks: + generate: + desc: Regenerate the provisional CRDs from Kubebuilder markers + cmds: + - go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.23.0 crd paths=./api/... output:crd:artifacts:config=config/crd/bases + + test: + desc: Run portable unit and API/controller integration tests + cmds: + - env GOCACHE={{.GO_CACHE}} go test ./... + - git diff --check + + build: + desc: Build every prototype executable + cmds: + - mkdir -p bin + - env GOCACHE={{.GO_CACHE}} go build -o bin/datumctl-fleet ./cmd/datumctl-fleet + - env GOCACHE={{.GO_CACHE}} go build -o bin/fleet-controller ./cmd/fleet-controller + - env GOCACHE={{.GO_CACHE}} go build -o bin/fleet-gateway ./cmd/fleet-gateway + - env GOCACHE={{.GO_CACHE}} go build -o bin/fleet-relay ./cmd/fleet-relay + + e2e:up: + desc: Create the two Kind clusters and real sushy/libvirt BMC environment + cmds: + - ./hack/e2e/up.sh + + e2e:test: + desc: Run every machine-management scenario and both DMTF validators + cmds: + - ./hack/e2e/test.sh + + e2e:test:path: + desc: Run one E2E path (currently DIR=machine-management) + requires: + vars: [DIR] + preconditions: + - sh: test '{{.DIR}}' = machine-management + msg: 'the only implemented E2E path is DIR=machine-management' + cmds: + - ./hack/e2e/test.sh + + e2e:diagnostics: + desc: Collect cluster, gateway, libvirt, and PXE evidence + cmds: + - ./hack/e2e/diagnostics.sh + + e2e:down: + desc: Remove only the named Fleet E2E resources + cmds: + - ./hack/e2e/down.sh + + e2e:openvpn:up: + desc: Replace the default private route with the separate OpenVPN qualification profile + cmds: + - ./hack/e2e/openvpn-up.sh diff --git a/api/v1alpha1/doc.go b/api/v1alpha1/doc.go new file mode 100644 index 00000000..3d265053 --- /dev/null +++ b/api/v1alpha1/doc.go @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 + +// +kubebuilder:object:generate=true +// +groupName=fleet.datumapis.com + +package v1alpha1 diff --git a/api/v1alpha1/groupversion_info.go b/api/v1alpha1/groupversion_info.go new file mode 100644 index 00000000..6309fc30 --- /dev/null +++ b/api/v1alpha1/groupversion_info.go @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package v1alpha1 contains the provisional Fleet machine-management APIs. +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var ( + GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + AddToScheme = SchemeBuilder.AddToScheme +) + +func addKnownTypes(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, + &MachineClaim{}, &MachineClaimList{}, + &MachineManagementSession{}, &MachineManagementSessionList{}, + &MachineAllocationBinding{}, &MachineAllocationBindingList{}, + &MachineManagementSessionBinding{}, &MachineManagementSessionBindingList{}, + &ProjectedMachineManagementSession{}, &ProjectedMachineManagementSessionList{}, + ) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} diff --git a/api/v1alpha1/types.go b/api/v1alpha1/types.go new file mode 100644 index 00000000..0b0c87cf --- /dev/null +++ b/api/v1alpha1/types.go @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: Apache-2.0 + +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" +) + +const ( + SessionFinalizer = "fleet.datumapis.com/machine-management-session" + ConditionReady = "Ready" +) + +// MachineClaim is the public allocation handle. The prototype seeds it; the +// protected MachineAllocationBinding remains the authoritative allocation. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type MachineClaim struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec MachineClaimSpec `json:"spec,omitempty"` + Status MachineClaimStatus `json:"status,omitempty"` +} + +type MachineClaimSpec struct { + MachineClassRef LocalObjectReference `json:"machineClassRef"` +} + +type MachineClaimStatus struct { + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +type LocalObjectReference struct { + Name string `json:"name"` +} + +// +kubebuilder:object:root=true +type MachineClaimList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineClaim `json:"items"` +} + +// MachineManagementSession is a short-lived public request for the machine +// currently bound to a claim. Resolved allocation details never enter it. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type MachineManagementSession struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="spec is immutable" + Spec MachineManagementSessionSpec `json:"spec"` + Status MachineManagementSessionStatus `json:"status,omitempty"` +} + +type MachineManagementSessionSpec struct { + MachineClaimRef LocalObjectReference `json:"machineClaimRef"` + // +kubebuilder:validation:Enum=Redfish + Protocol string `json:"protocol"` + // +kubebuilder:validation:Enum=Provisioning + AccessProfile string `json:"accessProfile"` + // +kubebuilder:validation:Pattern=`^[0-9a-f]{64}$` + ClientPublicKey string `json:"clientPublicKey"` + // +kubebuilder:validation:XValidation:rule="duration(self) >= duration('1m') && duration(self) <= duration('15m')",message="ttl must be between 1m and 15m" + TTL metav1.Duration `json:"ttl"` +} + +type MachineManagementSessionStatus struct { + Connection *SessionConnection `json:"connection,omitempty"` + ConnectBefore *metav1.Time `json:"connectBefore,omitempty"` + ExpiresAt *metav1.Time `json:"expiresAt,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// SessionConnection is non-secret rendezvous information. It never names a +// physical endpoint or adapter target. +type SessionConnection struct { + RelayURL string `json:"relayURL"` + RouteID string `json:"routeID"` + GatewayAudience string `json:"gatewayAudience"` + GatewayCertSHA256 string `json:"gatewayCertSHA256"` + ProtocolVersion string `json:"protocolVersion"` +} + +// +kubebuilder:object:root=true +type MachineManagementSessionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineManagementSession `json:"items"` +} + +// MachineAllocationBinding is synthetic prototype input owned by the allocator. +// It is protected in fleet-system and is never returned to customers. +// +kubebuilder:object:root=true +type MachineAllocationBinding struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec MachineAllocationBindingSpec `json:"spec"` +} + +type MachineAllocationBindingSpec struct { + ConsumerProjectUID types.UID `json:"consumerProjectUID"` + ProviderProjectUID types.UID `json:"providerProjectUID"` + ClaimNamespace string `json:"claimNamespace"` + ClaimName string `json:"claimName"` + ClaimUID types.UID `json:"claimUID"` + MachineName string `json:"machineName"` + MachineUID types.UID `json:"machineUID"` + BindingID string `json:"bindingID"` + BindingEpoch int64 `json:"bindingEpoch"` + LocationUID types.UID `json:"locationUID"` + LocationRevision string `json:"locationRevision"` + BareMetalMachineUID types.UID `json:"bareMetalMachineUID"` + AccessProfileRevision string `json:"accessProfileRevision"` + AdapterRoute string `json:"adapterRoute"` + BMCSystemID string `json:"bmcSystemID"` + Active bool `json:"active"` +} + +// +kubebuilder:object:root=true +type MachineAllocationBindingList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineAllocationBinding `json:"items"` +} + +// MachineManagementSessionBinding is the service-owned admission record. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type MachineManagementSessionBinding struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="admitted binding inputs are immutable" + Spec MachineManagementSessionBindingSpec `json:"spec"` + Status MachineManagementSessionBindingStatus `json:"status,omitempty"` +} + +type MachineManagementSessionBindingSpec struct { + SessionNamespace string `json:"sessionNamespace"` + SessionName string `json:"sessionName"` + SessionUID types.UID `json:"sessionUID"` + RequestingPrincipal string `json:"requestingPrincipal"` + ConsumerProjectUID types.UID `json:"consumerProjectUID"` + ProviderProjectUID types.UID `json:"providerProjectUID"` + ClaimName string `json:"claimName"` + ClaimUID types.UID `json:"claimUID"` + MachineName string `json:"machineName"` + MachineUID types.UID `json:"machineUID"` + BindingID string `json:"bindingID"` + BindingEpoch int64 `json:"bindingEpoch"` + LocationUID types.UID `json:"locationUID"` + LocationRevision string `json:"locationRevision"` + BareMetalMachineUID types.UID `json:"bareMetalMachineUID"` + AccessProfileRevision string `json:"accessProfileRevision"` + ClientPublicKey string `json:"clientPublicKey"` + ConnectBefore metav1.Time `json:"connectBefore"` + ExpiresAt metav1.Time `json:"expiresAt"` + SessionCorrelationID string `json:"sessionCorrelationID"` + OperationCorrelationID string `json:"operationCorrelationID"` + AdapterRoute string `json:"adapterRoute"` + BMCSystemID string `json:"bmcSystemID"` +} + +type MachineManagementSessionBindingStatus struct { + Connection *SessionConnection `json:"connection,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +type MachineManagementSessionBindingList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineManagementSessionBinding `json:"items"` +} + +// ProjectedMachineManagementSession is the least-privileged location copy. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type ProjectedMachineManagementSession struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec ProjectedMachineManagementSessionSpec `json:"spec"` + Status ProjectedMachineManagementSessionStatus `json:"status,omitempty"` +} + +type ProjectedMachineManagementSessionSpec struct { + SessionUID types.UID `json:"sessionUID"` + ClaimUID types.UID `json:"claimUID"` + MachineUID types.UID `json:"machineUID"` + BindingID string `json:"bindingID"` + BindingEpoch int64 `json:"bindingEpoch"` + LocationUID types.UID `json:"locationUID"` + LocationRevision string `json:"locationRevision"` + BareMetalMachineUID types.UID `json:"bareMetalMachineUID"` + AccessProfileRevision string `json:"accessProfileRevision"` + ClientPublicKey string `json:"clientPublicKey"` + ConnectBefore metav1.Time `json:"connectBefore"` + ExpiresAt metav1.Time `json:"expiresAt"` + AuthorityFreshUntil metav1.Time `json:"authorityFreshUntil"` + SessionCorrelationID string `json:"sessionCorrelationID"` + OperationCorrelationID string `json:"operationCorrelationID"` + AdapterRoute string `json:"adapterRoute"` + BMCSystemID string `json:"bmcSystemID"` +} + +type ProjectedMachineManagementSessionStatus struct { + Connection *SessionConnection `json:"connection,omitempty"` + ConnectedAt *metav1.Time `json:"connectedAt,omitempty"` + EndedAt *metav1.Time `json:"endedAt,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +type ProjectedMachineManagementSessionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ProjectedMachineManagementSession `json:"items"` +} diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 00000000..fe621bbb --- /dev/null +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 + +// This file is intentionally hand-maintained until generation is added to the +// repository. The JSON round-trip keeps the prototype correct for pointer, +// slice, map, and metav1 fields; `task generate` replaces it in production. +package v1alpha1 + +import ( + "encoding/json" + + "k8s.io/apimachinery/pkg/runtime" +) + +func copyJSON[T any](in *T) *T { + if in == nil { + return nil + } + b, err := json.Marshal(in) + if err != nil { + panic(err) + } + out := new(T) + if err := json.Unmarshal(b, out); err != nil { + panic(err) + } + return out +} + +func (in *MachineClaim) DeepCopy() *MachineClaim { return copyJSON(in) } +func (in *MachineClaim) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineClaimList) DeepCopy() *MachineClaimList { return copyJSON(in) } +func (in *MachineClaimList) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSession) DeepCopy() *MachineManagementSession { return copyJSON(in) } +func (in *MachineManagementSession) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionList) DeepCopy() *MachineManagementSessionList { return copyJSON(in) } +func (in *MachineManagementSessionList) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineAllocationBinding) DeepCopy() *MachineAllocationBinding { return copyJSON(in) } +func (in *MachineAllocationBinding) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineAllocationBindingList) DeepCopy() *MachineAllocationBindingList { return copyJSON(in) } +func (in *MachineAllocationBindingList) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionBinding) DeepCopy() *MachineManagementSessionBinding { + return copyJSON(in) +} +func (in *MachineManagementSessionBinding) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionBindingList) DeepCopy() *MachineManagementSessionBindingList { + return copyJSON(in) +} +func (in *MachineManagementSessionBindingList) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *ProjectedMachineManagementSession) DeepCopy() *ProjectedMachineManagementSession { + return copyJSON(in) +} +func (in *ProjectedMachineManagementSession) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *ProjectedMachineManagementSessionList) DeepCopy() *ProjectedMachineManagementSessionList { + return copyJSON(in) +} +func (in *ProjectedMachineManagementSessionList) DeepCopyObject() runtime.Object { + return in.DeepCopy() +} diff --git a/cmd/datumctl-fleet/main.go b/cmd/datumctl-fleet/main.go new file mode 100644 index 00000000..293df11a --- /dev/null +++ b/cmd/datumctl-fleet/main.go @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "errors" + "fmt" + "os" + + "go.datum.net/datumctl/plugin" + + fleetcmd "go.datum.net/fleet/internal/cmd/fleet" +) + +var version = "dev" + +func main() { + plugin.ServeManifest(plugin.Manifest{Name: "fleet", Version: version, Description: "Manage Datum Fleet machines and secure management sessions", APIVersion: 1, MinAPIVersion: 1}) + if err := fleetcmd.Command().Execute(); err != nil { + var exit *fleetcmd.ExitError + if errors.As(err, &exit) { + fmt.Fprintln(os.Stderr, "Error:", exit.Err) + os.Exit(exit.Code) + } + fmt.Fprintln(os.Stderr, "Error:", err) + os.Exit(1) + } +} diff --git a/cmd/fleet-controller/main.go b/cmd/fleet-controller/main.go new file mode 100644 index 00000000..18ebbf5d --- /dev/null +++ b/cmd/fleet-controller/main.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "flag" + "log/slog" + "os" + "time" + + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/clientcmd" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/healthz" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + "go.datum.net/fleet/internal/controller" +) + +func main() { + locationKubeconfig := flag.String("location-kubeconfig", "", "kubeconfig for the authoritative location cluster") + webhookCertDir := flag.String("webhook-cert-dir", "/var/run/fleet-webhook", "webhook serving certificate directory") + metrics := flag.String("metrics-bind-address", ":8080", "metrics address") + probe := flag.String("health-probe-bind-address", ":8081", "probe address") + authorityFreshness := flag.Duration("authority-freshness", 2*time.Minute, "maximum cached allocation-authority lifetime at a location") + perClaimLimit := flag.Int("per-claim-session-limit", 1, "maximum concurrent sessions for one claim") + perProjectLimit := flag.Int("per-project-session-limit", 5, "maximum concurrent sessions for one consumer project") + flag.Parse() + if *locationKubeconfig == "" { + slog.Error("--location-kubeconfig is required") + os.Exit(2) + } + scheme := runtime.NewScheme() + must(clientgoscheme.AddToScheme(scheme)) + must(fleetv1alpha1.AddToScheme(scheme)) + locationConfig, err := clientcmd.BuildConfigFromFlags("", *locationKubeconfig) + must(err) + locationClient, err := client.New(locationConfig, client.Options{Scheme: scheme}) + must(err) + wh := webhook.NewServer(webhook.Options{CertDir: *webhookCertDir}) + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{Scheme: scheme, Metrics: metricsserver.Options{BindAddress: *metrics}, HealthProbeBindAddress: *probe, WebhookServer: wh}) + must(err) + mgr.GetWebhookServer().Register("/mutate-fleet-datumapis-com-v1alpha1-machinemanagementsession", &admission.Webhook{Handler: controller.SessionAdmission{}}) + must((&controller.SessionReconciler{PerClaimLimit: *perClaimLimit, PerProjectLimit: *perProjectLimit}).SetupWithManager(mgr)) + must((&controller.ProjectionReconciler{LocationClient: locationClient, Freshness: *authorityFreshness}).SetupWithManager(mgr)) + must(mgr.AddHealthzCheck("healthz", healthz.Ping)) + must(mgr.AddReadyzCheck("readyz", healthz.Ping)) + slog.Info("starting Fleet session controllers") + must(mgr.Start(ctrl.SetupSignalHandler())) +} + +func must(err error) { + if err != nil { + slog.Error("fatal", "error", err) + os.Exit(1) + } +} diff --git a/cmd/fleet-gateway/main.go b/cmd/fleet-gateway/main.go new file mode 100644 index 00000000..86f922dd --- /dev/null +++ b/cmd/fleet-gateway/main.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "flag" + "log/slog" + "os" + "strings" + + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/healthz" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + "go.datum.net/fleet/internal/gateway" +) + +func main() { + var cfg gateway.Config + var tokenFile, userFile, passwordFile string + flag.StringVar(&cfg.RelayAddress, "relay-address", "fleet-relay.machine-access-system.svc:8443", "relay address") + flag.StringVar(&cfg.RelayPublicURL, "relay-public-url", "tcp://127.0.0.1:8443", "client-visible relay URL") + flag.StringVar(&tokenFile, "relay-token-file", "/var/run/secrets/fleet/relay-token", "relay registration token") + flag.StringVar(&cfg.Audience, "audience", "fleet-gateway/location-prototype/r1", "proof audience") + flag.StringVar(&cfg.AdapterRoute, "adapter-route", "sushy-libvirt-v1", "qualified adapter route") + flag.StringVar(&cfg.BMCBaseURL, "bmc-url", "http://sushy-emulator:8000", "private sushy-emulator URL") + flag.StringVar(&userFile, "bmc-username-file", "/var/run/secrets/fleet/bmc-username", "BMC username file") + flag.StringVar(&passwordFile, "bmc-password-file", "/var/run/secrets/fleet/bmc-password", "BMC password file") + flag.StringVar(&cfg.JournalDir, "journal-dir", "/var/lib/fleet", "durable journal directory") + flag.StringVar(&cfg.StateDir, "state-dir", "/var/lib/fleet/sessions", "gateway state directory") + flag.BoolVar(&cfg.DropResetResponseOnce, "fault-drop-reset-response-once", false, "test-only lost response injection") + metrics := flag.String("metrics-bind-address", ":8080", "metrics address") + probe := flag.String("health-probe-bind-address", ":8081", "probe address") + flag.Parse() + cfg.RelayGatewayToken = readSecret(tokenFile) + cfg.BMCUsername = readSecret(userFile) + cfg.BMCPassword = readSecret(passwordFile) + scheme := runtime.NewScheme() + must(clientgoscheme.AddToScheme(scheme)) + must(fleetv1alpha1.AddToScheme(scheme)) + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ + Scheme: scheme, + Cache: cache.Options{DefaultNamespaces: map[string]cache.Config{ + "machine-access-system": {}, + }}, + Metrics: metricsserver.Options{BindAddress: *metrics}, + HealthProbeBindAddress: *probe, + }) + must(err) + must((&gateway.Reconciler{Config: cfg}).SetupWithManager(mgr)) + must(mgr.AddHealthzCheck("healthz", healthz.Ping)) + must(mgr.AddReadyzCheck("readyz", healthz.Ping)) + slog.Info("starting location gateway", "audience", cfg.Audience, "adapterRoute", cfg.AdapterRoute) + must(mgr.Start(ctrl.SetupSignalHandler())) +} +func readSecret(path string) string { + b, err := os.ReadFile(path) + must(err) + return strings.TrimSpace(string(b)) +} +func must(err error) { + if err != nil { + slog.Error("fatal", "error", err) + os.Exit(1) + } +} diff --git a/cmd/fleet-relay/main.go b/cmd/fleet-relay/main.go new file mode 100644 index 00000000..6c10b731 --- /dev/null +++ b/cmd/fleet-relay/main.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "flag" + "log/slog" + "net" + "os" + "strings" + + "go.datum.net/fleet/internal/relay" +) + +func main() { + addr := flag.String("listen", ":8443", "relay TCP listen address") + tokenFile := flag.String("gateway-token-file", "/var/run/secrets/fleet/relay-token", "gateway registration token file") + flag.Parse() + token, err := os.ReadFile(*tokenFile) + if err != nil { + slog.Error("read gateway token", "error", err) + os.Exit(1) + } + l, err := net.Listen("tcp", *addr) + if err != nil { + slog.Error("listen", "error", err) + os.Exit(1) + } + slog.Info("relay listening", "address", l.Addr().String()) + if err := relay.NewServer(strings.TrimSpace(string(token))).Serve(l); err != nil { + slog.Error("serve relay", "error", err) + os.Exit(1) + } +} diff --git a/config/base/kustomization.yaml b/config/base/kustomization.yaml new file mode 100644 index 00000000..a1eee58b --- /dev/null +++ b/config/base/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - namespaces.yaml diff --git a/config/base/namespaces.yaml b/config/base/namespaces.yaml new file mode 100644 index 00000000..73d8be91 --- /dev/null +++ b/config/base/namespaces.yaml @@ -0,0 +1,17 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-system + labels: + pod-security.kubernetes.io/enforce: restricted + pod-security.kubernetes.io/audit: restricted + pod-security.kubernetes.io/warn: restricted +--- +apiVersion: v1 +kind: Namespace +metadata: + name: machine-access-system + labels: + pod-security.kubernetes.io/enforce: restricted + pod-security.kubernetes.io/audit: restricted + pod-security.kubernetes.io/warn: restricted diff --git a/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml b/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml new file mode 100644 index 00000000..63b85d74 --- /dev/null +++ b/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml @@ -0,0 +1,122 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: machineallocationbindings.fleet.datumapis.com +spec: + group: fleet.datumapis.com + names: + kind: MachineAllocationBinding + listKind: MachineAllocationBindingList + plural: machineallocationbindings + singular: machineallocationbinding + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + MachineAllocationBinding is synthetic prototype input owned by the allocator. + It is protected in fleet-system and is never returned to customers. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + properties: + accessProfileRevision: + type: string + active: + type: boolean + adapterRoute: + type: string + bareMetalMachineUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + bindingEpoch: + format: int64 + type: integer + bindingID: + type: string + bmcSystemID: + type: string + claimName: + type: string + claimNamespace: + type: string + claimUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + consumerProjectUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + locationRevision: + type: string + locationUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + machineName: + type: string + machineUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + providerProjectUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + required: + - accessProfileRevision + - active + - adapterRoute + - bareMetalMachineUID + - bindingEpoch + - bindingID + - bmcSystemID + - claimName + - claimNamespace + - claimUID + - consumerProjectUID + - locationRevision + - locationUID + - machineName + - machineUID + - providerProjectUID + type: object + required: + - spec + type: object + served: true + storage: true diff --git a/config/crd/bases/fleet.datumapis.com_machineclaims.yaml b/config/crd/bases/fleet.datumapis.com_machineclaims.yaml new file mode 100644 index 00000000..82067e83 --- /dev/null +++ b/config/crd/bases/fleet.datumapis.com_machineclaims.yaml @@ -0,0 +1,116 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: machineclaims.fleet.datumapis.com +spec: + group: fleet.datumapis.com + names: + kind: MachineClaim + listKind: MachineClaimList + plural: machineclaims + singular: machineclaim + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + MachineClaim is the public allocation handle. The prototype seeds it; the + protected MachineAllocationBinding remains the authoritative allocation. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + properties: + machineClassRef: + properties: + name: + type: string + required: + - name + type: object + required: + - machineClassRef + type: object + status: + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml b/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml new file mode 100644 index 00000000..e90dc6da --- /dev/null +++ b/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml @@ -0,0 +1,234 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: machinemanagementsessionbindings.fleet.datumapis.com +spec: + group: fleet.datumapis.com + names: + kind: MachineManagementSessionBinding + listKind: MachineManagementSessionBindingList + plural: machinemanagementsessionbindings + singular: machinemanagementsessionbinding + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: MachineManagementSessionBinding is the service-owned admission + record. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + properties: + accessProfileRevision: + type: string + adapterRoute: + type: string + bareMetalMachineUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + bindingEpoch: + format: int64 + type: integer + bindingID: + type: string + bmcSystemID: + type: string + claimName: + type: string + claimUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + clientPublicKey: + type: string + connectBefore: + format: date-time + type: string + consumerProjectUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + expiresAt: + format: date-time + type: string + locationRevision: + type: string + locationUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + machineName: + type: string + machineUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + operationCorrelationID: + type: string + providerProjectUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + requestingPrincipal: + type: string + sessionCorrelationID: + type: string + sessionName: + type: string + sessionNamespace: + type: string + sessionUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + required: + - accessProfileRevision + - adapterRoute + - bareMetalMachineUID + - bindingEpoch + - bindingID + - bmcSystemID + - claimName + - claimUID + - clientPublicKey + - connectBefore + - consumerProjectUID + - expiresAt + - locationRevision + - locationUID + - machineName + - machineUID + - operationCorrelationID + - providerProjectUID + - requestingPrincipal + - sessionCorrelationID + - sessionName + - sessionNamespace + - sessionUID + type: object + x-kubernetes-validations: + - message: admitted binding inputs are immutable + rule: self == oldSelf + status: + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + connection: + description: |- + SessionConnection is non-secret rendezvous information. It never names a + physical endpoint or adapter target. + properties: + gatewayAudience: + type: string + gatewayCertSHA256: + type: string + protocolVersion: + type: string + relayURL: + type: string + routeID: + type: string + required: + - gatewayAudience + - gatewayCertSHA256 + - protocolVersion + - relayURL + - routeID + type: object + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/fleet.datumapis.com_machinemanagementsessions.yaml b/config/crd/bases/fleet.datumapis.com_machinemanagementsessions.yaml new file mode 100644 index 00000000..38525424 --- /dev/null +++ b/config/crd/bases/fleet.datumapis.com_machinemanagementsessions.yaml @@ -0,0 +1,169 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: machinemanagementsessions.fleet.datumapis.com +spec: + group: fleet.datumapis.com + names: + kind: MachineManagementSession + listKind: MachineManagementSessionList + plural: machinemanagementsessions + singular: machinemanagementsession + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + MachineManagementSession is a short-lived public request for the machine + currently bound to a claim. Resolved allocation details never enter it. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + properties: + accessProfile: + enum: + - Provisioning + type: string + clientPublicKey: + pattern: ^[0-9a-f]{64}$ + type: string + machineClaimRef: + properties: + name: + type: string + required: + - name + type: object + protocol: + enum: + - Redfish + type: string + ttl: + type: string + x-kubernetes-validations: + - message: ttl must be between 1m and 15m + rule: duration(self) >= duration('1m') && duration(self) <= duration('15m') + required: + - accessProfile + - clientPublicKey + - machineClaimRef + - protocol + - ttl + type: object + x-kubernetes-validations: + - message: spec is immutable + rule: self == oldSelf + status: + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + connectBefore: + format: date-time + type: string + connection: + description: |- + SessionConnection is non-secret rendezvous information. It never names a + physical endpoint or adapter target. + properties: + gatewayAudience: + type: string + gatewayCertSHA256: + type: string + protocolVersion: + type: string + relayURL: + type: string + routeID: + type: string + required: + - gatewayAudience + - gatewayCertSHA256 + - protocolVersion + - relayURL + - routeID + type: object + expiresAt: + format: date-time + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml b/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml new file mode 100644 index 00000000..18b61e60 --- /dev/null +++ b/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml @@ -0,0 +1,212 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: projectedmachinemanagementsessions.fleet.datumapis.com +spec: + group: fleet.datumapis.com + names: + kind: ProjectedMachineManagementSession + listKind: ProjectedMachineManagementSessionList + plural: projectedmachinemanagementsessions + singular: projectedmachinemanagementsession + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: ProjectedMachineManagementSession is the least-privileged location + copy. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + properties: + accessProfileRevision: + type: string + adapterRoute: + type: string + authorityFreshUntil: + format: date-time + type: string + bareMetalMachineUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + bindingEpoch: + format: int64 + type: integer + bindingID: + type: string + bmcSystemID: + type: string + claimUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + clientPublicKey: + type: string + connectBefore: + format: date-time + type: string + expiresAt: + format: date-time + type: string + locationRevision: + type: string + locationUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + machineUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + operationCorrelationID: + type: string + sessionCorrelationID: + type: string + sessionUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + required: + - accessProfileRevision + - adapterRoute + - authorityFreshUntil + - bareMetalMachineUID + - bindingEpoch + - bindingID + - bmcSystemID + - claimUID + - clientPublicKey + - connectBefore + - expiresAt + - locationRevision + - locationUID + - machineUID + - operationCorrelationID + - sessionCorrelationID + - sessionUID + type: object + status: + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + connectedAt: + format: date-time + type: string + connection: + description: |- + SessionConnection is non-secret rendezvous information. It never names a + physical endpoint or adapter target. + properties: + gatewayAudience: + type: string + gatewayCertSHA256: + type: string + protocolVersion: + type: string + relayURL: + type: string + routeID: + type: string + required: + - gatewayAudience + - gatewayCertSHA256 + - protocolVersion + - relayURL + - routeID + type: object + endedAt: + format: date-time + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml new file mode 100644 index 00000000..b4a56aed --- /dev/null +++ b/config/crd/kustomization.yaml @@ -0,0 +1,8 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - bases/fleet.datumapis.com_machineclaims.yaml + - bases/fleet.datumapis.com_machinemanagementsessions.yaml + - bases/fleet.datumapis.com_machineallocationbindings.yaml + - bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml + - bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml diff --git a/config/location/access.yaml b/config/location/access.yaml new file mode 100644 index 00000000..b197a60e --- /dev/null +++ b/config/location/access.yaml @@ -0,0 +1,108 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-relay + namespace: machine-access-system +spec: + replicas: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-relay} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-relay} + spec: + automountServiceAccountToken: false + securityContext: {seccompProfile: {type: RuntimeDefault}, runAsNonRoot: true, fsGroup: 65532, fsGroupChangePolicy: OnRootMismatch} + containers: + - name: relay + image: fleet-relay:e2e + imagePullPolicy: IfNotPresent + args: ["--listen=:8443", "--gateway-token-file=/var/run/secrets/fleet/relay-token"] + ports: [{name: relay, containerPort: 8443}] + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 65532 + resources: + requests: {cpu: 10m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: [{name: relay-token, mountPath: /var/run/secrets/fleet, readOnly: true}] + volumes: [{name: relay-token, secret: {secretName: fleet-relay-token, defaultMode: 0440}}] +--- +apiVersion: v1 +kind: Service +metadata: + name: fleet-relay + namespace: machine-access-system +spec: + type: NodePort + selector: {app.kubernetes.io/name: fleet-relay} + ports: [{name: relay, port: 8443, targetPort: relay, nodePort: 30443}] +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-gateway + namespace: machine-access-system +spec: + replicas: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-gateway} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-gateway} + spec: + serviceAccountName: fleet-gateway + securityContext: {seccompProfile: {type: RuntimeDefault}, runAsNonRoot: true, fsGroup: 65532, fsGroupChangePolicy: OnRootMismatch} + containers: + - name: gateway + image: fleet-gateway:e2e + imagePullPolicy: IfNotPresent + args: + - --relay-address=fleet-relay.machine-access-system.svc:8443 + - --relay-public-url=tcp://127.0.0.1:30443 + - --relay-token-file=/var/run/secrets/fleet/relay-token + - --audience=fleet-gateway/location-prototype/r1 + - --adapter-route=sushy-libvirt-v1 + - --bmc-url=http://172.30.0.10:8000 + - --bmc-username-file=/var/run/secrets/fleet/bmc-username + - --bmc-password-file=/var/run/secrets/fleet/bmc-password + - --journal-dir=/var/lib/fleet + ports: [{name: metrics, containerPort: 8080}, {name: health, containerPort: 8081}] + livenessProbe: {httpGet: {path: /healthz, port: health}} + readinessProbe: {httpGet: {path: /readyz, port: health}} + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 65532 + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: credentials, mountPath: /var/run/secrets/fleet, readOnly: true} + - {name: journal, mountPath: /var/lib/fleet} + - {name: tmp, mountPath: /tmp} + volumes: + - name: credentials + projected: + defaultMode: 0440 + sources: + - secret: {name: fleet-relay-token} + - secret: {name: fleet-bmc-credentials} + - name: journal + persistentVolumeClaim: {claimName: fleet-gateway-journal} + - name: tmp + emptyDir: {} +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: fleet-gateway-journal + namespace: machine-access-system +spec: + accessModes: [ReadWriteOnce] + resources: {requests: {storage: 256Mi}} diff --git a/config/location/kustomization.yaml b/config/location/kustomization.yaml new file mode 100644 index 00000000..37080e28 --- /dev/null +++ b/config/location/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../base + - access.yaml + - networkpolicy.yaml diff --git a/config/location/networkpolicy.yaml b/config/location/networkpolicy.yaml new file mode 100644 index 00000000..af95f126 --- /dev/null +++ b/config/location/networkpolicy.yaml @@ -0,0 +1,43 @@ +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: default-deny + namespace: machine-access-system +spec: + podSelector: {} + policyTypes: [Ingress, Egress] +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: relay + namespace: machine-access-system +spec: + podSelector: {matchLabels: {app.kubernetes.io/name: fleet-relay}} + policyTypes: [Ingress, Egress] + ingress: + - ports: [{protocol: TCP, port: 8443}] + egress: [] +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: gateway + namespace: machine-access-system +spec: + podSelector: {matchLabels: {app.kubernetes.io/name: fleet-gateway}} + policyTypes: [Ingress, Egress] + ingress: [] + egress: + - to: [{podSelector: {matchLabels: {app.kubernetes.io/name: fleet-relay}}}] + ports: [{protocol: TCP, port: 8443}] + - to: [{ipBlock: {cidr: 172.30.0.10/32}}] + ports: [{protocol: TCP, port: 8000}] + - to: [{ipBlock: {cidr: 10.88.0.1/32}}] + ports: [{protocol: TCP, port: 8000}] + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}} + podSelector: {matchLabels: {k8s-app: kube-dns}} + ports: [{protocol: UDP, port: 53}, {protocol: TCP, port: 53}] + - to: [{ipBlock: {cidr: 10.96.0.1/32}}] + ports: [{protocol: TCP, port: 443}] diff --git a/config/manager/controller.yaml b/config/manager/controller.yaml new file mode 100644 index 00000000..64cb8b11 --- /dev/null +++ b/config/manager/controller.yaml @@ -0,0 +1,88 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-controller + namespace: fleet-system +spec: + replicas: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-controller} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-controller} + spec: + serviceAccountName: fleet-controller + securityContext: + seccompProfile: {type: RuntimeDefault} + runAsNonRoot: true + fsGroup: 65532 + fsGroupChangePolicy: OnRootMismatch + containers: + - name: controller + image: fleet-controller:e2e + imagePullPolicy: IfNotPresent + args: + - --location-kubeconfig=/var/run/fleet-location/kubeconfig + - --webhook-cert-dir=/var/run/fleet-webhook + # Test-only short window; the binary's product-oriented default is 2m. + - --authority-freshness=15s + # Lower than the product-oriented default so E2E can prove the limit. + - --per-project-session-limit=2 + ports: + - {name: webhook, containerPort: 9443} + - {name: metrics, containerPort: 8080} + - {name: health, containerPort: 8081} + livenessProbe: {httpGet: {path: /healthz, port: health}} + readinessProbe: {httpGet: {path: /readyz, port: health}} + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 65532 + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: location, mountPath: /var/run/fleet-location, readOnly: true} + - {name: webhook, mountPath: /var/run/fleet-webhook, readOnly: true} + - {name: tmp, mountPath: /tmp} + volumes: + - name: location + secret: {secretName: fleet-location-kubeconfig, defaultMode: 0440} + - name: webhook + secret: {secretName: fleet-webhook-tls, defaultMode: 0440} + - name: tmp + emptyDir: {} +--- +apiVersion: v1 +kind: Service +metadata: + name: fleet-webhook + namespace: fleet-system +spec: + selector: {app.kubernetes.io/name: fleet-controller} + ports: + - {name: https, port: 443, targetPort: webhook} +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingWebhookConfiguration +metadata: + name: fleet-machine-management-session +webhooks: + - name: mmssessions.fleet.datumapis.com + admissionReviewVersions: [v1] + sideEffects: None + failurePolicy: Fail + matchPolicy: Equivalent + clientConfig: + service: + namespace: fleet-system + name: fleet-webhook + path: /mutate-fleet-datumapis-com-v1alpha1-machinemanagementsession + rules: + - apiGroups: [fleet.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE] + resources: [machinemanagementsessions] + scope: Namespaced diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml new file mode 100644 index 00000000..b64d416c --- /dev/null +++ b/config/manager/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../base + - controller.yaml + - networkpolicy.yaml diff --git a/config/manager/networkpolicy.yaml b/config/manager/networkpolicy.yaml new file mode 100644 index 00000000..d50da2b2 --- /dev/null +++ b/config/manager/networkpolicy.yaml @@ -0,0 +1,20 @@ +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: fleet-controller + namespace: fleet-system +spec: + podSelector: {matchLabels: {app.kubernetes.io/name: fleet-controller}} + policyTypes: [Ingress, Egress] + ingress: + - from: [{ipBlock: {cidr: 172.16.0.0/12}}] + ports: [{protocol: TCP, port: 9443}] + egress: + - to: [{ipBlock: {cidr: 10.96.0.1/32}}] + ports: [{protocol: TCP, port: 443}] + - to: [{ipBlock: {cidr: 172.16.0.0/12}}] + ports: [{protocol: TCP, port: 6443}] + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}} + podSelector: {matchLabels: {k8s-app: kube-dns}} + ports: [{protocol: UDP, port: 53}, {protocol: TCP, port: 53}] diff --git a/config/rbac/controller.yaml b/config/rbac/controller.yaml new file mode 100644 index 00000000..6aa1b9f4 --- /dev/null +++ b/config/rbac/controller.yaml @@ -0,0 +1,96 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-controller + namespace: fleet-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-session-controller +rules: + - apiGroups: [fleet.datumapis.com] + resources: [machinemanagementsessions, machineclaims] + verbs: [get, list, watch] + # The controller writes only metadata finalizers on the public object. CEL + # validation keeps the customer-authored spec immutable. + - apiGroups: [fleet.datumapis.com] + resources: [machinemanagementsessions] + verbs: [update, patch] + - apiGroups: [fleet.datumapis.com] + resources: [machinemanagementsessions/status] + verbs: [get, update, patch] + - apiGroups: [fleet.datumapis.com] + resources: [machinemanagementsessions/finalizers] + verbs: [update, patch] + - apiGroups: [fleet.datumapis.com] + resources: [machineallocationbindings, machinemanagementsessionbindings] + verbs: [get, list, watch, create, update, patch] + - apiGroups: [fleet.datumapis.com] + resources: [machinemanagementsessionbindings/status] + verbs: [get, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: fleet-session-controller +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: fleet-session-controller +subjects: + - kind: ServiceAccount + name: fleet-controller + namespace: fleet-system +--- +# Claim read and management-session creation are deliberately separate grants. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-machineclaim-viewer +rules: + - apiGroups: [fleet.datumapis.com] + resources: [machineclaims] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-machine-management-session-creator +rules: + - apiGroups: [fleet.datumapis.com] + resources: [machinemanagementsessions] + verbs: [create, get, list, watch, delete] +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-gateway + namespace: machine-access-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-gateway + namespace: machine-access-system +rules: + - apiGroups: [fleet.datumapis.com] + resources: [projectedmachinemanagementsessions] + verbs: [get, list, watch] + - apiGroups: [fleet.datumapis.com] + resources: [projectedmachinemanagementsessions/status] + verbs: [get, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-gateway + namespace: machine-access-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-gateway +subjects: + - kind: ServiceAccount + name: fleet-gateway + namespace: machine-access-system diff --git a/config/rbac/projector-location.yaml b/config/rbac/projector-location.yaml new file mode 100644 index 00000000..9cc22286 --- /dev/null +++ b/config/rbac/projector-location.yaml @@ -0,0 +1,32 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-projector + namespace: machine-access-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-projector + namespace: machine-access-system +rules: + - apiGroups: [fleet.datumapis.com] + resources: [projectedmachinemanagementsessions] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [fleet.datumapis.com] + resources: [projectedmachinemanagementsessions/status] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-projector + namespace: machine-access-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-projector +subjects: + - kind: ServiceAccount + name: fleet-projector + namespace: machine-access-system diff --git a/config/redfish/FleetProvisioning.v1_0_0.json b/config/redfish/FleetProvisioning.v1_0_0.json new file mode 100644 index 00000000..1d117ae3 --- /dev/null +++ b/config/redfish/FleetProvisioning.v1_0_0.json @@ -0,0 +1,47 @@ +{ + "SchemaDefinition": "RedfishInteroperabilityProfile.v1_9_0", + "ProfileName": "FleetProvisioning", + "ProfileVersion": "1.0.0", + "OwningEntity": "Datum Technology, Inc.", + "Purpose": "Allocation-scoped virtual Redfish for one-time PXE or local-disk boot and bounded power operations.", + "License": "Apache-2.0", + "Protocol": { + "MinVersion": "1.18.0" + }, + "Resources": { + "ServiceRoot": { + "MinVersion": "1.15.0", + "ReadRequirement": "Mandatory", + "URIs": ["/redfish/v1/"], + "PropertyRequirements": { + "RedfishVersion": {"ReadRequirement": "Mandatory"}, + "Systems": {"ReadRequirement": "Mandatory"}, + "SessionService": {"ReadRequirement": "Mandatory"}, + "TaskService": {"ReadRequirement": "Mandatory"} + } + }, + "ComputerSystem": { + "MinVersion": "1.20.0", + "ReadRequirement": "Mandatory", + "URIs": ["/redfish/v1/Systems/{ComputerSystemId}"], + "PropertyRequirements": { + "PowerState": {"ReadRequirement": "Mandatory"}, + "Boot": {"ReadRequirement": "Mandatory"}, + "Actions": {"ReadRequirement": "Mandatory"} + }, + "ActionRequirements": { + "Reset": {"ReadRequirement": "Mandatory"} + } + }, + "SessionService": { + "MinVersion": "1.2.0", + "ReadRequirement": "Mandatory", + "URIs": ["/redfish/v1/SessionService"] + }, + "TaskService": { + "MinVersion": "1.2.0", + "ReadRequirement": "Mandatory", + "URIs": ["/redfish/v1/TaskService"] + } + } +} diff --git a/docs/design.md b/docs/design.md index 42978bcf..aa4391db 100644 --- a/docs/design.md +++ b/docs/design.md @@ -3,6 +3,11 @@ Reviewed on 2026-10-27. This is a synthesis for implementation planning, not a replacement for the source proposals or a claim that their APIs exist. +The [secure machine-management prototype](implementation/machine-management-prototype.md) +is the first concrete implementation. It intentionally uses synthetic, +pre-bound allocation input and does not turn the proposal's illustrative APIs +into accepted product contracts. + ## Source proposals | Source | Reviewed revision | Contribution | @@ -29,7 +34,8 @@ and coordinated changes above that shared service. ## Subsystem boundaries -All names below describe proposed resources, not implemented schemas. +Except for the explicitly documented machine-management prototype, names below +describe proposed resources, not implemented schemas. | Subsystem | Responsibilities and principal resources | | --- | --- | @@ -146,9 +152,10 @@ inventory remains finite and reports `InsufficientCapacity` when exhausted. - **Node service policy:** Resolve permitted roles, runtime/template privileges, region scoping, and the remaining regional DNS writer work. - **Repository ownership:** Source text uses `milo-os/fleet` in implementation - examples and leaves subsystem ownership open. This local `fleet` repository is - the requested starting point; remote organization, module path, license, and - any provider repository split still need to be chosen. + examples and leaves subsystem ownership open. The prototype selects + `go.datum.net/fleet` to match Datum Go conventions. Repository ownership, + stable API import guarantees, license policy, and any provider split still + require product decisions. The [review of #7705][node-review] requested clarity on readiness, regional rollout, fencing, and procurement policy. Its latest text addresses those points with the diff --git a/docs/implementation/machine-management-prototype.md b/docs/implementation/machine-management-prototype.md new file mode 100644 index 00000000..1dfb7a8d --- /dev/null +++ b/docs/implementation/machine-management-prototype.md @@ -0,0 +1,194 @@ +# Secure machine-management prototype + +Status: implemented prototype; portable tests are runnable on macOS and Linux, +while the full sushy/libvirt path is Linux-only. This document records what the +repository implements. The [enhancement](../enhancements/secure-bmc-access.md) +remains the proposed product contract and is not weakened by the shortcuts here. + +## Architecture and trust boundaries + +The customer runs the real `datumctl` binary. Its plugin dispatcher finds the +first-party `datumctl-fleet` executable. The plugin receives project context from +datumctl, obtains its bearer credential only through `plugin.Token()`, generates +an ephemeral Ed25519 key pair, and creates a public +`MachineManagementSession`. It never reads `DATUM_TOKEN`. + +The management-cluster controller authenticates through the Kubernetes delegated +request identity retained by the mutating admission webhook. Kubernetes RBAC +provides the prototype authorization decision: `machineclaims` read and +`machinemanagementsessions` create are separate grants. The controller resolves +the claim against a service-owned `MachineAllocationBinding` and creates a +protected `MachineManagementSessionBinding`. The latter pins the principal, +consumer and provider Project UIDs, claim and machine name/UID pairs, binding ID +and epoch, location UID/revision, private BareMetalMachine UID, profile revision, +client key, deadlines, adapter route, and correlation IDs. None of the private +target fields are copied to the public session. + +The projector writes a least-privileged session to the location API and refreshes +only its cached-authority deadline while every pinned input still matches. The +location gateway registers an outbound opaque route with the relay. Public status +contains only its relay URL, random route, proof audience, protocol version, and +gateway certificate fingerprint. The central API and controllers are not in the +Redfish request/response path. + +The client consumes the route once, pins the per-session gateway TLS certificate, +and signs every request with a timestamped, nonce-bearing, domain-separated +Ed25519 proof. The gateway rejects changed inputs, audiences, expired timestamps, +nonce replay, stale authority, and adapter-route mismatch. Relay registration and +gateway TLS/proof credentials are separate. The relay only pairs an opaque route; +it cannot select a BMC target and does not implement unrestricted CONNECT. + +The plugin exposes a TLS endpoint only on loopback. It writes a one-time local +username/password and CA bundle at mode `0600`, publishes a non-secret readiness +JSON file, deletes local login tokens on Redfish logout, and removes all temporary +files at shutdown. These credentials are unrelated to the gateway's private +sushy credential. + +At the location, the gateway exposes one virtual system named `allocated`. Its +adapter selects the physical sushy system solely from protected binding state. +Customer paths, Hosts, OData links, and guessed identifiers never participate in +physical routing. The only supported mutations are one-time `Pxe` or `Hdd` boot +selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or +`ForceRestart`. Unsupported values fail rather than being substituted. + +## Session and operation sequence + +1. `datumctl fleet machine-management proxy CLAIM` generates a key and asks the + management API for a session using only the claim name. +2. Admission retains the authenticated principal. The controller resolves the + current claim UID and exact active allocation, enforces limits, and persists + the protected binding before projection. +3. The projector checks the authoritative allocation on every refresh. The + location gateway establishes an outbound relay route and publishes non-secret + rendezvous status back through the projector. +4. The plugin consumes the route, verifies the pinned TLS identity, proves its + admitted private key, and opens the loopback Redfish service. +5. Before a boot or reset effect, the gateway fsyncs an operation containing the + session/allocation/correlation identities, normalized method and virtual URI, + exact accepted body, internally selected physical target, idempotency key, + operation and binding epochs, conflict/freshness preconditions, adapter route, + and later execution evidence. Effects for a machine are serialized across all + sessions in the gateway process. +6. A lost adapter response becomes `Unknown`; replaying the exact request returns + the existing task without a second adapter call. Failed or unknown effects are + never rewritten as success. +7. Expiry, public deletion, allocation release, or changed binding inputs closes + the location stream. Release writes a terminal revocation annotation so later + claim-name reuse or record reactivation cannot resurrect the session. If the + location cannot confirm deletion, the central cleanup condition is `Unknown`. + +## API and deployment artifacts + +Kubebuilder-style Go types and generated CRDs are under `api/v1alpha1` and +`config/crd/bases`. CEL makes the public spec immutable and constrains protocol, +profile, key encoding, and TTL. Conditions carry `observedGeneration`, explicit +reasons, and true/false/unknown outcomes. + +RBAC is in `config/rbac`; controller and location workloads are in +`config/manager` and `config/location`. Containers run as non-root with read-only +root filesystems, no added Linux capabilities, and `RuntimeDefault` seccomp. +NetworkPolicy permits the outbound relay, the one private BMC address, DNS, and +the Kubernetes API; it does not expose gateway ingress. Metrics cover admission, +active sessions, revocation latency, BMC reachability, operations, and unknown +outcomes. Protected bindings plus structured, correlation-bearing controller logs +provide the prototype's central audit record. + +The declared DMTF interoperability profile is +`config/redfish/FleetProvisioning.v1_0_0.json`. + +## Reproducible Linux environment + +The qualified prerequisite is Linux with Docker Engine and Compose v2, Kind, kubectl, Go 1.26.1, +Task, jq, OpenSSL, and curl. KVM is used when `/dev/kvm` is available; otherwise +the same real libvirt domain runs with QEMU software emulation. There is no +in-memory or static-JSON BMC fallback. The scripts can also attempt the QEMU path +on Docker-backed macOS for development, but CI qualification remains Linux. + +`task e2e:up` builds and starts: + +- management and location Kind clusters; +- locally built controller, relay, and gateway images; +- a privileged test-only Ubuntu 24.04 container running libvirt/QEMU and pinned + sushy-tools 2.2.0; +- allocated and unallocated libvirt domains on a PXE-enabled provisioning network; +- a minimal PXELINUX/initramfs fixture whose HTTP callback records the VM MAC; +- an internal Docker management network reachable only from the attached location + Kind node; and +- pinned DMTF Python Redfish client and validator tools. + +The sushy port accepts only the location node address. The customer process sees +only loopback ports for the relay and local Redfish connector. The default CI +profile relies on this isolated internal network. After `e2e:up`, the separate +`task e2e:openvpn:up` profile recreates the virtual BMC with a real OpenVPN `tun` +boundary, installs a privileged test client on the location node, moves the +gateway adapter to `10.88.0.1`, and proves the direct management address is +blocked. This profile is intentionally outside default hosted-runner CI. + +Run the complete lifecycle with: + +```console +task e2e:up +task e2e:test +task e2e:down +``` + +The test calls the actual `datumctl fleet ...` command. A repository-local test +Datum session stores synthetic service-account tokens through datumctl's file +keyring format, after which the plugin must still call datumctl's credential +helper. `e2e:up` explicitly trusts the locally built plugin by its path and SHA-256 +using datumctl's unmanaged-plugin trust command. It exercises generic DMTF client login, profile narrowing, distinct RBAC, +per-claim and per-project limits, one-shot rendezvous, real PXE and libvirt power +effects, DMTF validators, central API loss and freshness failure, release fencing, +claim recreation, route isolation, response-loss recovery, and bounded BMC errors. + +Validator versions are `redfish` 3.4.2, +`redfish-service-validator` 3.1.8, and +`redfish-interop-validator` 3.0.3. Reports and PXE correlation evidence are under +`.e2e/validators` and `.e2e/virtual-bmc/evidence`. + +## Troubleshooting + +Run `task e2e:diagnostics` before teardown. It captures both clusters' resources, +events and logs, protected/public session state, libvirt domain state/XML, virtual +BMC logs, validator reports, acceleration selection, and PXE callbacks. + +- A gateway stuck on `RelayUnavailable` usually indicates relay DNS/token or + NetworkPolicy failure in the location cluster. +- `BMCUnavailable` is intentionally bounded; inspect the gateway and virtual-BMC + diagnostics rather than expecting a private address in the customer response. +- No PXE callback: inspect `allocated-console.log`, libvirt network state, and the + VM MAC in `pxe-callbacks.jsonl`. +- `AuthorityStale` after a controller outage is expected. The E2E deployment uses + 15 seconds so the test is fast; the binary default is two minutes. +- `task e2e:down` validates its repository-local state path and names every Docker + and Kind target before removing it. + +## Prototype choices and remaining production gaps + +Implemented-and-tested code must not be confused with a production-ready +contract. Important gaps are: + +- Allocation and claim data are synthetic and pre-bound. There is no allocator, + quota transaction, installation controller, cleanup/quarantine workflow, or + cross-project Milo policy integration. +- Delegated Kubernetes authentication/RBAC models the intended Compute/Milo + pattern, but the production Datum API aggregation and IAM permission names are + not selected. +- The relay is a small Fleet-specific opaque TCP rendezvous with inner TLS, not + Compute's maintained relay deployment. A shared public transport package and + operational ownership decision are still required; Fleet does not import + Compute internal packages. +- The gateway is intentionally single-replica with an RWO journal. Its fsynced + files and in-process per-machine lock demonstrate order and recovery, but a + production multi-replica lease/fencing store is not implemented. +- Exact request bytes form the prototype idempotency identity. Production needs a + client-visible idempotency contract and adapter-specific recovery observation. +- The default test isolates the management network with Docker and iptables; a + separate OpenVPN profile exists but is not yet a production-qualified VPN. + Credential rotation, HSM-backed location identity, multi-location PKI, and + relay denial-of-service controls remain. +- The virtual profile omits firmware, AccountService, Managers, UpdateService, + virtual media, OEM actions, and BMC networking by design. Broader capability + requires a separately reviewed profile and adapter qualification. +- No physical BMC vendor is qualified. sushy/libvirt demonstrates effects and + ambiguity handling only. diff --git a/docs/roadmap.md b/docs/roadmap.md index bebc2677..ee3e99ea 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,9 +1,16 @@ # Implementation roadmap This proposed sequence follows the [reviewed Fleet designs](design.md). Milestones -are unimplemented. Owned-metal qualification and rented/managed adoption can +remain proposed. Owned-metal qualification and rented/managed adoption can progress independently while sharing allocation and installation contracts. +An implemented [machine-management vertical slice](implementation/machine-management-prototype.md) +now supplies evidence for a subset of milestones 1 and 3: immutable session +admission, retained allocation identity, location projection, bounded Redfish, +durable operation admission, revocation, and a real virtual-BMC path. It does +not implement allocator commits, installation, cleanup qualification, or a +production relay and therefore does not complete either milestone. + ## 1. Define the service contracts Record decisions for API scope and field ownership, project identity and IAM, diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..9b735329 --- /dev/null +++ b/go.mod @@ -0,0 +1,72 @@ +module go.datum.net/fleet + +go 1.26.1 + +require ( + github.com/prometheus/client_golang v1.24.0 + github.com/spf13/cobra v1.10.2 + go.datum.net/datumctl v0.15.0 + k8s.io/api v0.37.2 + k8s.io/apimachinery v0.37.2 + k8s.io/client-go v0.37.2 + sigs.k8s.io/controller-runtime v0.25.2 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/emicklei/go-restful/v3 v3.13.0 // indirect + github.com/evanphx/json-patch/v5 v5.9.11 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/fxamacker/cbor/v2 v2.9.1 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-openapi/jsonpointer v1.0.0 // indirect + github.com/go-openapi/jsonreference v1.0.0 // indirect + github.com/go-openapi/swag v0.27.1 // indirect + github.com/go-openapi/swag/cmdutils v0.27.1 // indirect + github.com/go-openapi/swag/conv v0.27.1 // indirect + github.com/go-openapi/swag/fileutils v0.27.1 // indirect + github.com/go-openapi/swag/jsonutils v0.27.1 // indirect + github.com/go-openapi/swag/loading v0.27.1 // indirect + github.com/go-openapi/swag/mangling v0.27.1 // indirect + github.com/go-openapi/swag/netutils v0.27.1 // indirect + github.com/go-openapi/swag/pools v0.27.1 // indirect + github.com/go-openapi/swag/stringutils v0.27.1 // indirect + github.com/go-openapi/swag/typeutils v0.27.1 // indirect + github.com/go-openapi/swag/yamlutils v0.27.1 // indirect + github.com/google/gnostic-models v0.7.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.70.0 // indirect + github.com/prometheus/procfs v0.21.1 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/x448/float16 v0.8.4 // indirect + go.yaml.in/yaml/v2 v2.4.4 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/net v0.57.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/term v0.45.0 // indirect + golang.org/x/text v0.40.0 // indirect + golang.org/x/time v0.15.0 // indirect + gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect + google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect + gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + k8s.io/apiextensions-apiserver v0.37.0 // indirect + k8s.io/klog/v2 v2.140.0 // indirect + k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect + k8s.io/utils v0.0.0-20260626114624-be93311217bd // indirect + sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect + sigs.k8s.io/randfill v1.0.0 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect + sigs.k8s.io/yaml v1.6.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..f2fd5182 --- /dev/null +++ b/go.sum @@ -0,0 +1,192 @@ +github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= +github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= +github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/evanphx/json-patch v0.5.2 h1:xVCHIVMUu1wtM/VkR9jVZ45N3FhZfYMMYGorLCR8P3k= +github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= +github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= +github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= +github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= +github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= +github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= +github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= +github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= +github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0= +github.com/go-openapi/swag v0.27.1 h1:VotvOLWW8q/EAxB0YdsBBGC8XYyeL1YwBj2ungAGPNg= +github.com/go-openapi/swag v0.27.1/go.mod h1:GTkJPwHfhJp6MWr4/rCh64HVI3Ofu+tcsbfjfHmTxpE= +github.com/go-openapi/swag/cmdutils v0.27.1 h1:I7sYqaWVl5mq0NEmNQkAmFDyNin9ufvMX/p2zwtQaOE= +github.com/go-openapi/swag/cmdutils v0.27.1/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= +github.com/go-openapi/swag/conv v0.27.1 h1:8wi9ZG+olmY1wXphl93EWniPtbSPkXM/feH7FgjsvrU= +github.com/go-openapi/swag/conv v0.27.1/go.mod h1:QbqMivkpKhC3g1B1GGGOJ6ANewI3S62dbzYu3Duowqs= +github.com/go-openapi/swag/fileutils v0.27.1 h1:QQqBSoi5mW4XpU85nS0mLcA+zAE6vLzrb0QkmLKf9oM= +github.com/go-openapi/swag/fileutils v0.27.1/go.mod h1:VvJFZLTZS0AI854gEQz5tk7dBESdLjiNUMSZ/th2ry8= +github.com/go-openapi/swag/jsonutils v0.27.1 h1:SVgK3i4USzCU5mibOOS/l4ea2h9UQXy7J7RNLTjuXjU= +github.com/go-openapi/swag/jsonutils v0.27.1/go.mod h1:tdlEpZqdcQ17uj6J4YdK9vd8It5qWMwjWXOs0tjpRlk= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.1 h1:mJu3COL9WEaZVp/Kf2PRMi7tPszPEJfSr/OO75ynCs8= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.1/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY= +github.com/go-openapi/swag/loading v0.27.1 h1:/DxUgDXKbBX4bcn7r9uEXfJyzN5XpiJmZplzQTjrRCY= +github.com/go-openapi/swag/loading v0.27.1/go.mod h1:jvGh3iA2+zyUUycB5fgJWzeHnhrpvGnJJM0RVE9ZShE= +github.com/go-openapi/swag/mangling v0.27.1 h1:yC9D0HyUE8gbP+BfmGx9+AA89ikwZTMjESK3OnnoaqA= +github.com/go-openapi/swag/mangling v0.27.1/go.mod h1:jtBE2+V+3pILxOR7Vgce+Cwp6A2PgZbvVqfNntbVs0w= +github.com/go-openapi/swag/netutils v0.27.1 h1:mICMFoS82F5TZ4Zy3cqmcQk+BFeCp3Uyq3Np7GI0/qU= +github.com/go-openapi/swag/netutils v0.27.1/go.mod h1:J+WYyFMLtvtCGqa6jLv+YNUmIKI3ZRQRrvfNDMoQoEQ= +github.com/go-openapi/swag/pools v0.27.1 h1:9LeadcMyb2GJCbXX5hVQDbZ2Lq9TL4dCs/nx1j5DO0E= +github.com/go-openapi/swag/pools v0.27.1/go.mod h1:kVQefhSK5RWuRe7BXsL8htgBPAMpN7HDGpGEknqugeE= +github.com/go-openapi/swag/stringutils v0.27.1 h1:ZXePZ0r2p1qSjo8tD3Un4vFj8+FqlCkczxDrJIhYUp8= +github.com/go-openapi/swag/stringutils v0.27.1/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM= +github.com/go-openapi/swag/typeutils v0.27.1 h1:KSTdFlfnse4r6dP9IrEnwMldjE+zs71UeEB3//PtVXc= +github.com/go-openapi/swag/typeutils v0.27.1/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ= +github.com/go-openapi/swag/yamlutils v0.27.1 h1:ftxv6xvXb1E3zohUc+okZ9nSqNb9StQX/FXnKZ98sQA= +github.com/go-openapi/swag/yamlutils v0.27.1/go.mod h1:bnxFIB1qewGRiZHypXGZ3fNgf13/0HfRgnS/iZBDrOo= +github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0= +github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo= +github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug= +github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= +github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J0b1vyeLSOYI8bm5wbJM/8yDe8= +github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ= +github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/onsi/ginkgo/v2 v2.27.4 h1:fcEcQW/A++6aZAZQNUmNjvA9PSOzefMJBerHJ4t8v8Y= +github.com/onsi/ginkgo/v2 v2.27.4/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= +github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q= +github.com/onsi/gomega v1.39.0/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.24.0 h1:5XStIklKuAtJSNpdD3s8XJj/Yv78IQmE1kbNk87JrAI= +github.com/prometheus/client_golang v1.24.0/go.mod h1:QcsNdotprC2nS4BTM2ucbcqxd2CeXTEa9jW7zHO9iDE= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.70.0 h1:bcpru3tWPVnxGnETLgOV5jbp/JRXgYEyv65CuBLAMMI= +github.com/prometheus/common v0.70.0/go.mod h1:S/SFasQmgGiYH6C81LKCtYa8QACgthGg5zxL2udV7SY= +github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= +github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +go.datum.net/datumctl v0.15.0 h1:dOrnfwWyhQ0Yp42jTUiMu3w/ySkftz2CXF7hsuWp4gE= +go.datum.net/datumctl v0.15.0/go.mod h1:rwu8XWb0FeMzX8vCu+UxKLw89DAkyLOh70PNbDaotac= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw= +gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= +google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= +google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= +gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +k8s.io/api v0.37.2 h1:PnxqnUFy93jr2GcpWDkKOm8wfy25kT9wa572MuQS8oc= +k8s.io/api v0.37.2/go.mod h1:+NVRLft99kx+Jg9v34GmHw867Dapim89TSyCsn2hK+M= +k8s.io/apiextensions-apiserver v0.37.0 h1:zRMQ3+/LIE5oZ0tVvXwYHC+dIkSP5cjNWju7AZU1LOI= +k8s.io/apiextensions-apiserver v0.37.0/go.mod h1:HU0PfSBwchHL5iDau6jjt9zU6ryWkDDlaVUiq91NK80= +k8s.io/apimachinery v0.37.2 h1:G4t9RGoPDbQML38hz/kQQiltttgd3egg2ODCR8aIc2o= +k8s.io/apimachinery v0.37.2/go.mod h1:qaAvSNvgU2x07wRM95MSHSJTPQ/ob/LeNAGbeDgqQJg= +k8s.io/client-go v0.37.2 h1:sgFtyRZukGkOrsu+QgS7LYnbFFJ5ut3MchdBNduD//E= +k8s.io/client-go v0.37.2/go.mod h1:bo3LFC8YbCtKFPX21Yj8puMsoJLAv/+SvuOODma0s54= +k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= +k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3ddJoY6OnyM225MXwGHPm0A= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I= +k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= +k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= +sigs.k8s.io/controller-runtime v0.25.2 h1:bEkK3PVOIVK9X8QWLGVhJgmFc++47vfT6wakSzAOLsQ= +sigs.k8s.io/controller-runtime v0.25.2/go.mod h1:4QqLdT6z/L6Olj8JJCtvztid4/fnIiYsfaTFScegctc= +sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= +sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= +sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= +sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= +sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/hack/e2e/diagnostics.sh b/hack/e2e/diagnostics.sh new file mode 100755 index 00000000..8ff78742 --- /dev/null +++ b/hack/e2e/diagnostics.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +OUT="${E2E_DIR}/diagnostics/$(date -u +%Y%m%dT%H%M%SZ)" +mkdir -p "${OUT}" +for cluster in management location; do + kubeconfig="${E2E_DIR}/${cluster}.kubeconfig" + if [[ -f "${kubeconfig}" ]]; then + kubectl --kubeconfig "${kubeconfig}" get all,events -A -o wide >"${OUT}/${cluster}-resources.txt" 2>&1 || true + kubectl --kubeconfig "${kubeconfig}" get machinemanagementsessions,machineallocationbindings,machinemanagementsessionbindings,projectedmachinemanagementsessions -A -o yaml >"${OUT}/${cluster}-fleet.yaml" 2>&1 || true + kubectl --kubeconfig "${kubeconfig}" logs -A --all-containers --prefix --tail=-1 >"${OUT}/${cluster}-logs.txt" 2>&1 || true + if [[ "${cluster}" == location ]]; then + kubectl --kubeconfig "${kubeconfig}" -n machine-access-system exec deployment/fleet-gateway -- \ + sh -c 'for f in /var/lib/fleet/operations/*.json; do test -f "$f" && { echo "$f"; cat "$f"; }; done' \ + >"${OUT}/operation-journal.jsonl" 2>&1 || true + fi + fi +done +docker logs fleet-e2e-virtual-bmc >"${OUT}/virtual-bmc.log" 2>&1 || true +docker exec fleet-e2e-virtual-bmc virsh list --all >"${OUT}/libvirt-domains.txt" 2>&1 || true +docker exec fleet-e2e-virtual-bmc virsh dumpxml allocated >"${OUT}/allocated-domain.xml" 2>&1 || true +if [[ -d "${E2E_DIR}/virtual-bmc/evidence" ]]; then cp -R "${E2E_DIR}/virtual-bmc/evidence" "${OUT}/"; fi +echo "diagnostics: ${OUT}" diff --git a/hack/e2e/down.sh b/hack/e2e/down.sh new file mode 100755 index 00000000..29b91784 --- /dev/null +++ b/hack/e2e/down.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" +export FLEET_E2E_STATE="${E2E_DIR}/virtual-bmc" +kind delete cluster --name fleet-management-e2e 2>/dev/null || true +kind delete cluster --name fleet-location-e2e 2>/dev/null || true +docker compose -p fleet-bmc-e2e -f "${TEST_DIR}/compose.yaml" down --remove-orphans 2>/dev/null || true +docker network rm fleet-management-e2e 2>/dev/null || true +case "${E2E_DIR}" in + "${ROOT_DIR}/.e2e") rm -rf -- "${E2E_DIR}" ;; + *) echo "refusing to remove unexpected path ${E2E_DIR}" >&2; exit 1 ;; +esac diff --git a/hack/e2e/openvpn-up.sh b/hack/e2e/openvpn-up.sh new file mode 100755 index 00000000..1320c36f --- /dev/null +++ b/hack/e2e/openvpn-up.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" +LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" +export FLEET_E2E_STATE="${E2E_DIR}/virtual-bmc" +[[ $(uname -s) == Linux ]] || { echo "OpenVPN qualification requires Linux" >&2; exit 1; } +[[ -f "${LOCATION_KUBECONFIG}" ]] || { echo "run task e2e:up first" >&2; exit 1; } + +docker compose -p fleet-bmc-e2e -f "${TEST_DIR}/compose.yaml" -f "${TEST_DIR}/compose.openvpn.yaml" up -d --build --force-recreate virtual-bmc +for _ in $(seq 1 60); do [[ -s "${FLEET_E2E_STATE}/evidence/openvpn.key" ]] && break; sleep 1; done +[[ -s "${FLEET_E2E_STATE}/evidence/openvpn.key" ]] || { echo "OpenVPN server key was not created" >&2; exit 1; } +docker build -t fleet-openvpn-client:e2e "${TEST_DIR}/openvpn" +kind load docker-image fleet-openvpn-client:e2e --name fleet-location-e2e +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create secret generic fleet-openvpn-key \ + --from-file=openvpn.key="${FLEET_E2E_STATE}/evidence/openvpn.key" --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${TEST_DIR}/openvpn/client.yaml" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status daemonset/fleet-openvpn-client --timeout=120s +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch deployment fleet-gateway --type=json \ + -p='[{"op":"replace","path":"/spec/template/spec/containers/0/args/5","value":"--bmc-url=http://10.88.0.1:8000"}]' +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s +pod=$(kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system get pod -l app.kubernetes.io/name=fleet-openvpn-client -o jsonpath='{.items[0].metadata.name}') +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system exec "${pod}" -- curl --fail --silent http://10.88.0.1:8000/redfish/v1/Systems >/dev/null +if kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system exec "${pod}" -- curl --fail --silent --connect-timeout 2 http://172.30.0.10:8000/redfish/v1/Systems >/dev/null 2>&1; then + echo "direct management route remained reachable in OpenVPN profile" >&2 + exit 1 +fi +echo "OpenVPN management boundary: PASS" diff --git a/hack/e2e/test.sh b/hack/e2e/test.sh new file mode 100755 index 00000000..aa903e8e --- /dev/null +++ b/hack/e2e/test.sh @@ -0,0 +1,326 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" +MGMT_KUBECONFIG="${E2E_DIR}/management.kubeconfig" +LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" +PATH="${E2E_DIR}/bin:${PATH}" +export PATH + +for file in "${MGMT_KUBECONFIG}" "${LOCATION_KUBECONFIG}" "${E2E_DIR}/management-ca.crt"; do + [[ -f "${file}" ]] || { echo "missing ${file}; run task e2e:up" >&2; exit 1; } +done +# Each run must prove a new boot rather than accepting evidence left by an +# earlier invocation against the same idempotent environment. +rm -f "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" \ + "${E2E_DIR}/virtual-bmc/evidence/pxe-operation-correlation.json" \ + "${E2E_DIR}/virtual-bmc/evidence/allocated-console.log" + +proxy_pid= +second_proxy_pid= +management_paused=false +location_paused=false +cleanup() { + if [[ -n "${proxy_pid}" ]]; then kill -TERM "${proxy_pid}" 2>/dev/null || true; wait "${proxy_pid}" 2>/dev/null || true; fi + if [[ -n "${second_proxy_pid}" ]]; then kill -TERM "${second_proxy_pid}" 2>/dev/null || true; wait "${second_proxy_pid}" 2>/dev/null || true; fi + if [[ "${management_paused}" == true ]]; then docker unpause fleet-management-e2e-control-plane >/dev/null 2>&1 || true; fi + if [[ "${location_paused}" == true ]]; then docker unpause fleet-location-e2e-control-plane >/dev/null 2>&1 || true; fi +} +trap cleanup EXIT + +fail() { echo "FAIL: $*" >&2; exit 1; } +wait_for() { + local description=$1 command=$2 + for _ in $(seq 1 90); do eval "${command}" && return 0; sleep 1; done + fail "timed out waiting for ${description}" +} +run_timeout() { + local seconds=$1 + shift + if command -v timeout >/dev/null; then timeout "${seconds}" "$@"; return; fi + if command -v gtimeout >/dev/null; then gtimeout "${seconds}" "$@"; return; fi + perl -e '$seconds = shift; alarm $seconds; exec @ARGV' "${seconds}" "$@" +} +file_mode() { + if stat -c %a "$1" >/dev/null 2>&1; then stat -c %a "$1"; else stat -f %Lp "$1"; fi +} + +api_server=$(kubectl config view --kubeconfig "${MGMT_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.server}') + +# A claim reader cannot create a management session. This invokes datumctl's +# actual plugin discovery/dispatch and credential-helper path. +set +e +HOME="${E2E_DIR}/home-viewer" datumctl fleet machine-management proxy db-01 -- \ + --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" \ + --ready-file "${E2E_DIR}/viewer-ready.json" >"${E2E_DIR}/viewer.log" 2>&1 +viewer_status=$? +set -e +[[ ${viewer_status} -eq 11 ]] || fail "claim-only principal exit=${viewer_status}, expected permission exit 11" +[[ ! -e "${E2E_DIR}/viewer-ready.json" ]] || fail "unauthorized principal received a local endpoint" + +start_proxy() { + local ttl=${1:-15m} + rm -f "${E2E_DIR}/ready.json" "${E2E_DIR}/credentials.json" "${E2E_DIR}/ca.pem" + DATUM_TOKEN=must-not-be-used HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-01 -- \ + --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" \ + --listen 127.0.0.1:9443 --ttl "${ttl}" \ + --ready-file "${E2E_DIR}/ready.json" --credential-file "${E2E_DIR}/credentials.json" \ + --ca-file "${E2E_DIR}/ca.pem" >"${E2E_DIR}/proxy.log" 2>&1 & + proxy_pid=$! + wait_for "datumctl fleet proxy readiness" "jq -e '.ready == true' '${E2E_DIR}/ready.json' >/dev/null 2>&1" + endpoint=$(jq -r .endpoint "${E2E_DIR}/credentials.json") + username=$(jq -r .username "${E2E_DIR}/credentials.json") + password=$(jq -r .password "${E2E_DIR}/credentials.json") + root=${endpoint%/redfish/v1/} +} + +stop_proxy() { + kill -TERM "${proxy_pid}" 2>/dev/null || true + wait "${proxy_pid}" 2>/dev/null || true + proxy_pid= + wait_for "session deletion" "! kubectl --kubeconfig '${MGMT_KUBECONFIG}' -n default get machinemanagementsessions.fleet.datumapis.com -o name 2>/dev/null | grep -q ." +} + +# Nested x86 QEMU on non-x86 developer hosts can take tens of seconds to apply +# a real libvirt boot mutation. Keep the deadline bounded while allowing the +# required software-emulation fallback to complete without manufacturing a +# client-side lost-response outcome. +rf() { curl --silent --show-error --max-time 90 --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" "$@"; } +rf_status() { curl --silent --max-time 90 --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" "$@"; } + +start_proxy +[[ $(file_mode "${E2E_DIR}/credentials.json") == 600 ]] || fail "credential file is not 0600" +[[ $(file_mode "${E2E_DIR}/ca.pem") == 600 ]] || fail "CA file is not 0600" +if curl --fail --silent --connect-timeout 2 http://172.30.0.10:8000/redfish/v1/ >/dev/null 2>&1; then + fail "customer test process reached the private sushy endpoint" +fi +session_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.name}') +if kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default patch machinemanagementsession "${session_name}" --type=merge -p '{"spec":{"ttl":"10m"}}' >/dev/null 2>&1; then + fail "immutable public session spec was mutable" +fi + +# Use DMTF's generic Python Redfish client, not a project-specific client. A +# remote Docker engine cannot share the macOS loopback namespace, so the +# unqualified Darwin development path uses the same pinned client from a local +# temporary virtual environment. Native Linux and CI retain the container path. +if [[ $(uname -s) == Darwin ]]; then + validator_bin=${FLEET_VALIDATOR_BIN:-/private/tmp/fleet-validator-venv/bin} + FLEET_CREDENTIAL_FILE="${E2E_DIR}/credentials.json" FLEET_CA_BUNDLE="${E2E_DIR}/ca.pem" \ + "${validator_bin}/python" "${TEST_DIR}/generic-client.py" +else + docker run --rm --network host \ + -e FLEET_CREDENTIAL_FILE=/state/credentials.json -e FLEET_CA_BUNDLE=/state/ca.pem \ + -v "${E2E_DIR}:/state:ro" -v "${TEST_DIR}:/work:ro" fleet-redfish-tools:e2e \ + "python /work/generic-client.py" +fi + +# Session-local login credentials are revocable and are not BMC credentials. +login_headers="${E2E_DIR}/login.headers" +curl --silent --show-error --cacert "${E2E_DIR}/ca.pem" -D "${login_headers}" \ + -H 'Content-Type: application/json' -d "{\"UserName\":\"${username}\",\"Password\":\"${password}\"}" \ + "${root}/redfish/v1/SessionService/Sessions" >/dev/null +local_token=$(awk 'tolower($1)=="x-auth-token:" {gsub("\r", "", $2); print $2}' "${login_headers}") +[[ -n "${local_token}" ]] || fail "local Redfish login did not return a token" +curl --silent --show-error --cacert "${E2E_DIR}/ca.pem" -H "X-Auth-Token: ${local_token}" \ + -X DELETE "${root}/redfish/v1/SessionService/Sessions/local" -o /dev/null +[[ $(curl --silent --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" -H "X-Auth-Token: ${local_token}" "${root}/redfish/v1/Systems") == 401 ]] || fail "deleted local Redfish token remained valid" + +# The virtual tree is intentionally narrow and contains exactly one allocated system. +for path in AccountService Managers UpdateService Systems/unallocated Systems/allocated/Oem/Reset; do + [[ $(rf_status "${root}/redfish/v1/${path}") == 404 ]] || fail "forbidden path ${path} was exposed" +done +[[ $(curl --silent --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" -H 'Host: 172.30.0.10' "${root}/redfish/v1/Systems") == 400 ]] || fail "Host routing was accepted" +[[ $(curl --silent --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" --request-target 'http://172.30.0.10/redfish/v1/Systems' "${root}/redfish/v1/Systems") == 400 ]] || fail "absolute request target was accepted" +[[ $(rf_status -X PATCH -H 'Content-Type: application/json' -d '{"AssetTag":"customer-controlled"}' "${root}/redfish/v1/Systems/allocated") == 400 ]] || fail "unsupported PATCH was accepted" +[[ $(rf_status -X POST -H 'Content-Type: application/json' -d '{"ResetType":"Nmi"}' "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") == 400 ]] || fail "unsupported reset was accepted" +[[ $(docker exec fleet-e2e-virtual-bmc virsh domstate unallocated | tr -d '\r') == "shut off" ]] || fail "unallocated domain was affected" + +# A second connector cannot consume the already-consumed rendezvous route. +route=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].status.connection.routeID}') +replay=$(run_timeout 3 bash -c "exec 9<>/dev/tcp/127.0.0.1/30443; printf 'CLIENT %s\\n' '${route}' >&9; IFS= read -r line <&9; printf '%s' \"\${line}\"") +[[ "${replay}" == ERROR* ]] || fail "relay route replay was not rejected: ${replay}" + +# Per-claim admission limit remains distinct from claim read permission. +set +e +run_timeout 20 env HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-01 -- \ + --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" >"${E2E_DIR}/second-session.log" 2>&1 +second_status=$? +set -e +[[ ${second_status} -ne 0 ]] || fail "second concurrent claim session was admitted" +grep -q SessionLimitExceeded "${E2E_DIR}/second-session.log" || fail "session limit rejection was not actionable" + +# The E2E controller uses a test-only project limit of two. A second distinct, +# pre-bound claim is admitted; a third is rejected by the real plugin workflow. +for claim in db-02 db-03; do + kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - <"${E2E_DIR}/proxy-2.log" 2>&1 & +second_proxy_pid=$! +wait_for "second project session" "jq -e '.ready == true' '${E2E_DIR}/ready-2.json' >/dev/null 2>&1" +set +e +run_timeout 20 env HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-03 -- \ + --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" >"${E2E_DIR}/project-limit.log" 2>&1 +project_status=$? +set -e +[[ ${project_status} -ne 0 ]] || fail "third project session was admitted over the limit" +grep -q SessionLimitExceeded "${E2E_DIR}/project-limit.log" || fail "project limit rejection was not actionable" +kill -TERM "${second_proxy_pid}"; wait "${second_proxy_pid}" || true; second_proxy_pid= + +# Real sushy -> libvirt PXE effect, correlated by the allocated VM MAC callback. +pxe_body='{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Pxe"}}' +pxe_task=$(rf -X PATCH -H 'Content-Type: application/json' -d "${pxe_body}" "${root}/redfish/v1/Systems/allocated") +[[ $(jq -r .TaskState <<<"${pxe_task}") == Completed ]] || fail "PXE boot mutation did not complete" +power_task=$(rf -X POST -H 'Content-Type: application/json' -d '{"ResetType":"On"}' "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") +task_uri=$(jq -r '.["@odata.id"]' <<<"${power_task}") +[[ $(rf "${root}${task_uri}" | jq -r .TaskState) == Completed ]] || fail "power task did not complete" +# A complete Ubuntu kernel boot under nested software QEMU can exceed the +# ordinary control-plane wait. Keep this proof bounded, but allow four minutes +# for the real VM to load the initramfs, configure DHCP, and call back. +for _ in $(seq 1 240); do + grep -q '/pxe/52-54-00-aa-00-01' "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" 2>/dev/null && break + sleep 1 +done +grep -q '/pxe/52-54-00-aa-00-01' "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" 2>/dev/null || fail "timed out waiting for PXE callback for allocated MAC" +wait_for "PXE fixture poweroff in libvirt" "[[ \$(docker exec fleet-e2e-virtual-bmc virsh domstate allocated | tr -d '\\r') == 'shut off' ]]" +! grep -q '/pxe/52-54-00-aa-00-02' "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" || fail "unallocated VM produced a PXE callback" +jq -n --arg operationID "$(jq -r .Id <<<"${power_task}")" --arg mac 52:54:00:aa:00:01 \ + --argjson callback "$(grep '/pxe/52-54-00-aa-00-01' "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" | tail -1)" \ + '{operationID:$operationID,vmMAC:$mac,callback:$callback}' >"${E2E_DIR}/virtual-bmc/evidence/pxe-operation-correlation.json" + +hdd_body='{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Hdd"}}' +rf -X PATCH -H 'Content-Type: application/json' -d "${hdd_body}" "${root}/redfish/v1/Systems/allocated" >/dev/null +[[ $(rf "${root}/redfish/v1/Systems/allocated" | jq -r .Boot.BootSourceOverrideTarget) == Hdd ]] || fail "local-disk target was not restored" +domain_xml=$(docker exec fleet-e2e-virtual-bmc virsh dumpxml allocated) +grep -A6 "" <<<"${domain_xml}" | grep -q "" || fail "libvirt did not retain the local-disk boot target" +if grep -A6 "" <<<"${domain_xml}" | grep -q '/dev/null +wait_for "new allocation domain power-on" "[[ \$(docker exec fleet-e2e-virtual-bmc virsh domstate unallocated | tr -d '\\r') == running ]]" + +# Fault-inject a lost BMC response. Retrying the identical admitted operation +# must recover its Unknown task without sending a second physical reset. +stop_proxy +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch deployment fleet-gateway --type=json \ + -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--fault-drop-reset-response-once"}]' +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s +start_proxy +reset_path='/redfish/v1/Systems/unallocated/Actions/ComputerSystem.Reset' +reset_before=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) +lost_body='{"ResetType":"ForceRestart"}' +lost_first=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") +lost_second=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") +[[ $(jq -r .TaskState <<<"${lost_first}") == Exception && $(jq -r .TaskStatus <<<"${lost_first}") == Warning ]] || fail "lost response was not reported Unknown" +[[ $(jq -r .Id <<<"${lost_first}") == $(jq -r .Id <<<"${lost_second}") ]] || fail "retry created a second operation" +reset_after=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) +[[ $((reset_after - reset_before)) -eq 1 ]] || fail "lost-response retry sent $((reset_after - reset_before)) physical resets" + +# The gateway schedules the admitted expiry and closes the stream rather than +# treating a still-live client or relay connection as authority. +stop_proxy +start_proxy 1m +sleep 65 +[[ $(rf_status "${root}/redfish/v1/Systems/allocated") != 200 ]] || fail "expired session retained Redfish access" +stop_proxy +start_proxy + +# Stop only the private sushy route. The customer receives a bounded error that +# does not disclose the private endpoint or credential. +gateway_pod=$(kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system get pod -l app.kubernetes.io/name=fleet-gateway -o jsonpath='{.items[0].metadata.name}') +docker exec fleet-e2e-virtual-bmc iptables -I INPUT 1 -p tcp --dport 8000 -s 172.30.0.20 -j REJECT +bmc_error=$(rf "${root}/redfish/v1/Systems/allocated") +[[ $(jq -r .error.code <<<"${bmc_error}") == Fleet.1.0.BMCUnavailable ]] || fail "BMC failure was not actionable" +! grep -Eq '172\.30\.0\.10|fleet-gateway|synthetic-e2e-only' <<<"${bmc_error}" || fail "BMC failure disclosed private data" +docker exec fleet-e2e-virtual-bmc iptables -D INPUT 1 + +# If the location cannot acknowledge explicit deletion, the public object may +# finish deleting only with a protected Unknown teardown outcome. +unknown_session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.uid}') +docker pause fleet-location-e2e-control-plane >/dev/null +location_paused=true +stop_proxy +cleanup_status=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${unknown_session_uid}" -o json | jq -r '.status.conditions[] | select(.type=="CleanupConfirmed") | .status + ":" + .reason') +[[ "${cleanup_status}" == "Unknown:LocationUnconfirmed" ]] || fail "unconfirmed teardown was not Unknown: ${cleanup_status}" +docker unpause fleet-location-e2e-control-plane >/dev/null +location_paused=false +[[ ! -e "${E2E_DIR}/credentials.json" && ! -e "${E2E_DIR}/ca.pem" ]] || fail "proxy secret files survived shutdown" +echo "machine-management end-to-end scenarios: PASS" diff --git a/hack/e2e/up.sh b/hack/e2e/up.sh new file mode 100755 index 00000000..a34fe7e9 --- /dev/null +++ b/hack/e2e/up.sh @@ -0,0 +1,181 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" +MGMT_KUBECONFIG="${E2E_DIR}/management.kubeconfig" +LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" +export FLEET_E2E_STATE="${E2E_DIR}/virtual-bmc" + +for tool in docker kind kubectl go jq openssl; do + command -v "${tool}" >/dev/null || { echo "missing required tool: ${tool}" >&2; exit 1; } +done +if [[ $(uname -s) != Linux ]]; then + echo "warning: Linux is the qualified environment; attempting the same QEMU software-emulation path on $(uname -s)" >&2 + # Cross-architecture Lima guests can expose a nominal /dev/kvm even though + # nesting it reboots the outer VM. Select the required software fallback. + export FLEET_FORCE_QEMU=${FLEET_FORCE_QEMU:-1} +fi +mkdir -p "${E2E_DIR}/bin" "${FLEET_E2E_STATE}/evidence" "${FLEET_E2E_STATE}/images" +find "${FLEET_E2E_STATE}/evidence" -maxdepth 1 -type f -delete + +docker compose -p fleet-bmc-e2e -f "${TEST_DIR}/compose.yaml" up -d --build +for _ in $(seq 1 60); do docker exec fleet-e2e-virtual-bmc virsh list --all >/dev/null 2>&1 && break; sleep 1; done +docker exec fleet-e2e-virtual-bmc virsh destroy allocated >/dev/null 2>&1 || true +docker exec fleet-e2e-virtual-bmc virsh destroy unallocated >/dev/null 2>&1 || true + +if ! kind get clusters | grep -qx fleet-management-e2e; then + kind create cluster --name fleet-management-e2e --config "${TEST_DIR}/kind-management.yaml" +fi +if ! kind get clusters | grep -qx fleet-location-e2e; then + kind create cluster --name fleet-location-e2e --config "${TEST_DIR}/kind-location.yaml" +fi +kind get kubeconfig --name fleet-management-e2e >"${MGMT_KUBECONFIG}" +kind get kubeconfig --name fleet-location-e2e >"${LOCATION_KUBECONFIG}" +chmod 0600 "${MGMT_KUBECONFIG}" "${LOCATION_KUBECONFIG}" + +if ! docker network inspect fleet-management-e2e | jq -e '.[0].Containers | to_entries[] | select(.value.Name=="fleet-location-e2e-control-plane")' >/dev/null; then + docker network connect --ip 172.30.0.20 fleet-management-e2e fleet-location-e2e-control-plane +fi + +build_image() { + local image=$1 package=$2 binary=$3 + docker build -t "${image}:e2e" --build-arg "PACKAGE=${package}" --build-arg "BINARY=${binary}" "${ROOT_DIR}" +} +build_image fleet-controller ./cmd/fleet-controller fleet-controller +build_image fleet-gateway ./cmd/fleet-gateway fleet-gateway +build_image fleet-relay ./cmd/fleet-relay fleet-relay +docker build -t fleet-redfish-tools:e2e "${TEST_DIR}/tools" +kind load docker-image fleet-controller:e2e --name fleet-management-e2e +kind load docker-image fleet-gateway:e2e fleet-relay:e2e --name fleet-location-e2e + +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/crd" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/crd" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/base" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/base" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" wait --for=condition=Established --timeout=60s crd/machinemanagementsessions.fleet.datumapis.com +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" wait --for=condition=Established --timeout=60s crd/projectedmachinemanagementsessions.fleet.datumapis.com +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/controller.yaml" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/controller.yaml" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/projector-location.yaml" + +relay_token=$(openssl rand -hex 32) +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create secret generic fleet-relay-token \ + --from-literal=relay-token="${relay_token}" --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create secret generic fleet-bmc-credentials \ + --from-literal=bmc-username=fleet-gateway --from-literal=bmc-password=synthetic-e2e-only \ + --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - +unset relay_token + +projector_token=$(kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create token fleet-projector --duration=2h) +location_ca=$(kubectl config view --kubeconfig "${LOCATION_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}') +location_ip=$(docker inspect fleet-location-e2e-control-plane | jq -r '.[0].NetworkSettings.Networks.kind.IPAddress') +cat >"${E2E_DIR}/projector.kubeconfig" </dev/null 2>&1 +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system create secret tls fleet-webhook-tls \ + --cert="${E2E_DIR}/webhook/tls.crt" --key="${E2E_DIR}/webhook/tls.key" --dry-run=client -o yaml | kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${ROOT_DIR}/config/manager/controller.yaml" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${ROOT_DIR}/config/manager/networkpolicy.yaml" +webhook_ca=$(base64 -w0 <"${E2E_DIR}/webhook/tls.crt") +kubectl --kubeconfig "${MGMT_KUBECONFIG}" patch mutatingwebhookconfiguration fleet-machine-management-session --type=json \ + -p="[{\"op\":\"add\",\"path\":\"/webhooks/0/clientConfig/caBundle\",\"value\":\"${webhook_ca}\"}]" +unset webhook_ca + +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/location/access.yaml" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/location/networkpolicy.yaml" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system rollout status deployment/fleet-controller --timeout=120s +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-relay --timeout=120s +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s + +# Reset only resources owned by this dedicated E2E environment so repeated up +# and test invocations begin from the same authority state. +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machinemanagementsessions --all --timeout=40s --ignore-not-found +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system delete projectedmachinemanagementsessions --all --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system delete machinemanagementsessionbindings --all --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machineclaims db-02 db-03 --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system delete machineallocationbindings db-02-allocation db-03-allocation --ignore-not-found + +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/claim.yaml" +claim_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machineclaim db-01 -o jsonpath='{.metadata.uid}') +sed "s/CLAIM_UID/${claim_uid}/g" "${TEST_DIR}/seed/allocation.yaml" | kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - + +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/test-identities.yaml" +authorized_token=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default create token fleet-authorized --duration=2h) +viewer_token=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default create token fleet-viewer --duration=2h) + +env GOBIN="${E2E_DIR}/bin" go install go.datum.net/datumctl@v0.15.0 +env GOCACHE="${E2E_DIR}/go-cache" go build -o "${E2E_DIR}/bin/datumctl-fleet" "${ROOT_DIR}/cmd/datumctl-fleet" +api_server=$(kubectl config view --kubeconfig "${MGMT_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.server}') +api_host=${api_server#https://} +kubectl config view --kubeconfig "${MGMT_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d >"${E2E_DIR}/management-ca.crt" + +write_datum_session() { + local name=$1 token=$2 + local home_dir="${E2E_DIR}/home-${name}" user_key="${name}@kind" + mkdir -p "${home_dir}/.datumctl" + chmod 0700 "${home_dir}/.datumctl" + cat >"${home_dir}/.datumctl/config" </dev/null 2>&1; then + expiry=$(date -u -d '+2 hours' '+%Y-%m-%dT%H:%M:%SZ') + else + expiry=$(date -u -v+2H '+%Y-%m-%dT%H:%M:%SZ') + fi + creds=$(jq -cn --arg token "${token}" --arg expiry "${expiry}" --arg host "${api_host}" --arg email "${name}@example.test" \ + '{hostname:"kind.invalid",api_hostname:$host,client_id:"fleet-e2e",endpoint_auth_url:"https://kind.invalid/auth",endpoint_token_url:"https://kind.invalid/token",scopes:[],token:{access_token:$token,token_type:"Bearer",expiry:$expiry},user_name:$email,user_email:$email,subject:$email}') + jq -n --arg key "${user_key}" --arg creds "${creds}" '{"datumctl-auth":{($key):$creds,"active_user":$key,"known_users":([$key]|tojson)}}' >"${home_dir}/.datumctl/credentials.json" + chmod 0600 "${home_dir}/.datumctl/config" "${home_dir}/.datumctl/credentials.json" +} +write_datum_session authorized "${authorized_token}" +write_datum_session viewer "${viewer_token}" +unset authorized_token viewer_token +for identity in authorized viewer; do + HOME="${E2E_DIR}/home-${identity}" PATH="${E2E_DIR}/bin:${PATH}" \ + "${E2E_DIR}/bin/datumctl" plugin trust fleet >/dev/null +done + +echo "Fleet machine-management e2e environment is ready in ${E2E_DIR}" diff --git a/hack/e2e/validators.sh b/hack/e2e/validators.sh new file mode 100755 index 00000000..35556924 --- /dev/null +++ b/hack/e2e/validators.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +CREDENTIAL_FILE=${FLEET_CREDENTIAL_FILE:-${E2E_DIR}/credentials.json} +REPORT_DIR="${E2E_DIR}/validators" +[[ -f "${CREDENTIAL_FILE}" ]] || { echo "missing proxy credential file: ${CREDENTIAL_FILE}" >&2; exit 1; } +mkdir -p "${REPORT_DIR}/service" "${REPORT_DIR}/interop" + +endpoint=$(jq -r .endpoint "${CREDENTIAL_FILE}") +username=$(jq -r .username "${CREDENTIAL_FILE}") +password=$(jq -r .password "${CREDENTIAL_FILE}") +ca_bundle=$(jq -r .caBundle "${CREDENTIAL_FILE}") + +if [[ $(uname -s) == Darwin ]]; then + validator_bin=${FLEET_VALIDATOR_BIN:-/private/tmp/fleet-validator-venv/bin} + REQUESTS_CA_BUNDLE="${ca_bundle}" "${validator_bin}/rf_service_validator" \ + --rhost "${endpoint%/redfish/v1/}" --user "${username}" --password "${password}" \ + --authtype Session --nooemcheck --logdir "${REPORT_DIR}/service" + REQUESTS_CA_BUNDLE="${ca_bundle}" "${validator_bin}/rf_interop_validator" \ + --rhost "${endpoint%/redfish/v1/}" --user "${username}" --password "${password}" \ + --authtype Session --nooemcheck --logdir "${REPORT_DIR}/interop" \ + "${ROOT_DIR}/config/redfish/FleetProvisioning.v1_0_0.json" +else + docker run --rm --network host \ + -e REQUESTS_CA_BUNDLE=/state/ca.pem \ + -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ + fleet-redfish-tools:e2e \ + "rf_service_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/service" + + docker run --rm --network host \ + -e REQUESTS_CA_BUNDLE=/state/ca.pem \ + -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ + fleet-redfish-tools:e2e \ + "rf_interop_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/interop /work/config/redfish/FleetProvisioning.v1_0_0.json" +fi + +echo "DMTF validator reports: ${REPORT_DIR}" diff --git a/internal/cmd/fleet/root.go b/internal/cmd/fleet/root.go new file mode 100644 index 00000000..d7d3cbeb --- /dev/null +++ b/internal/cmd/fleet/root.go @@ -0,0 +1,547 @@ +// SPDX-License-Identifier: Apache-2.0 + +package fleet + +import ( + "context" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io" + "math/big" + "net" + "net/http" + "net/http/httputil" + "net/url" + "os" + "os/signal" + "path/filepath" + "strings" + "sync" + "syscall" + "time" + + "github.com/spf13/cobra" + "go.datum.net/datumctl/plugin" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + "go.datum.net/fleet/internal/gateway" + "go.datum.net/fleet/internal/protocol" + "go.datum.net/fleet/internal/relay" +) + +const ( + ExitUsage = 2 + ExitAuth = 10 + ExitPermission = 11 + ExitAPI = 12 + ExitConnect = 13 +) + +type ExitError struct { + Code int + Err error +} + +func (e *ExitError) Error() string { return e.Err.Error() } +func (e *ExitError) Unwrap() error { return e.Err } + +type proxyOptions struct { + namespace, listen, credentialFile, readyFile, caFile, apiServer, apiCAFile string + ttl time.Duration +} + +func Command() *cobra.Command { + root := plugin.NewRootCmd("fleet", "Manage Datum Fleet resources") + mm := &cobra.Command{Use: "machine-management", Short: "Access allocation-scoped machine management"} + o := &proxyOptions{} + proxy := &cobra.Command{Use: "proxy CLAIM", Short: "Open a short-lived local Redfish endpoint", Args: cobra.ExactArgs(1), SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { return o.run(cmd.Context(), cmd, args[0]) }} + proxy.Flags().StringVar(&o.namespace, "namespace", "default", "MachineClaim namespace") + proxy.Flags().StringVar(&o.listen, "listen", "127.0.0.1:0", "loopback address for the local Redfish endpoint") + proxy.Flags().DurationVar(&o.ttl, "ttl", 15*time.Minute, "session lifetime (1m-15m)") + proxy.Flags().StringVar(&o.credentialFile, "credential-file", "", "0600 JSON credential file (temporary when omitted)") + proxy.Flags().StringVar(&o.readyFile, "ready-file", "", "machine-readable non-secret readiness JSON") + proxy.Flags().StringVar(&o.caFile, "ca-file", "", "session CA bundle path (temporary when omitted)") + proxy.Flags().StringVar(&o.apiServer, "api-server", "", "Fleet/Kubernetes API URL (defaults to datumctl API context)") + proxy.Flags().StringVar(&o.apiCAFile, "api-ca-file", "", "CA bundle for the API server") + mm.AddCommand(proxy) + root.AddCommand(mm) + return root +} + +func (o *proxyOptions) run(parent context.Context, cmd *cobra.Command, claim string) error { + if o.ttl < time.Minute || o.ttl > 15*time.Minute { + return &ExitError{ExitUsage, errors.New("--ttl must be between 1m and 15m")} + } + pctx := plugin.Context() + if pctx.CredentialsHelper == "" { + return &ExitError{ExitAuth, errors.New("run datumctl-fleet through datumctl so the credential helper is available")} + } + if pctx.Project == "" { + return &ExitError{ExitUsage, errors.New("select a Datum project before creating a machine-management session")} + } + token, err := plugin.Token() + if err != nil { + return &ExitError{ExitAuth, fmt.Errorf("obtain credentials through datumctl: %w", err)} + } + api, err := newAPIClient(o, pctx.APIHost, token, pctx.Project) + if err != nil { + return &ExitError{ExitAPI, err} + } + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return &ExitError{ExitConnect, err} + } + defer clear(privateKey) + ctx, cancel := signal.NotifyContext(parent, os.Interrupt, syscall.SIGTERM) + defer cancel() + session, err := api.create(ctx, o.namespace, claim, protocol.PublicKey(privateKey), o.ttl) + if err != nil { + return classifyAPI(err) + } + sessionName := session.Name + defer func() { + revokeCtx, c := context.WithTimeout(context.Background(), 10*time.Second) + defer c() + _ = api.delete(revokeCtx, o.namespace, sessionName) + }() + session, err = api.waitReady(ctx, o.namespace, sessionName) + if err != nil { + return classifyAPI(err) + } + conn, err := connectLocation(ctx, privateKey, session) + if err != nil { + return &ExitError{ExitConnect, err} + } + defer conn.Close() + cleanup, endpoint, err := o.serveLocal(ctx, privateKey, session.UID, session.Status.Connection, conn) + if err != nil { + return &ExitError{ExitConnect, err} + } + defer cleanup() + fmt.Fprintf(cmd.OutOrStdout(), "Session %s is ready until %s\nRedfish endpoint: %s\nReadiness file: %s\n", session.Name, session.Status.ExpiresAt.UTC().Format(time.RFC3339), endpoint, o.readyFile) + <-ctx.Done() + return nil +} + +type apiClient struct { + base, project, token string + client *http.Client +} + +func newAPIClient(o *proxyOptions, host, token, project string) (*apiClient, error) { + base := o.apiServer + if base == "" { + if strings.Contains(host, "://") { + base = host + } else { + base = "https://" + host + } + } + if base == "https://" || base == "" { + return nil, errors.New("datumctl did not provide an API host") + } + transport := http.DefaultTransport.(*http.Transport).Clone() + if o.apiCAFile != "" { + b, err := os.ReadFile(o.apiCAFile) + if err != nil { + return nil, err + } + roots, _ := x509.SystemCertPool() + if roots == nil { + roots = x509.NewCertPool() + } + if !roots.AppendCertsFromPEM(b) { + return nil, errors.New("API CA bundle contains no certificates") + } + transport.TLSClientConfig = &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12} + } + return &apiClient{base: strings.TrimRight(base, "/"), project: project, token: token, client: &http.Client{Transport: transport, Timeout: 30 * time.Second}}, nil +} +func (a *apiClient) url(ns, name string) string { + u := a.base + "/apis/fleet.datumapis.com/v1alpha1/namespaces/" + url.PathEscape(ns) + "/machinemanagementsessions" + if name != "" { + u += "/" + url.PathEscape(name) + } + return u +} +func (a *apiClient) do(ctx context.Context, method, u string, body io.Reader, out any) error { + req, err := http.NewRequestWithContext(ctx, method, u, body) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+a.token) + req.Header.Set("X-Datum-Project", a.project) + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := a.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return &apiError{status: resp.StatusCode, message: strings.TrimSpace(string(b))} + } + if out != nil && resp.StatusCode != http.StatusNoContent { + return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out) + } + return nil +} +func (a *apiClient) create(ctx context.Context, ns, claim, key string, ttl time.Duration) (*fleetv1alpha1.MachineManagementSession, error) { + s := &fleetv1alpha1.MachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{GenerateName: claim + "-", Namespace: ns}, Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineClaimRef: fleetv1alpha1.LocalObjectReference{Name: claim}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: key, TTL: metav1.Duration{Duration: ttl}}} + b, _ := json.Marshal(s) + var out fleetv1alpha1.MachineManagementSession + if err := a.do(ctx, http.MethodPost, a.url(ns, ""), strings.NewReader(string(b)), &out); err != nil { + return nil, err + } + return &out, nil +} +func (a *apiClient) waitReady(ctx context.Context, ns, name string) (*fleetv1alpha1.MachineManagementSession, error) { + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + for { + var s fleetv1alpha1.MachineManagementSession + if err := a.do(ctx, http.MethodGet, a.url(ns, name), nil, &s); err != nil { + return nil, err + } + for _, c := range s.Status.Conditions { + if c.Type == fleetv1alpha1.ConditionReady && c.Status == metav1.ConditionTrue && s.Status.Connection != nil { + return &s, nil + } + if c.Type == fleetv1alpha1.ConditionReady && c.Status == metav1.ConditionFalse { + return nil, fmt.Errorf("session rejected: %s: %s", c.Reason, c.Message) + } + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-ticker.C: + } + } +} +func (a *apiClient) delete(ctx context.Context, ns, name string) error { + return a.do(ctx, http.MethodDelete, a.url(ns, name), nil, nil) +} + +type apiError struct { + status int + message string +} + +func (e *apiError) Error() string { return fmt.Sprintf("API returned %d: %s", e.status, e.message) } +func classifyAPI(err error) error { + var e *apiError + if errors.As(err, &e) { + if e.status == http.StatusUnauthorized { + return &ExitError{ExitAuth, err} + } + if e.status == http.StatusForbidden { + return &ExitError{ExitPermission, err} + } + } + return &ExitError{ExitAPI, err} +} + +func connectLocation(ctx context.Context, key ed25519.PrivateKey, s *fleetv1alpha1.MachineManagementSession) (net.Conn, error) { + c := s.Status.Connection + if c == nil { + return nil, errors.New("session has no connection") + } + u, err := url.Parse(c.RelayURL) + if err != nil || u.Scheme != "tcp" { + return nil, fmt.Errorf("unsupported relay URL %q", c.RelayURL) + } + d := net.Dialer{} + raw, err := d.DialContext(ctx, "tcp", u.Host) + if err != nil { + return nil, fmt.Errorf("reach relay: %w", err) + } + if err := relay.Connect(raw, c.RouteID); err != nil { + _ = raw.Close() + return nil, err + } + expected, err := hex.DecodeString(c.GatewayCertSHA256) + if err != nil || len(expected) != sha256.Size { + _ = raw.Close() + return nil, errors.New("session published an invalid gateway certificate pin") + } + tlsConn := tls.Client(raw, &tls.Config{MinVersion: tls.VersionTLS13, ServerName: "fleet-gateway", NextProtos: []string{"datum-fleet-redfish/1"}, InsecureSkipVerify: true, VerifyConnection: func(cs tls.ConnectionState) error { + if len(cs.PeerCertificates) != 1 { + return errors.New("gateway certificate chain must contain one pinned certificate") + } + sum := sha256.Sum256(cs.PeerCertificates[0].Raw) + if !equal(sum[:], expected) { + return errors.New("gateway certificate does not match the admitted session") + } + return nil + }}) + if err := tlsConn.HandshakeContext(ctx); err != nil { + _ = raw.Close() + return nil, fmt.Errorf("authenticate location gateway: %w", err) + } + return tlsConn, nil +} + +func (o *proxyOptions) serveLocal(ctx context.Context, key ed25519.PrivateKey, sessionUID types.UID, c *fleetv1alpha1.SessionConnection, remote net.Conn) (func(), string, error) { + listener, err := net.Listen("tcp", o.listen) + if err != nil { + return nil, "", err + } + if !isLoopback(listener.Addr()) { + _ = listener.Close() + return nil, "", errors.New("local Redfish endpoint must listen on loopback") + } + cert, caPEM, err := localCertificate() + if err != nil { + _ = listener.Close() + return nil, "", err + } + dir, err := os.MkdirTemp("", "datumctl-fleet-") + if err != nil { + _ = listener.Close() + return nil, "", err + } + removeDir := true + if o.caFile == "" { + o.caFile = filepath.Join(dir, "ca.pem") + } + if o.credentialFile == "" { + o.credentialFile = filepath.Join(dir, "credentials.json") + } + if o.readyFile == "" { + o.readyFile = filepath.Join(dir, "ready.json") + } + cleanup := func() { + _ = listener.Close() + _ = remote.Close() + _ = os.Remove(o.credentialFile) + _ = os.Remove(o.caFile) + _ = os.Remove(o.readyFile) + if removeDir { + _ = os.Remove(dir) + } + } + if err := os.WriteFile(o.caFile, caPEM, 0o600); err != nil { + cleanup() + return nil, "", err + } + password := randomSecret() + username := "fleet" + endpoint := "https://" + listener.Addr().String() + "/redfish/v1/" + credential := map[string]string{"endpoint": endpoint, "username": username, "password": password, "caBundle": o.caFile} + if err := writeJSONFile(o.credentialFile, credential, 0o600); err != nil { + cleanup() + return nil, "", err + } + ready := map[string]any{"ready": true, "endpoint": endpoint, "credentialFile": o.credentialFile, "caBundle": o.caFile, "sessionUID": string(sessionUID)} + if err := writeJSONFile(o.readyFile, ready, 0o644); err != nil { + cleanup() + return nil, "", err + } + transport := &http.Transport{ForceAttemptHTTP2: false, DialTLSContext: singleDialer(remote)} + proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "https", Host: "fleet-gateway"}) + proxy.Transport = transport + original := proxy.Director + proxy.Director = func(r *http.Request) { + original(r) + r.Host = "fleet-gateway" + r.Header.Del("Authorization") + r.Header.Del("X-Auth-Token") + p, _ := protocol.Sign(key, string(sessionUID), c.GatewayAudience, time.Now()) + r.Header.Set(gateway.HeaderSession, string(sessionUID)) + r.Header.Set(gateway.HeaderAudience, c.GatewayAudience) + r.Header.Set(gateway.HeaderTimestamp, p.Timestamp) + r.Header.Set(gateway.HeaderNonce, p.Nonce) + r.Header.Set(gateway.HeaderSignature, p.Signature) + } + local := newLocalAuth(username, password, proxy) + server := &http.Server{Handler: local, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second} + tlsListener := tls.NewListener(listener, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13}) + go func() { + <-ctx.Done() + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = server.Shutdown(shutdown) + }() + go func() { _ = server.Serve(tlsListener) }() + return cleanup, endpoint, nil +} + +func singleDialer(conn net.Conn) func(context.Context, string, string) (net.Conn, error) { + var mu sync.Mutex + used := false + return func(context.Context, string, string) (net.Conn, error) { + mu.Lock() + defer mu.Unlock() + if used { + return nil, errors.New("location connection is single-use") + } + used = true + return conn, nil + } +} +func newLocalAuth(user, password string, next http.Handler) http.Handler { + tokens := map[string]bool{} + var mu sync.Mutex + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !validLocalTarget(r) { + http.Error(w, "arbitrary local targets and Host routing are not accepted", http.StatusBadRequest) + return + } + // Generic Redfish clients discover the service root before creating a + // session. It contains only virtual links and still crosses the admitted, + // proof-protected gateway stream. + if r.Method == http.MethodGet && (r.URL.Path == "/redfish/v1" || r.URL.Path == "/redfish/v1/") { + // DMTF clients commonly probe the slashless URI first. Canonicalize it + // for the virtual gateway without redirecting or exposing another host. + if r.URL.Path == "/redfish/v1" { + r.URL.Path = "/redfish/v1/" + } + next.ServeHTTP(w, r) + return + } + if r.Method == http.MethodPost && r.URL.Path == "/redfish/v1/SessionService/Sessions" { + var in struct { + UserName string `json:"UserName"` + Password string `json:"Password"` + } + if json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&in) != nil || in.UserName != user || in.Password != password { + http.Error(w, "invalid local Redfish credentials", http.StatusUnauthorized) + return + } + token := randomSecret() + mu.Lock() + tokens[token] = true + mu.Unlock() + w.Header().Set("X-Auth-Token", token) + w.Header().Set("Location", "/redfish/v1/SessionService/Sessions/local") + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = io.WriteString(w, `{"@odata.id":"/redfish/v1/SessionService/Sessions/local","Id":"local","Name":"Fleet local session"}`) + return + } + if r.Method == http.MethodDelete && r.URL.Path == "/redfish/v1/SessionService/Sessions/local" { + token := r.Header.Get("X-Auth-Token") + mu.Lock() + valid := tokens[token] + if valid { + delete(tokens, token) + } + mu.Unlock() + if !valid { + http.Error(w, "invalid local Redfish session", http.StatusUnauthorized) + return + } + w.WriteHeader(http.StatusNoContent) + return + } + authorized := false + if u, p, ok := r.BasicAuth(); ok && u == user && p == password { + authorized = true + } + mu.Lock() + if tokens[r.Header.Get("X-Auth-Token")] { + authorized = true + } + mu.Unlock() + if !authorized { + w.Header().Set("WWW-Authenticate", `Basic realm="Fleet Redfish"`) + http.Error(w, "local Redfish authentication required", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) +} + +func validLocalTarget(r *http.Request) bool { + if r.URL.IsAbs() || r.RequestURI == "*" || strings.Contains(r.URL.Path, "..") || !strings.HasPrefix(r.URL.Path, "/redfish/v1") { + return false + } + if r.URL.RawPath != "" { + unescaped, err := url.PathUnescape(r.URL.RawPath) + if err != nil || unescaped != r.URL.Path { + return false + } + } + host := r.Host + if parsed, _, err := net.SplitHostPort(host); err == nil { + host = parsed + } + host = strings.Trim(host, "[]") + return host == "localhost" || (net.ParseIP(host) != nil && net.ParseIP(host).IsLoopback()) +} +func localCertificate() (tls.Certificate, []byte, error) { + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return tls.Certificate{}, nil, err + } + pub := &priv.PublicKey + serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + now := time.Now() + tmpl := x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "datumctl-fleet local Redfish"}, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, DNSNames: []string{"localhost"}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IsCA: true, BasicConstraintsValid: true} + der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, pub, priv) + if err != nil { + return tls.Certificate{}, nil, err + } + keyDER, _ := x509.MarshalPKCS8PrivateKey(priv) + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) + cert, err := tls.X509KeyPair(certPEM, keyPEM) + return cert, certPEM, err +} +func randomSecret() string { b := make([]byte, 24); _, _ = rand.Read(b); return hex.EncodeToString(b) } +func writeJSONFile(path string, v any, mode os.FileMode) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + b, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode) + if err != nil { + return err + } + if err := f.Chmod(mode); err != nil { + _ = f.Close() + return err + } + if _, err := f.Write(b); err != nil { + _ = f.Close() + return err + } + return f.Close() +} +func isLoopback(addr net.Addr) bool { + host, _, err := net.SplitHostPort(addr.String()) + if err != nil { + return false + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} +func equal(a, b []byte) bool { + if len(a) != len(b) { + return false + } + var v byte + for i := range a { + v |= a[i] ^ b[i] + } + return v == 0 +} diff --git a/internal/cmd/fleet/root_test.go b/internal/cmd/fleet/root_test.go new file mode 100644 index 00000000..fb3b11f4 --- /dev/null +++ b/internal/cmd/fleet/root_test.go @@ -0,0 +1,76 @@ +package fleet + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestLocalRedfishSessionCanBeDeleted(t *testing.T) { + nextCalls := 0 + h := newLocalAuth("fleet", "secret", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { nextCalls++ })) + login := httptest.NewRequest(http.MethodPost, "/redfish/v1/SessionService/Sessions", strings.NewReader(`{"UserName":"fleet","Password":"secret"}`)) + login.Host = "127.0.0.1:9443" + w := httptest.NewRecorder() + h.ServeHTTP(w, login) + if w.Code != http.StatusCreated || w.Header().Get("X-Auth-Token") == "" { + t.Fatalf("login: %d %#v", w.Code, w.Header()) + } + token := w.Header().Get("X-Auth-Token") + del := httptest.NewRequest(http.MethodDelete, "/redfish/v1/SessionService/Sessions/local", nil) + del.Host = "127.0.0.1:9443" + del.Header.Set("X-Auth-Token", token) + w = httptest.NewRecorder() + h.ServeHTTP(w, del) + if w.Code != http.StatusNoContent { + t.Fatalf("delete: %d", w.Code) + } + get := httptest.NewRequest(http.MethodGet, "/redfish/v1/Systems", nil) + get.Host = "127.0.0.1:9443" + get.Header.Set("X-Auth-Token", token) + w = httptest.NewRecorder() + h.ServeHTTP(w, get) + if w.Code != http.StatusUnauthorized || nextCalls != 0 { + t.Fatalf("deleted token accepted: status=%d calls=%d", w.Code, nextCalls) + } +} + +func TestLocalConnectorAllowsSlashlessServiceRootDiscovery(t *testing.T) { + called := false + h := newLocalAuth("fleet", "secret", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + called = true + if r.URL.Path != "/redfish/v1/" { + t.Fatalf("path = %q, want canonical service root", r.URL.Path) + } + })) + r := httptest.NewRequest(http.MethodGet, "/redfish/v1", nil) + r.Host = "127.0.0.1:9443" + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if !called || w.Code != http.StatusOK { + t.Fatalf("service root discovery: called=%v status=%d", called, w.Code) + } +} + +func TestLocalConnectorRejectsArbitraryRouting(t *testing.T) { + h := newLocalAuth("fleet", "secret", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + t.Fatal("rejected target reached proxy") + })) + for _, test := range []struct { + target string + host string + }{ + {target: "/redfish/v1/Systems", host: "bmc.private"}, + {target: "http://bmc.private/redfish/v1/Systems", host: "bmc.private"}, + {target: "/redfish/v1/Systems/../Managers", host: "127.0.0.1:9443"}, + } { + r := httptest.NewRequest(http.MethodGet, test.target, nil) + r.Host = test.host + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusBadRequest { + t.Fatalf("target=%q host=%q: %d", test.target, test.host, w.Code) + } + } +} diff --git a/internal/controller/admission.go b/internal/controller/admission.go new file mode 100644 index 00000000..784841d8 --- /dev/null +++ b/internal/controller/admission.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "encoding/json" + "reflect" + "time" + + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" +) + +// SessionAdmission retains the authenticated API principal before the +// asynchronous controller resolves private allocation state. Kubernetes RBAC +// separately controls create on sessions; claim read permission does not imply it. +type SessionAdmission struct{} + +func (SessionAdmission) Handle(_ context.Context, req admission.Request) admission.Response { + var session fleetv1alpha1.MachineManagementSession + if err := json.Unmarshal(req.Object.Raw, &session); err != nil { + return admission.Errored(400, err) + } + if req.Operation == admissionv1.Update { + var old fleetv1alpha1.MachineManagementSession + if err := json.Unmarshal(req.OldObject.Raw, &old); err != nil { + return admission.Errored(400, err) + } + if !reflect.DeepEqual(session.Spec, old.Spec) { + return admission.Denied("spec is immutable; create a new session") + } + if session.Annotations[PrincipalAnnotation] != old.Annotations[PrincipalAnnotation] { + return admission.Denied("requesting principal is service-owned") + } + return admission.Allowed("immutable session update") + } + if req.Operation != admissionv1.Create { + return admission.Allowed("no mutation required") + } + if session.Spec.Protocol != "Redfish" || session.Spec.AccessProfile != "Provisioning" { + return admission.Denied("only the Redfish Provisioning profile is supported") + } + if session.Spec.TTL.Duration == 0 { + session.Spec.TTL = metav1.Duration{Duration: 15 * time.Minute} + } + if session.Annotations == nil { + session.Annotations = map[string]string{} + } + session.Annotations[PrincipalAnnotation] = req.UserInfo.Username + mutated, err := json.Marshal(&session) + if err != nil { + return admission.Errored(500, err) + } + return admission.PatchResponseFromRaw(req.Object.Raw, mutated) +} diff --git a/internal/controller/admission_test.go b/internal/controller/admission_test.go new file mode 100644 index 00000000..d3964216 --- /dev/null +++ b/internal/controller/admission_test.go @@ -0,0 +1,36 @@ +package controller + +import ( + "context" + "encoding/json" + "testing" + + admissionv1 "k8s.io/api/admission/v1" + authnv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" +) + +func TestAdmissionRetainsAuthenticatedPrincipal(t *testing.T) { + s := fleetv1alpha1.MachineManagementSession{Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineClaimRef: fleetv1alpha1.LocalObjectReference{Name: "db-01"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}} + raw, _ := json.Marshal(s) + resp := SessionAdmission{}.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{Operation: admissionv1.Create, Object: runtime.RawExtension{Raw: raw}, UserInfo: authnv1.UserInfo{Username: "alice@example.test"}}}) + if !resp.Allowed || len(resp.Patches) == 0 { + t.Fatalf("response %+v", resp) + } +} + +func TestAdmissionRejectsSpecMutation(t *testing.T) { + old := fleetv1alpha1.MachineManagementSession{ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{PrincipalAnnotation: "alice"}}, Spec: fleetv1alpha1.MachineManagementSessionSpec{Protocol: "Redfish", AccessProfile: "Provisioning"}} + newObj := *old.DeepCopy() + newObj.Spec.AccessProfile = "Other" + oldRaw, _ := json.Marshal(old) + newRaw, _ := json.Marshal(newObj) + resp := SessionAdmission{}.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{Operation: admissionv1.Update, Object: runtime.RawExtension{Raw: newRaw}, OldObject: runtime.RawExtension{Raw: oldRaw}}}) + if resp.Allowed { + t.Fatal("mutable spec accepted") + } +} diff --git a/internal/controller/projection.go b/internal/controller/projection.go new file mode 100644 index 00000000..0a826b11 --- /dev/null +++ b/internal/controller/projection.go @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "fmt" + "reflect" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" +) + +// ProjectionReconciler carries the least-privileged session copy into one +// authoritative location API. It never participates in Redfish transport. +type ProjectionReconciler struct { + client.Client + LocationClient client.Client + SystemNamespace string + LocationNamespace string + Now func() time.Time + Freshness time.Duration +} + +func (r *ProjectionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + var b fleetv1alpha1.MachineManagementSessionBinding + if err := r.Get(ctx, req.NamespacedName, &b); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if req.Namespace != r.systemNamespace() { + return ctrl.Result{}, nil + } + key := types.NamespacedName{Namespace: r.locationNamespace(), Name: b.Name} + active := r.allocationStillActive(ctx, &b) + if !active && b.Annotations[RevokedAtAnnotation] == "" { + patch := client.MergeFrom(b.DeepCopy()) + if b.Annotations == nil { + b.Annotations = map[string]string{} + } + // Allocation release is a one-way fence for this admitted session. An + // allocator later reusing the claim name or reactivating a record cannot + // resurrect authority tied to the old binding epoch. + b.Annotations[RevokedAtAnnotation] = r.now().UTC().Format(time.RFC3339Nano) + if err := r.Patch(ctx, &b, patch); err != nil { + return ctrl.Result{}, err + } + } + if b.Annotations[RevokedAtAnnotation] != "" || !active { + return r.removeProjection(ctx, &b, key) + } + var p fleetv1alpha1.ProjectedMachineManagementSession + err := r.LocationClient.Get(ctx, key, &p) + if apierrors.IsNotFound(err) { + p = *r.build(&b) + if err := r.LocationClient.Create(ctx, &p); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } + if err != nil { + return ctrl.Result{}, err + } + if !projectionMatches(&b, &p) { + setNamedCondition(&b.Status.Conditions, fleetv1alpha1.ConditionReady, b.Generation, metav1.ConditionFalse, "ProjectionChanged", "Location projection no longer matches the admitted session inputs.", r.now()) + return ctrl.Result{}, r.Status().Update(ctx, &b) + } + // Refresh only cached-authority time while all immutable binding inputs match. + fresh := metav1.NewTime(r.now().Add(r.freshness())) + if p.Spec.AuthorityFreshUntil.Before(&fresh) { + patch := client.MergeFrom(p.DeepCopy()) + p.Spec.AuthorityFreshUntil = fresh + if err := r.LocationClient.Patch(ctx, &p, patch); err != nil { + return ctrl.Result{}, err + } + } + if !reflect.DeepEqual(b.Status.Connection, p.Status.Connection) || !reflect.DeepEqual(b.Status.Conditions, p.Status.Conditions) { + b.Status.Connection = p.Status.Connection + b.Status.Conditions = append([]metav1.Condition(nil), p.Status.Conditions...) + for i := range b.Status.Conditions { + b.Status.Conditions[i].ObservedGeneration = b.Generation + } + if err := r.Status().Update(ctx, &b); err != nil { + return ctrl.Result{}, err + } + } + if p.Status.Connection == nil { + return ctrl.Result{RequeueAfter: 2 * time.Second}, nil + } + return ctrl.Result{RequeueAfter: r.freshness() / 2}, nil +} + +func (r *ProjectionReconciler) allocationStillActive(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding) bool { + var list fleetv1alpha1.MachineAllocationBindingList + if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace()), client.MatchingLabels{ClaimUIDLabel: string(b.Spec.ClaimUID)}); err != nil || len(list.Items) != 1 { + return false + } + a := list.Items[0].Spec + return a.Active && a.ClaimUID == b.Spec.ClaimUID && a.MachineUID == b.Spec.MachineUID && a.BindingID == b.Spec.BindingID && a.BindingEpoch == b.Spec.BindingEpoch && a.LocationUID == b.Spec.LocationUID && a.LocationRevision == b.Spec.LocationRevision && a.AdapterRoute == b.Spec.AdapterRoute +} + +func (r *ProjectionReconciler) removeProjection(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding, key types.NamespacedName) (ctrl.Result, error) { + var p fleetv1alpha1.ProjectedMachineManagementSession + err := r.LocationClient.Get(ctx, key, &p) + if err == nil { + if p.DeletionTimestamp.IsZero() { + if err := r.LocationClient.Delete(ctx, &p); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } + if !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionTrue, "LocationTeardownConfirmed", "The location session projection was removed.", r.now()) + setNamedCondition(&b.Status.Conditions, fleetv1alpha1.ConditionReady, b.Generation, metav1.ConditionFalse, "Revoked", "The session authority has ended.", r.now()) + return ctrl.Result{}, r.Status().Update(ctx, b) +} + +func (r *ProjectionReconciler) build(b *fleetv1alpha1.MachineManagementSessionBinding) *fleetv1alpha1.ProjectedMachineManagementSession { + s := b.Spec + return &fleetv1alpha1.ProjectedMachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "ProjectedMachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{Name: b.Name, Namespace: r.locationNamespace(), Labels: map[string]string{SessionUIDLabel: string(s.SessionUID), ClaimUIDLabel: string(s.ClaimUID)}}, Spec: fleetv1alpha1.ProjectedMachineManagementSessionSpec{SessionUID: s.SessionUID, ClaimUID: s.ClaimUID, MachineUID: s.MachineUID, BindingID: s.BindingID, BindingEpoch: s.BindingEpoch, LocationUID: s.LocationUID, LocationRevision: s.LocationRevision, BareMetalMachineUID: s.BareMetalMachineUID, AccessProfileRevision: s.AccessProfileRevision, ClientPublicKey: s.ClientPublicKey, ConnectBefore: s.ConnectBefore, ExpiresAt: s.ExpiresAt, AuthorityFreshUntil: metav1.NewTime(r.now().Add(r.freshness())), SessionCorrelationID: s.SessionCorrelationID, OperationCorrelationID: s.OperationCorrelationID, AdapterRoute: s.AdapterRoute, BMCSystemID: s.BMCSystemID}} +} + +func projectionMatches(b *fleetv1alpha1.MachineManagementSessionBinding, p *fleetv1alpha1.ProjectedMachineManagementSession) bool { + s := b.Spec + x := p.Spec + return x.SessionUID == s.SessionUID && x.ClaimUID == s.ClaimUID && x.MachineUID == s.MachineUID && x.BindingID == s.BindingID && x.BindingEpoch == s.BindingEpoch && x.LocationUID == s.LocationUID && x.LocationRevision == s.LocationRevision && x.BareMetalMachineUID == s.BareMetalMachineUID && x.AccessProfileRevision == s.AccessProfileRevision && x.ClientPublicKey == s.ClientPublicKey && x.ConnectBefore.Equal(&s.ConnectBefore) && x.ExpiresAt.Equal(&s.ExpiresAt) && x.AdapterRoute == s.AdapterRoute && x.BMCSystemID == s.BMCSystemID +} +func (r *ProjectionReconciler) SetupWithManager(mgr ctrl.Manager) error { + if r.LocationClient == nil { + return fmt.Errorf("location client is required") + } + r.Client = mgr.GetClient() + return ctrl.NewControllerManagedBy(mgr). + For(&fleetv1alpha1.MachineManagementSessionBinding{}). + Watches(&fleetv1alpha1.MachineAllocationBinding{}, handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, obj client.Object) []reconcile.Request { + a := obj.(*fleetv1alpha1.MachineAllocationBinding) + var list fleetv1alpha1.MachineManagementSessionBindingList + if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace()), client.MatchingLabels{ClaimUIDLabel: string(a.Spec.ClaimUID)}); err != nil { + return nil + } + out := make([]reconcile.Request, 0, len(list.Items)) + for i := range list.Items { + out = append(out, reconcile.Request{NamespacedName: types.NamespacedName{Namespace: list.Items[i].Namespace, Name: list.Items[i].Name}}) + } + return out + })).Complete(r) +} +func (r *ProjectionReconciler) systemNamespace() string { + if r.SystemNamespace != "" { + return r.SystemNamespace + } + return SystemNamespace +} +func (r *ProjectionReconciler) locationNamespace() string { + if r.LocationNamespace != "" { + return r.LocationNamespace + } + return LocationNamespace +} +func (r *ProjectionReconciler) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} +func (r *ProjectionReconciler) freshness() time.Duration { + if r.Freshness > 0 { + return r.Freshness + } + return DefaultAuthorityFreshness +} + +var _ = apimeta.FindStatusCondition diff --git a/internal/controller/projection_test.go b/internal/controller/projection_test.go new file mode 100644 index 00000000..d4e4c8d0 --- /dev/null +++ b/internal/controller/projection_test.go @@ -0,0 +1,54 @@ +package controller + +import ( + "context" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" +) + +func TestReleasedAllocationTerminallyRevokesProjection(t *testing.T) { + scheme := runtime.NewScheme() + if err := fleetv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + now := time.Unix(1000, 0).UTC() + binding := &fleetv1alpha1.MachineManagementSessionBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "session-uid", Namespace: SystemNamespace}, + Spec: fleetv1alpha1.MachineManagementSessionBindingSpec{ + SessionUID: "session-uid", ClaimUID: "claim-uid", MachineUID: "machine-uid", + BindingID: "binding", BindingEpoch: 1, LocationUID: "location", LocationRevision: "r1", + AdapterRoute: "sushy-libvirt-v1", ExpiresAt: metav1.NewTime(now.Add(time.Hour)), + }, + } + allocation := &fleetv1alpha1.MachineAllocationBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: SystemNamespace, Labels: map[string]string{ClaimUIDLabel: "claim-uid"}}, + Spec: fleetv1alpha1.MachineAllocationBindingSpec{ClaimUID: "claim-uid", MachineUID: "machine-uid", BindingID: "binding", BindingEpoch: 1, LocationUID: "location", LocationRevision: "r1", AdapterRoute: "sushy-libvirt-v1", Active: false}, + } + projection := &fleetv1alpha1.ProjectedMachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: binding.Name, Namespace: LocationNamespace}} + primary := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(binding).WithObjects(binding, allocation).Build() + location := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(projection).WithObjects(projection).Build() + r := &ProjectionReconciler{Client: primary, LocationClient: location, Now: func() time.Time { return now }} + _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: SystemNamespace, Name: binding.Name}}) + if err != nil { + t.Fatal(err) + } + var got fleetv1alpha1.MachineManagementSessionBinding + if err := primary.Get(context.Background(), types.NamespacedName{Namespace: SystemNamespace, Name: binding.Name}, &got); err != nil { + t.Fatal(err) + } + if got.Annotations[RevokedAtAnnotation] == "" { + t.Fatal("released allocation did not permanently revoke admitted binding") + } + var removed fleetv1alpha1.ProjectedMachineManagementSession + if err := location.Get(context.Background(), types.NamespacedName{Namespace: LocationNamespace, Name: binding.Name}, &removed); err == nil { + t.Fatal("location projection survived allocation release") + } +} diff --git a/internal/controller/session.go b/internal/controller/session.go new file mode 100644 index 00000000..61b007fd --- /dev/null +++ b/internal/controller/session.go @@ -0,0 +1,290 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "log/slog" + "reflect" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetmetrics "go.datum.net/fleet/internal/metrics" +) + +const ( + SystemNamespace = "fleet-system" + LocationNamespace = "machine-access-system" + PrincipalAnnotation = "fleet.datumapis.com/requesting-principal" + ClaimUIDLabel = "fleet.datumapis.com/claim-uid" + SessionUIDLabel = "fleet.datumapis.com/session-uid" + RevokedAtAnnotation = "fleet.datumapis.com/revoked-at" + DefaultConnectWindow = time.Minute + DefaultAuthorityFreshness = 2 * time.Minute +) + +type SessionReconciler struct { + client.Client + SystemNamespace string + Now func() time.Time + PerClaimLimit int + PerProjectLimit int +} + +func (r *SessionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + var session fleetv1alpha1.MachineManagementSession + if err := r.Get(ctx, req.NamespacedName, &session); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if !session.DeletionTimestamp.IsZero() { + return r.revoke(ctx, &session) + } + if !controllerutil.ContainsFinalizer(&session, fleetv1alpha1.SessionFinalizer) { + patch := client.MergeFrom(session.DeepCopy()) + controllerutil.AddFinalizer(&session, fleetv1alpha1.SessionFinalizer) + if err := r.Patch(ctx, &session, patch); err != nil { + return ctrl.Result{}, err + } + } + if session.UID == "" { + return ctrl.Result{RequeueAfter: time.Second}, nil + } + bindingName := string(session.UID) + var admitted fleetv1alpha1.MachineManagementSessionBinding + err := r.Get(ctx, types.NamespacedName{Namespace: r.systemNamespace(), Name: bindingName}, &admitted) + if apierrors.IsNotFound(err) { + return r.admit(ctx, &session) + } + if err != nil { + return ctrl.Result{}, err + } + if admitted.Spec.SessionUID != session.UID { + return ctrl.Result{}, fmt.Errorf("protected binding UID mismatch") + } + return r.reflect(ctx, &session, &admitted) +} + +func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.MachineManagementSession) (ctrl.Result, error) { + principal := session.Annotations[PrincipalAnnotation] + if principal == "" { + return r.reject(ctx, session, "PrincipalMissing", "Admission did not retain the authenticated principal.") + } + var claim fleetv1alpha1.MachineClaim + key := types.NamespacedName{Namespace: session.Namespace, Name: session.Spec.MachineClaimRef.Name} + if err := r.Get(ctx, key, &claim); err != nil { + if apierrors.IsNotFound(err) { + return r.reject(ctx, session, "ClaimNotFound", "The MachineClaim does not exist.") + } + return ctrl.Result{}, err + } + var allocations fleetv1alpha1.MachineAllocationBindingList + if err := r.List(ctx, &allocations, client.InNamespace(r.systemNamespace()), client.MatchingLabels{ClaimUIDLabel: string(claim.UID)}); err != nil { + return ctrl.Result{}, err + } + if len(allocations.Items) != 1 || !allocations.Items[0].Spec.Active { + return r.reject(ctx, session, "ClaimNotActive", "The MachineClaim has no active authoritative allocation.") + } + a := allocations.Items[0] + if a.Spec.ClaimUID != claim.UID || a.Spec.ClaimName != claim.Name || a.Spec.ClaimNamespace != claim.Namespace { + return r.reject(ctx, session, "AllocationChanged", "The retained allocation does not match this claim incarnation.") + } + if result, err := r.enforceLimits(ctx, a.Spec.ConsumerProjectUID, claim.UID); err != nil || result != nil { + if err != nil { + return ctrl.Result{}, err + } + return r.reject(ctx, session, "SessionLimitExceeded", *result) + } + now := r.now() + ttl := session.Spec.TTL.Duration + if ttl <= 0 { + ttl = 15 * time.Minute + } + connect := metav1.NewTime(now.Add(DefaultConnectWindow)) + expiry := metav1.NewTime(now.Add(ttl)) + b := &fleetv1alpha1.MachineManagementSessionBinding{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSessionBinding"}, ObjectMeta: metav1.ObjectMeta{Name: string(session.UID), Namespace: r.systemNamespace(), Labels: map[string]string{SessionUIDLabel: string(session.UID), ClaimUIDLabel: string(claim.UID)}}, Spec: fleetv1alpha1.MachineManagementSessionBindingSpec{SessionNamespace: session.Namespace, SessionName: session.Name, SessionUID: session.UID, RequestingPrincipal: principal, ConsumerProjectUID: a.Spec.ConsumerProjectUID, ProviderProjectUID: a.Spec.ProviderProjectUID, ClaimName: claim.Name, ClaimUID: claim.UID, MachineName: a.Spec.MachineName, MachineUID: a.Spec.MachineUID, BindingID: a.Spec.BindingID, BindingEpoch: a.Spec.BindingEpoch, LocationUID: a.Spec.LocationUID, LocationRevision: a.Spec.LocationRevision, BareMetalMachineUID: a.Spec.BareMetalMachineUID, AccessProfileRevision: a.Spec.AccessProfileRevision, ClientPublicKey: session.Spec.ClientPublicKey, ConnectBefore: connect, ExpiresAt: expiry, SessionCorrelationID: randomID(), OperationCorrelationID: randomID(), AdapterRoute: a.Spec.AdapterRoute, BMCSystemID: a.Spec.BMCSystemID}} + if err := r.Create(ctx, b); err != nil { + if apierrors.IsAlreadyExists(err) { + return ctrl.Result{Requeue: true}, nil + } + return ctrl.Result{}, err + } + fleetmetrics.SessionAdmissions.WithLabelValues("admitted").Inc() + slog.InfoContext(ctx, "machine-management session admitted", + "sessionUID", session.UID, "claimUID", claim.UID, "machineUID", a.Spec.MachineUID, + "bindingID", a.Spec.BindingID, "bindingEpoch", a.Spec.BindingEpoch, + "principal", principal, "sessionCorrelationID", b.Spec.SessionCorrelationID) + return ctrl.Result{RequeueAfter: time.Second}, nil +} + +func (r *SessionReconciler) enforceLimits(ctx context.Context, projectUID, claimUID types.UID) (*string, error) { + var list fleetv1alpha1.MachineManagementSessionBindingList + if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace())); err != nil { + return nil, err + } + claimCount, projectCount := 0, 0 + now := r.now() + for i := range list.Items { + b := &list.Items[i] + if !b.Spec.ExpiresAt.After(now) || b.Annotations[RevokedAtAnnotation] != "" { + continue + } + if b.Spec.ClaimUID == claimUID { + claimCount++ + } + if b.Spec.ConsumerProjectUID == projectUID { + projectCount++ + } + } + cl := r.PerClaimLimit + if cl == 0 { + cl = 1 + } + pl := r.PerProjectLimit + if pl == 0 { + pl = 5 + } + if claimCount >= cl { + s := fmt.Sprintf("The claim already has %d active session(s); limit is %d.", claimCount, cl) + return &s, nil + } + if projectCount >= pl { + s := fmt.Sprintf("The project already has %d active session(s); limit is %d.", projectCount, pl) + return &s, nil + } + return nil, nil +} + +func (r *SessionReconciler) reflect(ctx context.Context, s *fleetv1alpha1.MachineManagementSession, b *fleetv1alpha1.MachineManagementSessionBinding) (ctrl.Result, error) { + if equalityStatus(s, b) { + if r.now().After(b.Spec.ExpiresAt.Time) { + patch := client.MergeFrom(b.DeepCopy()) + if b.Annotations == nil { + b.Annotations = map[string]string{} + } + b.Annotations[RevokedAtAnnotation] = r.now().UTC().Format(time.RFC3339Nano) + if err := r.Patch(ctx, b, patch); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{RequeueAfter: time.Until(b.Spec.ExpiresAt.Time)}, nil + } + s.Status.ConnectBefore = b.Spec.ConnectBefore.DeepCopy() + s.Status.ExpiresAt = b.Spec.ExpiresAt.DeepCopy() + s.Status.Connection = b.Status.Connection + if c := apimeta.FindStatusCondition(b.Status.Conditions, fleetv1alpha1.ConditionReady); c != nil { + condition := *c + condition.ObservedGeneration = s.Generation + apimeta.SetStatusCondition(&s.Status.Conditions, condition) + } else { + setCondition(&s.Status.Conditions, s.Generation, metav1.ConditionUnknown, "Pending", "Waiting for location projection.", r.now()) + } + if err := r.Status().Update(ctx, s); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: time.Until(b.Spec.ExpiresAt.Time)}, nil +} + +func (r *SessionReconciler) reject(ctx context.Context, s *fleetv1alpha1.MachineManagementSession, reason, message string) (ctrl.Result, error) { + fleetmetrics.SessionAdmissions.WithLabelValues(reason).Inc() + slog.WarnContext(ctx, "machine-management session rejected", "sessionUID", s.UID, "reason", reason) + setCondition(&s.Status.Conditions, s.Generation, metav1.ConditionFalse, reason, message, r.now()) + return ctrl.Result{}, r.Status().Update(ctx, s) +} + +func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.MachineManagementSession) (ctrl.Result, error) { + if !controllerutil.ContainsFinalizer(s, fleetv1alpha1.SessionFinalizer) { + return ctrl.Result{}, nil + } + var b fleetv1alpha1.MachineManagementSessionBinding + key := types.NamespacedName{Namespace: r.systemNamespace(), Name: string(s.UID)} + if err := r.Get(ctx, key, &b); err == nil { + if b.Annotations[RevokedAtAnnotation] == "" { + patch := client.MergeFrom(b.DeepCopy()) + if b.Annotations == nil { + b.Annotations = map[string]string{} + } + b.Annotations[RevokedAtAnnotation] = r.now().UTC().Format(time.RFC3339Nano) + if err := r.Patch(ctx, &b, patch); err != nil { + return ctrl.Result{}, err + } + slog.InfoContext(ctx, "machine-management session revocation requested", "sessionUID", s.UID, "bindingID", b.Spec.BindingID, "sessionCorrelationID", b.Spec.SessionCorrelationID) + } + if c := apimeta.FindStatusCondition(b.Status.Conditions, "CleanupConfirmed"); c != nil && c.Status == metav1.ConditionTrue { + fleetmetrics.RevocationLatency.Observe(r.now().Sub(s.DeletionTimestamp.Time).Seconds()) + patch := client.MergeFrom(s.DeepCopy()) + controllerutil.RemoveFinalizer(s, fleetv1alpha1.SessionFinalizer) + return ctrl.Result{}, r.Patch(ctx, s, patch) + } + if r.now().After(s.DeletionTimestamp.Add(30 * time.Second)) { + fleetmetrics.RevocationLatency.Observe(r.now().Sub(s.DeletionTimestamp.Time).Seconds()) + setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionUnknown, "LocationUnconfirmed", "The location did not confirm session teardown.", r.now()) + if err := r.Status().Update(ctx, &b); err != nil { + return ctrl.Result{}, err + } + patch := client.MergeFrom(s.DeepCopy()) + controllerutil.RemoveFinalizer(s, fleetv1alpha1.SessionFinalizer) + return ctrl.Result{}, r.Patch(ctx, s, patch) + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } else if !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + patch := client.MergeFrom(s.DeepCopy()) + controllerutil.RemoveFinalizer(s, fleetv1alpha1.SessionFinalizer) + return ctrl.Result{}, r.Patch(ctx, s, patch) +} + +func (r *SessionReconciler) SetupWithManager(mgr ctrl.Manager) error { + r.Client = mgr.GetClient() + return ctrl.NewControllerManagedBy(mgr). + For(&fleetv1alpha1.MachineManagementSession{}). + Watches(&fleetv1alpha1.MachineManagementSessionBinding{}, handler.EnqueueRequestsFromMapFunc(func(_ context.Context, obj client.Object) []reconcile.Request { + b := obj.(*fleetv1alpha1.MachineManagementSessionBinding) + return []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: b.Spec.SessionNamespace, Name: b.Spec.SessionName}}} + })). + WithOptions(controller.Options{MaxConcurrentReconciles: 1}).Complete(r) +} +func (r *SessionReconciler) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} +func (r *SessionReconciler) systemNamespace() string { + if r.SystemNamespace != "" { + return r.SystemNamespace + } + return SystemNamespace +} + +func setCondition(cs *[]metav1.Condition, generation int64, status metav1.ConditionStatus, reason, message string, now time.Time) { + apimeta.SetStatusCondition(cs, metav1.Condition{Type: fleetv1alpha1.ConditionReady, Status: status, Reason: reason, Message: message, ObservedGeneration: generation, LastTransitionTime: metav1.NewTime(now)}) +} +func setNamedCondition(cs *[]metav1.Condition, name string, generation int64, status metav1.ConditionStatus, reason, message string, now time.Time) { + apimeta.SetStatusCondition(cs, metav1.Condition{Type: name, Status: status, Reason: reason, Message: message, ObservedGeneration: generation, LastTransitionTime: metav1.NewTime(now)}) +} +func randomID() string { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} + +func equalityStatus(s *fleetv1alpha1.MachineManagementSession, b *fleetv1alpha1.MachineManagementSessionBinding) bool { + return reflect.DeepEqual(s.Status.Connection, b.Status.Connection) && reflect.DeepEqual(s.Status.Conditions, b.Status.Conditions) && s.Status.ConnectBefore != nil && s.Status.ConnectBefore.Equal(&b.Spec.ConnectBefore) && s.Status.ExpiresAt != nil && s.Status.ExpiresAt.Equal(&b.Spec.ExpiresAt) +} diff --git a/internal/controller/session_test.go b/internal/controller/session_test.go new file mode 100644 index 00000000..84111cec --- /dev/null +++ b/internal/controller/session_test.go @@ -0,0 +1,79 @@ +package controller + +import ( + "context" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" +) + +func testScheme(t *testing.T) *runtime.Scheme { + t.Helper() + s := runtime.NewScheme() + if err := fleetv1alpha1.AddToScheme(s); err != nil { + t.Fatal(err) + } + return s +} + +func TestAdmissionPinsProtectedAllocation(t *testing.T) { + scheme := testScheme(t) + now := time.Unix(1000, 0) + claim := &fleetv1alpha1.MachineClaim{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineClaim"}, ObjectMeta: metav1.ObjectMeta{Name: "db-01", Namespace: "default", UID: "claim-uid"}} + allocation := testAllocation(claim.UID) + session := testSession("session-uid") + c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(session, &fleetv1alpha1.MachineManagementSessionBinding{}).WithObjects(claim, allocation, session).Build() + r := &SessionReconciler{Client: c, Now: func() time.Time { return now }} + req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "default", Name: "access"}} + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatal(err) + } // finalizer + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatal(err) + } // binding + var b fleetv1alpha1.MachineManagementSessionBinding + if err := c.Get(context.Background(), types.NamespacedName{Namespace: SystemNamespace, Name: "session-uid"}, &b); err != nil { + t.Fatal(err) + } + if b.Spec.ClaimUID != "claim-uid" || b.Spec.MachineUID != "machine-uid" || b.Spec.ProviderProjectUID != "provider-project" || b.Spec.RequestingPrincipal != "alice@example.test" { + t.Fatalf("binding not pinned: %+v", b.Spec) + } + if b.Spec.AdapterRoute == "" || b.Spec.BMCSystemID == "" { + t.Fatal("private adapter identity missing") + } +} + +func TestRecreatedClaimNameCannotInheritAllocation(t *testing.T) { + scheme := testScheme(t) + claim := &fleetv1alpha1.MachineClaim{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineClaim"}, ObjectMeta: metav1.ObjectMeta{Name: "db-01", Namespace: "default", UID: "new-claim-uid"}} + allocation := testAllocation("old-claim-uid") + allocation.Labels[ClaimUIDLabel] = "new-claim-uid" // even a forged lookup label cannot change retained UID + session := testSession("session-uid") + c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(session).WithObjects(claim, allocation, session).Build() + r := &SessionReconciler{Client: c} + req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "default", Name: "access"}} + _, _ = r.Reconcile(context.Background(), req) + _, _ = r.Reconcile(context.Background(), req) + var got fleetv1alpha1.MachineManagementSession + if err := c.Get(context.Background(), req.NamespacedName, &got); err != nil { + t.Fatal(err) + } + if len(got.Status.Conditions) == 0 || got.Status.Conditions[0].Reason != "AllocationChanged" { + t.Fatalf("conditions %+v", got.Status.Conditions) + } +} + +func testSession(uid types.UID) *fleetv1alpha1.MachineManagementSession { + return &fleetv1alpha1.MachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{Name: "access", Namespace: "default", UID: uid, Annotations: map[string]string{PrincipalAnnotation: "alice@example.test"}}, Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineClaimRef: fleetv1alpha1.LocalObjectReference{Name: "db-01"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", TTL: metav1.Duration{Duration: 15 * time.Minute}}} +} + +func testAllocation(claimUID types.UID) *fleetv1alpha1.MachineAllocationBinding { + return &fleetv1alpha1.MachineAllocationBinding{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineAllocationBinding"}, ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: SystemNamespace, Labels: map[string]string{ClaimUIDLabel: string(claimUID)}}, Spec: fleetv1alpha1.MachineAllocationBindingSpec{ConsumerProjectUID: "consumer-project", ProviderProjectUID: "provider-project", ClaimNamespace: "default", ClaimName: "db-01", ClaimUID: claimUID, MachineName: "machine-a", MachineUID: "machine-uid", BindingID: "binding-a", BindingEpoch: 7, LocationUID: "location-uid", LocationRevision: "location-r1", BareMetalMachineUID: "bmm-uid", AccessProfileRevision: "provisioning-r1", AdapterRoute: "sushy-libvirt", BMCSystemID: "vm-allocated", Active: true}} +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go new file mode 100644 index 00000000..9e34a815 --- /dev/null +++ b/internal/gateway/gateway.go @@ -0,0 +1,371 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gateway + +import ( + "bufio" + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/pem" + "errors" + "math/big" + "net" + "net/http" + "os" + "path/filepath" + "sync" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + "go.datum.net/fleet/internal/journal" + fleetmetrics "go.datum.net/fleet/internal/metrics" + "go.datum.net/fleet/internal/protocol" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/relay" +) + +const ( + HeaderTimestamp = "X-Datum-Fleet-Timestamp" + HeaderNonce = "X-Datum-Fleet-Nonce" + HeaderSignature = "X-Datum-Fleet-Signature" + HeaderSession = "X-Datum-Fleet-Session" + HeaderAudience = "X-Datum-Fleet-Audience" +) + +type Config struct { + RelayAddress string + RelayPublicURL string + RelayGatewayToken string + Audience string + AdapterRoute string + BMCBaseURL string + BMCUsername string + BMCPassword string + JournalDir string + StateDir string + DropResetResponseOnce bool +} + +type Reconciler struct { + client.Client + Config Config + mu sync.Mutex + active map[client.ObjectKey]*activeSession +} + +type activeSession struct { + cancel context.CancelFunc + mu sync.RWMutex + spec fleetv1alpha1.ProjectedMachineManagementSessionSpec +} + +func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + var p fleetv1alpha1.ProjectedMachineManagementSession + if err := r.Get(ctx, req.NamespacedName, &p); err != nil { + if apierrors.IsNotFound(err) { + r.stop(req.NamespacedName) + return ctrl.Result{}, nil + } + return ctrl.Result{}, err + } + now := time.Now() + if !p.DeletionTimestamp.IsZero() || now.After(p.Spec.ExpiresAt.Time) { + r.stop(req.NamespacedName) + return ctrl.Result{}, nil + } + if p.Status.ConnectedAt == nil && now.After(p.Spec.ConnectBefore.Time) { + r.stop(req.NamespacedName) + setCondition(&p, metav1.ConditionFalse, "ConnectWindowExpired", "No client connected before the admitted connection deadline.") + return ctrl.Result{}, r.Status().Update(ctx, &p) + } + if p.Spec.AdapterRoute != r.Config.AdapterRoute { + setCondition(&p, metav1.ConditionFalse, "AdapterRouteRejected", "The projected adapter route is not served by this gateway.") + return ctrl.Result{}, r.Status().Update(ctx, &p) + } + r.mu.Lock() + if r.active == nil { + r.active = map[client.ObjectKey]*activeSession{} + } + a := r.active[req.NamespacedName] + if a == nil { + runCtx, cancel := context.WithCancel(context.Background()) + a = &activeSession{cancel: cancel, spec: p.Spec} + r.active[req.NamespacedName] = a + go r.run(runCtx, req.NamespacedName, a) + } else { + a.mu.Lock() + if !sameBinding(a.spec, p.Spec) { + a.mu.Unlock() + r.mu.Unlock() + r.stop(req.NamespacedName) + setCondition(&p, metav1.ConditionFalse, "SessionInputsChanged", "Projected binding inputs changed after the gateway accepted them.") + return ctrl.Result{}, r.Status().Update(ctx, &p) + } + a.spec.AuthorityFreshUntil = p.Spec.AuthorityFreshUntil + a.mu.Unlock() + } + r.mu.Unlock() + wake := time.Until(p.Spec.ExpiresAt.Time) + if p.Status.ConnectedAt == nil && time.Until(p.Spec.ConnectBefore.Time) < wake { + wake = time.Until(p.Spec.ConnectBefore.Time) + } + return ctrl.Result{RequeueAfter: wake}, nil +} + +func (r *Reconciler) run(ctx context.Context, key client.ObjectKey, a *activeSession) { + fleetmetrics.ActiveSessions.Inc() + defer fleetmetrics.ActiveSessions.Dec() + cert, der, fingerprint, err := loadOrCreateCertificate(r.Config.StateDir, key.Name) + if err != nil { + r.failStatus(key, "GatewayCertificateError", "The location gateway could not create its session certificate.") + return + } + store, err := journal.Open(filepath.Join(r.Config.JournalDir, "operations")) + if err != nil { + r.failStatus(key, "JournalUnavailable", "The durable operation journal is unavailable.") + return + } + routeID := randomHex(24) + conn, err := r.dialRelay(ctx, routeID) + if err != nil { + r.failStatus(key, "RelayUnavailable", "The location gateway could not establish its outbound relay route.") + return + } + defer conn.Close() + go func() { + <-ctx.Done() + _ = conn.Close() + }() + if err := r.readyStatus(key, routeID, fingerprint); err != nil { + return + } + line, err := bufio.NewReader(conn).ReadString('\n') + if err != nil || line != "OK\n" { + r.failStatus(key, "RelayDisconnected", "The outbound relay route ended before a client connected.") + return + } + r.connectedStatus(key) + a.mu.RLock() + spec := a.spec + a.mu.RUnlock() + adapter := &redfish.SushyAdapter{BaseURL: r.Config.BMCBaseURL, SystemID: spec.BMCSystemID, Username: r.Config.BMCUsername, Password: r.Config.BMCPassword, DropResetResponseOnce: r.Config.DropResetResponseOnce} + h := &redfish.Handler{Adapter: adapter, Journal: store, CurrentAuthority: func() redfish.Authority { + a.mu.RLock() + defer a.mu.RUnlock() + s := a.spec + return redfish.Authority{SessionUID: string(s.SessionUID), SessionCorrelationID: s.SessionCorrelationID, OperationCorrelationID: s.OperationCorrelationID, ClaimUID: string(s.ClaimUID), MachineUID: string(s.MachineUID), BindingID: s.BindingID, BindingEpoch: s.BindingEpoch, AdapterRoute: s.AdapterRoute, OperationEpoch: 1, ExpiresAt: s.ExpiresAt.Time, FreshUntil: s.AuthorityFreshUntil.Time} + }} + protected := r.proofMiddleware(a, h) + tlsConn := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13, NextProtos: []string{"datum-fleet-redfish/1"}}) + // The relay admits one connector for the session, so an HTTP idle timeout + // would permanently strand a valid session during a long PXE boot. Expiry, + // revocation, and projection teardown bound the stream lifetime instead. + server := &http.Server{Handler: protected, ReadHeaderTimeout: 10 * time.Second, MaxHeaderBytes: 16 << 10} + _ = server.Serve(newOneConnListener(tlsConn)) + _ = der // DER is retained only to make certificate pin derivation explicit. + r.endedStatus(key, "Disconnected", "The client connection ended.") +} + +func (r *Reconciler) dialRelay(ctx context.Context, routeID string) (net.Conn, error) { + d := net.Dialer{Timeout: 10 * time.Second} + c, err := d.DialContext(ctx, "tcp", r.Config.RelayAddress) + if err != nil { + return nil, err + } + if err := relay.Register(c, routeID, r.Config.RelayGatewayToken); err != nil { + _ = c.Close() + return nil, err + } + return c, nil +} + +func (r *Reconciler) proofMiddleware(a *activeSession, next http.Handler) http.Handler { + used := map[string]bool{} + var mu sync.Mutex + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + a.mu.RLock() + spec := a.spec + a.mu.RUnlock() + if req.Header.Get(HeaderSession) != string(spec.SessionUID) || req.Header.Get(HeaderAudience) != r.Config.Audience { + http.Error(w, "session proof target mismatch", http.StatusUnauthorized) + return + } + proof := protocol.Proof{Timestamp: req.Header.Get(HeaderTimestamp), Nonce: req.Header.Get(HeaderNonce), Signature: req.Header.Get(HeaderSignature)} + err := protocol.Verify(spec.ClientPublicKey, string(spec.SessionUID), r.Config.Audience, proof, time.Now(), func(n string) bool { + mu.Lock() + defer mu.Unlock() + if used[n] { + return true + } + used[n] = true + return false + }) + if err != nil { + http.Error(w, "invalid session key proof", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, req) + }) +} + +func (r *Reconciler) readyStatus(key client.ObjectKey, route, fingerprint string) error { + return r.updateStatus(key, func(p *fleetv1alpha1.ProjectedMachineManagementSession) { + p.Status.Connection = &fleetv1alpha1.SessionConnection{RelayURL: r.Config.RelayPublicURL, RouteID: route, GatewayAudience: r.Config.Audience, GatewayCertSHA256: fingerprint, ProtocolVersion: protocol.Version} + setCondition(p, metav1.ConditionTrue, "SessionReady", "The outbound location route is ready for one connector.") + }) +} +func (r *Reconciler) connectedStatus(key client.ObjectKey) { + _ = r.updateStatus(key, func(p *fleetv1alpha1.ProjectedMachineManagementSession) { + now := metav1.Now() + p.Status.ConnectedAt = &now + setCondition(p, metav1.ConditionTrue, "Connected", "The client proved possession of the admitted session key.") + }) +} +func (r *Reconciler) endedStatus(key client.ObjectKey, reason, message string) { + _ = r.updateStatus(key, func(p *fleetv1alpha1.ProjectedMachineManagementSession) { + now := metav1.Now() + p.Status.EndedAt = &now + setCondition(p, metav1.ConditionFalse, reason, message) + }) +} +func (r *Reconciler) failStatus(key client.ObjectKey, reason, message string) { + _ = r.updateStatus(key, func(p *fleetv1alpha1.ProjectedMachineManagementSession) { + setCondition(p, metav1.ConditionFalse, reason, message) + }) +} +func (r *Reconciler) updateStatus(key client.ObjectKey, mutate func(*fleetv1alpha1.ProjectedMachineManagementSession)) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var p fleetv1alpha1.ProjectedMachineManagementSession + if err := r.Get(ctx, key, &p); err != nil { + return err + } + mutate(&p) + return r.Status().Update(ctx, &p) +} +func (r *Reconciler) stop(key client.ObjectKey) { + r.mu.Lock() + defer r.mu.Unlock() + if a := r.active[key]; a != nil { + a.cancel() + delete(r.active, key) + } +} +func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { + r.Client = mgr.GetClient() + return ctrl.NewControllerManagedBy(mgr).For(&fleetv1alpha1.ProjectedMachineManagementSession{}).Complete(r) +} + +func sameBinding(a, b fleetv1alpha1.ProjectedMachineManagementSessionSpec) bool { + a.AuthorityFreshUntil = metav1.Time{} + b.AuthorityFreshUntil = metav1.Time{} + return a.SessionUID == b.SessionUID && a.ClaimUID == b.ClaimUID && a.MachineUID == b.MachineUID && a.BindingID == b.BindingID && a.BindingEpoch == b.BindingEpoch && a.LocationUID == b.LocationUID && a.LocationRevision == b.LocationRevision && a.BareMetalMachineUID == b.BareMetalMachineUID && a.AccessProfileRevision == b.AccessProfileRevision && a.ClientPublicKey == b.ClientPublicKey && a.ConnectBefore.Equal(&b.ConnectBefore) && a.ExpiresAt.Equal(&b.ExpiresAt) && a.AdapterRoute == b.AdapterRoute && a.BMCSystemID == b.BMCSystemID +} +func setCondition(p *fleetv1alpha1.ProjectedMachineManagementSession, status metav1.ConditionStatus, reason, message string) { + apimeta.SetStatusCondition(&p.Status.Conditions, metav1.Condition{Type: fleetv1alpha1.ConditionReady, Status: status, Reason: reason, Message: message, ObservedGeneration: p.Generation, LastTransitionTime: metav1.Now()}) +} + +func loadOrCreateCertificate(dir, name string) (tls.Certificate, []byte, string, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return tls.Certificate{}, nil, "", err + } + certPath, keyPath := filepath.Join(dir, name+".crt"), filepath.Join(dir, name+".key") + if certPEM, err := os.ReadFile(certPath); err == nil { + keyPEM, e := os.ReadFile(keyPath) + if e == nil { + cert, e := tls.X509KeyPair(certPEM, keyPEM) + if e == nil && len(cert.Certificate) > 0 { + sum := sha256.Sum256(cert.Certificate[0]) + return cert, cert.Certificate[0], hex.EncodeToString(sum[:]), nil + } + } + } + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return tls.Certificate{}, nil, "", err + } + serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + now := time.Now() + tmpl := x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "fleet-gateway"}, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(24 * time.Hour), DNSNames: []string{"fleet-gateway"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} + der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, pub, priv) + if err != nil { + return tls.Certificate{}, nil, "", err + } + pkcs8, err := x509.MarshalPKCS8PrivateKey(priv) + if err != nil { + return tls.Certificate{}, nil, "", err + } + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}) + if err := os.WriteFile(certPath, certPEM, 0o600); err != nil { + return tls.Certificate{}, nil, "", err + } + if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil { + return tls.Certificate{}, nil, "", err + } + cert, err := tls.X509KeyPair(certPEM, keyPEM) + sum := sha256.Sum256(der) + return cert, der, hex.EncodeToString(sum[:]), err +} +func randomHex(n int) string { b := make([]byte, n); _, _ = rand.Read(b); return hex.EncodeToString(b) } + +type oneConnListener struct { + mu sync.Mutex + conn net.Conn + accepted bool + done chan struct{} + once sync.Once +} + +func newOneConnListener(conn net.Conn) *oneConnListener { + l := &oneConnListener{done: make(chan struct{})} + l.conn = ¬ifyConn{Conn: conn, closed: func() { l.once.Do(func() { close(l.done) }) }} + return l +} + +func (l *oneConnListener) Accept() (net.Conn, error) { + l.mu.Lock() + if !l.accepted { + l.accepted = true + conn := l.conn + l.mu.Unlock() + return conn, nil + } + l.mu.Unlock() + <-l.done + return nil, errors.New("single connection consumed") +} +func (l *oneConnListener) Close() error { + l.once.Do(func() { close(l.done) }) + return l.conn.Close() +} +func (l *oneConnListener) Addr() net.Addr { return dummyAddr("relay") } + +type dummyAddr string + +func (d dummyAddr) Network() string { return "relay" } +func (d dummyAddr) String() string { return string(d) } + +type notifyConn struct { + net.Conn + once sync.Once + closed func() +} + +func (c *notifyConn) Close() error { + err := c.Conn.Close() + c.once.Do(c.closed) + return err +} diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go new file mode 100644 index 00000000..cda87209 --- /dev/null +++ b/internal/gateway/gateway_test.go @@ -0,0 +1,34 @@ +package gateway + +import ( + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" +) + +func TestBindingInputsCannotChangeAfterGatewayAcceptance(t *testing.T) { + a := fleetv1alpha1.ProjectedMachineManagementSessionSpec{ + SessionUID: "session", ClaimUID: "claim", MachineUID: "machine", + BindingID: "binding", BindingEpoch: 1, LocationUID: "location", LocationRevision: "r1", + BareMetalMachineUID: "bmm", AccessProfileRevision: "profile", ClientPublicKey: "key", + ConnectBefore: metav1.NewTime(time.Unix(100, 0)), ExpiresAt: metav1.NewTime(time.Unix(200, 0)), + AuthorityFreshUntil: metav1.NewTime(time.Unix(110, 0)), AdapterRoute: "adapter", BMCSystemID: "physical", + } + b := a + b.AuthorityFreshUntil = metav1.NewTime(time.Unix(120, 0)) + if !sameBinding(a, b) { + t.Fatal("authority freshness was not refreshable") + } + b.AdapterRoute = "changed" + if sameBinding(a, b) { + t.Fatal("changed adapter route was accepted") + } + b = a + b.BindingEpoch++ + if sameBinding(a, b) { + t.Fatal("changed binding epoch was accepted") + } +} diff --git a/internal/journal/journal.go b/internal/journal/journal.go new file mode 100644 index 00000000..bcd7f1b3 --- /dev/null +++ b/internal/journal/journal.go @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package journal durably records admitted hardware mutations before effects. +package journal + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +type Outcome string + +const ( + Pending Outcome = "Pending" + Succeeded Outcome = "Succeeded" + Failed Outcome = "Failed" + Unknown Outcome = "Unknown" +) + +type Operation struct { + ID string `json:"id"` + SessionUID string `json:"sessionUID"` + SessionCorrelationID string `json:"sessionCorrelationID"` + OperationCorrelationID string `json:"operationCorrelationID"` + ClaimUID string `json:"claimUID"` + MachineUID string `json:"machineUID"` + BindingID string `json:"bindingID"` + BindingEpoch int64 `json:"bindingEpoch"` + Method string `json:"method"` + VirtualTarget string `json:"virtualTarget"` + AcceptedBody json.RawMessage `json:"acceptedBody"` + PhysicalTarget string `json:"physicalTarget"` + IdempotencyIdentity string `json:"idempotencyIdentity"` + OperationEpoch int64 `json:"operationEpoch"` + ConflictPrecondition string `json:"conflictPrecondition"` + AdapterRoute string `json:"adapterRoute"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + Outcome Outcome `json:"outcome"` + Evidence string `json:"evidence,omitempty"` + HTTPStatus int `json:"httpStatus,omitempty"` +} + +func Identity(sessionUID, method, target string, body []byte) string { + h := sha256.New() + _, _ = fmt.Fprintf(h, "%s\n%s\n%s\n", sessionUID, method, target) + _, _ = h.Write(body) + return hex.EncodeToString(h.Sum(nil)) +} + +type Store struct { + dir string + mu sync.Mutex +} + +var machineLocks = struct { + sync.Mutex + locks map[string]*sync.Mutex +}{locks: map[string]*sync.Mutex{}} + +func Open(dir string) (*Store, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + return &Store{dir: dir}, nil +} + +func (s *Store) MachineLock(machineUID string) func() { + machineLocks.Lock() + l := machineLocks.locks[machineUID] + if l == nil { + l = &sync.Mutex{} + machineLocks.locks[machineUID] = l + } + machineLocks.Unlock() + l.Lock() + return l.Unlock +} + +func (s *Store) Admit(op Operation) (Operation, bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + if op.ID == "" { + return Operation{}, false, errors.New("operation ID is required") + } + if existing, err := s.read(op.ID); err == nil { + return existing, false, nil + } else if !errors.Is(err, os.ErrNotExist) { + return Operation{}, false, err + } + now := time.Now().UTC() + op.CreatedAt, op.UpdatedAt, op.Outcome = now, now, Pending + if err := s.write(op); err != nil { + return Operation{}, false, err + } + return op, true, nil +} + +func (s *Store) Get(id string) (Operation, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.read(id) +} + +func (s *Store) List() ([]Operation, error) { + s.mu.Lock() + defer s.mu.Unlock() + entries, err := os.ReadDir(s.dir) + if err != nil { + return nil, err + } + operations := make([]Operation, 0, len(entries)) + for _, entry := range entries { + if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" { + continue + } + id := strings.TrimSuffix(entry.Name(), ".json") + op, err := s.read(id) + if err != nil { + return nil, err + } + operations = append(operations, op) + } + return operations, nil +} + +func (s *Store) Finish(id string, outcome Outcome, status int, evidence string) (Operation, error) { + s.mu.Lock() + defer s.mu.Unlock() + op, err := s.read(id) + if err != nil { + return Operation{}, err + } + op.Outcome, op.HTTPStatus, op.Evidence, op.UpdatedAt = outcome, status, evidence, time.Now().UTC() + if err := s.write(op); err != nil { + return Operation{}, err + } + return op, nil +} + +func (s *Store) read(id string) (Operation, error) { + b, err := os.ReadFile(s.path(id)) + if err != nil { + return Operation{}, err + } + var op Operation + if err := json.Unmarshal(b, &op); err != nil { + return Operation{}, err + } + return op, nil +} + +func (s *Store) write(op Operation) error { + b, err := json.MarshalIndent(op, "", " ") + if err != nil { + return err + } + tmp, err := os.CreateTemp(s.dir, ".operation-*.tmp") + if err != nil { + return err + } + name := tmp.Name() + defer os.Remove(name) + if err := tmp.Chmod(0o600); err != nil { + _ = tmp.Close() + return err + } + if _, err := tmp.Write(b); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Rename(name, s.path(op.ID)); err != nil { + return err + } + d, err := os.Open(s.dir) + if err != nil { + return err + } + defer d.Close() + return d.Sync() +} + +func (s *Store) path(id string) string { + return filepath.Join(s.dir, id+".json") +} diff --git a/internal/journal/journal_test.go b/internal/journal/journal_test.go new file mode 100644 index 00000000..35f20a98 --- /dev/null +++ b/internal/journal/journal_test.go @@ -0,0 +1,29 @@ +package journal + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestAdmissionIsDurableAndDeduplicated(t *testing.T) { + s, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + op := Operation{ID: "op-1", MachineUID: "machine-1", Method: "POST", VirtualTarget: "/reset", AcceptedBody: json.RawMessage(`{"ResetType":"On"}`)} + if _, fresh, err := s.Admit(op); err != nil || !fresh { + t.Fatalf("admit fresh=%v err=%v", fresh, err) + } + if _, fresh, err := s.Admit(op); err != nil || fresh { + t.Fatalf("duplicate fresh=%v err=%v", fresh, err) + } + info, err := os.Stat(filepath.Join(s.dir, "op-1.json")) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("mode %o", info.Mode().Perm()) + } +} diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go new file mode 100644 index 00000000..e48c5f30 --- /dev/null +++ b/internal/metrics/metrics.go @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 + +package metrics + +import ( + "github.com/prometheus/client_golang/prometheus" + controllermetrics "sigs.k8s.io/controller-runtime/pkg/metrics" +) + +var ( + SessionAdmissions = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "fleet_machine_management_session_admissions_total", Help: "Machine-management session admission decisions."}, []string{"outcome"}) + ActiveSessions = prometheus.NewGauge(prometheus.GaugeOpts{Name: "fleet_machine_management_active_sessions", Help: "Active location gateway sessions."}) + RevocationLatency = prometheus.NewHistogram(prometheus.HistogramOpts{Name: "fleet_machine_management_revocation_latency_seconds", Help: "Time from public deletion to location teardown outcome.", Buckets: prometheus.DefBuckets}) + BMCReachability = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "fleet_machine_management_bmc_requests_total", Help: "BMC adapter request outcomes."}, []string{"outcome"}) + Operations = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "fleet_machine_management_operations_total", Help: "Durably journaled mutation outcomes."}, []string{"outcome"}) + UnknownOperations = prometheus.NewGauge(prometheus.GaugeOpts{Name: "fleet_machine_management_unknown_operations", Help: "Operations with an unknown physical outcome."}) +) + +func init() { + controllermetrics.Registry.MustRegister(SessionAdmissions, ActiveSessions, RevocationLatency, BMCReachability, Operations, UnknownOperations) +} diff --git a/internal/protocol/proof.go b/internal/protocol/proof.go new file mode 100644 index 00000000..3d12441d --- /dev/null +++ b/internal/protocol/proof.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package protocol defines the Fleet-specific client proof. It is deliberately +// independent of Compute's provisional internal protocol. +package protocol + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "strconv" + "strings" + "time" +) + +const ( + Version = "redfish-v1alpha1" + Domain = "datum-fleet-machine-management-v1" + ClockSkew = 30 * time.Second +) + +type Proof struct { + Timestamp string + Nonce string + Signature string +} + +func PublicKey(key ed25519.PrivateKey) string { + return hex.EncodeToString(key.Public().(ed25519.PublicKey)) +} + +func Sign(key ed25519.PrivateKey, sessionUID, audience string, now time.Time) (Proof, error) { + nonceBytes := make([]byte, 24) + if _, err := rand.Read(nonceBytes); err != nil { + return Proof{}, err + } + p := Proof{Timestamp: strconv.FormatInt(now.Unix(), 10), Nonce: base64.RawURLEncoding.EncodeToString(nonceBytes)} + p.Signature = base64.StdEncoding.EncodeToString(ed25519.Sign(key, message(sessionUID, audience, p.Timestamp, p.Nonce))) + return p, nil +} + +func Verify(publicKey, sessionUID, audience string, p Proof, now time.Time, usedNonce func(string) bool) error { + pub, err := hex.DecodeString(publicKey) + if err != nil || len(pub) != ed25519.PublicKeySize { + return errors.New("invalid session client public key") + } + ts, err := strconv.ParseInt(p.Timestamp, 10, 64) + if err != nil { + return errors.New("missing or malformed proof timestamp") + } + d := now.Sub(time.Unix(ts, 0)) + if d > ClockSkew || d < -ClockSkew { + return fmt.Errorf("proof timestamp outside %s clock skew", ClockSkew) + } + if p.Nonce == "" { + return errors.New("missing proof nonce") + } + sig, err := base64.StdEncoding.DecodeString(p.Signature) + if err != nil { + return errors.New("malformed proof signature") + } + if !ed25519.Verify(ed25519.PublicKey(pub), message(sessionUID, audience, p.Timestamp, p.Nonce), sig) { + return errors.New("proof signature does not match session key and gateway audience") + } + if usedNonce != nil && usedNonce(p.Nonce) { + return errors.New("proof nonce was already consumed") + } + return nil +} + +func message(sessionUID, audience, timestamp, nonce string) []byte { + return []byte(strings.Join([]string{Domain, Version, sessionUID, audience, timestamp, nonce}, "\n")) +} diff --git a/internal/protocol/proof_test.go b/internal/protocol/proof_test.go new file mode 100644 index 00000000..0dab06d2 --- /dev/null +++ b/internal/protocol/proof_test.go @@ -0,0 +1,37 @@ +package protocol + +import ( + "crypto/ed25519" + "crypto/rand" + "testing" + "time" +) + +func TestProofBindingAndReplay(t *testing.T) { + _, key, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + now := time.Unix(1000, 0) + p, err := Sign(key, "session-a", "gateway-a", now) + if err != nil { + t.Fatal(err) + } + used := false + consume := func(string) bool { old := used; used = true; return old } + if err := Verify(PublicKey(key), "session-a", "gateway-a", p, now, consume); err != nil { + t.Fatal(err) + } + if err := Verify(PublicKey(key), "session-a", "gateway-a", p, now, consume); err == nil { + t.Fatal("replay accepted") + } + if err := Verify(PublicKey(key), "session-a", "gateway-b", p, now, nil); err == nil { + t.Fatal("changed audience accepted") + } + if err := Verify(PublicKey(key), "session-b", "gateway-a", p, now, nil); err == nil { + t.Fatal("changed session accepted") + } + if err := Verify(PublicKey(key), "session-a", "gateway-a", p, now.Add(ClockSkew+time.Second), nil); err == nil { + t.Fatal("expired signature accepted") + } +} diff --git a/internal/redfish/adapter.go b/internal/redfish/adapter.go new file mode 100644 index 00000000..b59b2800 --- /dev/null +++ b/internal/redfish/adapter.go @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: Apache-2.0 + +package redfish + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" +) + +var ErrResponseLost = errors.New("BMC may have applied the effect but its response was lost") + +type System struct { + PowerState string + BootTarget string +} + +type Adapter interface { + Observe(context.Context) (System, error) + SetOneTimeBoot(context.Context, string) error + Reset(context.Context, string) error + PhysicalTarget() string +} + +// SushyAdapter calls exactly one internally selected sushy-emulator system. +// Customer URLs, Host headers, links, and IDs never enter these requests. +type SushyAdapter struct { + BaseURL string + SystemID string + Username string + Password string + Client *http.Client + DropResetResponseOnce bool + dropped bool +} + +func (a *SushyAdapter) Observe(ctx context.Context) (System, error) { + var body struct { + PowerState string `json:"PowerState"` + Boot struct { + Target string `json:"BootSourceOverrideTarget"` + } `json:"Boot"` + } + if err := a.doJSON(ctx, http.MethodGet, a.systemPath(), nil, &body); err != nil { + return System{}, err + } + return System{PowerState: body.PowerState, BootTarget: physicalToVirtualBoot(body.Boot.Target)}, nil +} + +func (a *SushyAdapter) SetOneTimeBoot(ctx context.Context, target string) error { + physical, ok := map[string]string{"Pxe": "Pxe", "Hdd": "Hdd"}[target] + if !ok { + return fmt.Errorf("unsupported boot target %q", target) + } + body := map[string]any{"Boot": map[string]any{"BootSourceOverrideEnabled": "Once", "BootSourceOverrideTarget": physical}} + return a.doJSON(ctx, http.MethodPatch, a.systemPath(), body, nil) +} + +func (a *SushyAdapter) Reset(ctx context.Context, resetType string) error { + if !supportedReset(resetType) { + return fmt.Errorf("unsupported ResetType %q", resetType) + } + body := map[string]string{"ResetType": resetType} + err := a.doJSON(ctx, http.MethodPost, a.systemPath()+"/Actions/ComputerSystem.Reset", body, nil) + if err == nil && a.DropResetResponseOnce && !a.dropped { + a.dropped = true + return ErrResponseLost + } + return err +} + +func (a *SushyAdapter) PhysicalTarget() string { return "bmc-system:" + a.SystemID } + +func (a *SushyAdapter) systemPath() string { + return "/redfish/v1/Systems/" + url.PathEscape(a.SystemID) +} + +func (a *SushyAdapter) doJSON(ctx context.Context, method, path string, in, out any) error { + var body io.Reader + if in != nil { + b, err := json.Marshal(in) + if err != nil { + return err + } + body = bytes.NewReader(b) + } + req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(a.BaseURL, "/")+path, body) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + if in != nil { + req.Header.Set("Content-Type", "application/json") + } + req.SetBasicAuth(a.Username, a.Password) + client := a.Client + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("BMC unavailable: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("BMC rejected the qualified operation with status %d", resp.StatusCode) + } + if out != nil { + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out); err != nil { + return fmt.Errorf("invalid BMC response: %w", err) + } + } + return nil +} + +func physicalToVirtualBoot(v string) string { + if v == "Pxe" { + return "Pxe" + } + return "Hdd" +} +func supportedReset(v string) bool { + return v == "On" || v == "ForceOff" || v == "GracefulShutdown" || v == "GracefulRestart" || v == "ForceRestart" +} diff --git a/internal/redfish/handler.go b/internal/redfish/handler.go new file mode 100644 index 00000000..6321e9c4 --- /dev/null +++ b/internal/redfish/handler.go @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: Apache-2.0 + +package redfish + +import ( + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "go.datum.net/fleet/internal/journal" + fleetmetrics "go.datum.net/fleet/internal/metrics" +) + +const SystemID = "allocated" + +type Authority struct { + SessionUID string + SessionCorrelationID string + OperationCorrelationID string + ClaimUID string + MachineUID string + BindingID string + BindingEpoch int64 + AdapterRoute string + OperationEpoch int64 + ExpiresAt time.Time + FreshUntil time.Time +} + +type Handler struct { + Adapter Adapter + Journal *journal.Store + Authority Authority + CurrentAuthority func() Authority + Now func() time.Time + mu sync.Mutex + tokens map[string]bool +} + +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + setODataHeaders(w) + if err := h.checkRequest(r); err != nil { + writeError(w, http.StatusBadRequest, "Base.1.18.PropertyValueFormatError", err.Error()) + return + } + authority := h.authority() + if h.now().After(authority.ExpiresAt) { + writeError(w, http.StatusForbidden, "Fleet.1.0.SessionExpired", "The machine-management session has expired.") + return + } + if h.now().After(authority.FreshUntil) { + writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.AuthorityStale", "Allocation authority is stale; the gateway has failed closed.") + return + } + switch { + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/": + h.serviceRoot(w) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/SessionService": + h.sessionService(w) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/SessionService/Sessions": + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#SessionCollection.SessionCollection", "@odata.id": r.URL.Path, "Name": "Sessions", "Members": []any{}, "Members@odata.count": 0}) + case r.Method == http.MethodPost && r.URL.Path == "/redfish/v1/SessionService/Sessions": + h.login(w, r) + case r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, "/redfish/v1/SessionService/Sessions/"): + h.logout(w, r) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/Systems": + h.systems(w) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/Systems/"+SystemID: + h.system(w, r) + case r.Method == http.MethodPatch && r.URL.Path == "/redfish/v1/Systems/"+SystemID: + h.patchSystem(w, r) + case r.Method == http.MethodPost && r.URL.Path == "/redfish/v1/Systems/"+SystemID+"/Actions/ComputerSystem.Reset": + h.reset(w, r) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/TaskService": + h.taskService(w) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/TaskService/Tasks": + h.tasks(w) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/redfish/v1/TaskService/Tasks/"): + h.task(w, strings.TrimPrefix(r.URL.Path, "/redfish/v1/TaskService/Tasks/")) + default: + writeError(w, http.StatusNotFound, "Base.1.18.ResourceMissingAtURI", "The resource is outside the Fleet Provisioning profile.") + } +} + +func (h *Handler) checkRequest(r *http.Request) error { + if r.URL.RawPath != "" { + if u, err := url.PathUnescape(r.URL.RawPath); err != nil || u != r.URL.Path { + return errors.New("encoded or ambiguous paths are not accepted") + } + } + if strings.Contains(r.URL.Path, "..") || !strings.HasPrefix(r.URL.Path, "/redfish/v1") { + return errors.New("target is outside the virtual Redfish service") + } + if r.URL.IsAbs() || r.RequestURI == "*" { + return errors.New("absolute and arbitrary targets are not accepted") + } + host := r.Host + if i := strings.LastIndex(host, ":"); i >= 0 { + host = host[:i] + } + host = strings.Trim(host, "[]") + if host != "" && host != "127.0.0.1" && host != "localhost" && host != "fleet-gateway" { + return errors.New("Host routing is not accepted") + } + return nil +} + +func (h *Handler) serviceRoot(w http.ResponseWriter) { + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ServiceRoot.v1_15_0.ServiceRoot", "@odata.id": "/redfish/v1/", "Id": "RootService", "Name": "Fleet Virtual Redfish Service", "RedfishVersion": "1.18.0", "UUID": h.authority().SessionUID, "Systems": odata("/redfish/v1/Systems"), "SessionService": odata("/redfish/v1/SessionService"), "TaskService": odata("/redfish/v1/TaskService")}) +} +func (h *Handler) sessionService(w http.ResponseWriter) { + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#SessionService.v1_2_0.SessionService", "@odata.id": "/redfish/v1/SessionService", "Id": "SessionService", "Name": "Session Service", "ServiceEnabled": true, "SessionTimeout": 900, "Sessions": odata("/redfish/v1/SessionService/Sessions")}) +} + +func (h *Handler) login(w http.ResponseWriter, r *http.Request) { + var in struct { + UserName string `json:"UserName"` + Password string `json:"Password"` + } + if err := decodeExact(r, &in); err != nil || in.UserName == "" || in.Password == "" { + writeError(w, http.StatusBadRequest, "Base.1.18.MalformedJSON", "UserName and Password are required.") + return + } + b := make([]byte, 24) + _, _ = rand.Read(b) + token := base64.RawURLEncoding.EncodeToString(b) + h.mu.Lock() + if h.tokens == nil { + h.tokens = map[string]bool{} + } + h.tokens[token] = true + h.mu.Unlock() + loc := "/redfish/v1/SessionService/Sessions/local" + w.Header().Set("X-Auth-Token", token) + w.Header().Set("Location", loc) + writeJSON(w, http.StatusCreated, map[string]any{"@odata.type": "#Session.v1_7_0.Session", "@odata.id": loc, "Id": "local", "Name": "Fleet session-local login", "UserName": in.UserName}) +} +func (h *Handler) logout(w http.ResponseWriter, r *http.Request) { + h.mu.Lock() + delete(h.tokens, r.Header.Get("X-Auth-Token")) + h.mu.Unlock() + w.WriteHeader(http.StatusNoContent) +} + +func (h *Handler) systems(w http.ResponseWriter) { + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ComputerSystemCollection.ComputerSystemCollection", "@odata.id": "/redfish/v1/Systems", "Name": "Computer System Collection", "Members": []any{odata("/redfish/v1/Systems/" + SystemID)}, "Members@odata.count": 1}) +} + +func (h *Handler) system(w http.ResponseWriter, r *http.Request) { + s, err := h.Adapter.Observe(r.Context()) + if err != nil { + fleetmetrics.BMCReachability.WithLabelValues("unreachable").Inc() + writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.BMCUnavailable", "The allocated system management endpoint is unavailable.") + return + } + fleetmetrics.BMCReachability.WithLabelValues("reachable").Inc() + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ComputerSystem.v1_20_0.ComputerSystem", "@odata.id": r.URL.Path, "Id": SystemID, "Name": "Allocated Machine", "SystemType": "Physical", "PowerState": s.PowerState, "Status": map[string]string{"State": "Enabled", "Health": "OK"}, "Boot": map[string]any{"BootSourceOverrideEnabled": "Once", "BootSourceOverrideTarget": s.BootTarget, "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd"}}, "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": r.URL.Path + "/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff", "GracefulShutdown", "GracefulRestart", "ForceRestart"}}}}) +} + +func (h *Handler) patchSystem(w http.ResponseWriter, r *http.Request) { + raw, err := readBody(r) + if err != nil { + writeError(w, http.StatusBadRequest, "Base.1.18.MalformedJSON", err.Error()) + return + } + var in struct { + Boot *struct { + Enabled string `json:"BootSourceOverrideEnabled"` + Target string `json:"BootSourceOverrideTarget"` + } `json:"Boot"` + } + if err := json.Unmarshal(raw, &in); err != nil || in.Boot == nil { + writeError(w, http.StatusBadRequest, "Base.1.18.PropertyNotWritable", "Only Boot one-time override is writable.") + return + } + var generic map[string]any + _ = json.Unmarshal(raw, &generic) + boot, bootOK := generic["Boot"].(map[string]any) + if len(generic) != 1 || !bootOK || len(boot) != 2 || in.Boot.Enabled != "Once" || (in.Boot.Target != "Pxe" && in.Boot.Target != "Hdd") { + writeError(w, http.StatusBadRequest, "Base.1.18.PropertyValueNotInList", "Only one-time Pxe or Hdd boot selection is supported.") + return + } + h.mutate(w, r, raw, func() error { return h.Adapter.SetOneTimeBoot(r.Context(), in.Boot.Target) }) +} + +func (h *Handler) reset(w http.ResponseWriter, r *http.Request) { + raw, err := readBody(r) + if err != nil { + writeError(w, http.StatusBadRequest, "Base.1.18.MalformedJSON", err.Error()) + return + } + var in struct { + ResetType string `json:"ResetType"` + } + var generic map[string]any + if json.Unmarshal(raw, &in) != nil || json.Unmarshal(raw, &generic) != nil || len(generic) != 1 || !supportedReset(in.ResetType) { + writeError(w, http.StatusBadRequest, "Base.1.18.ActionParameterNotSupported", "ResetType is not supported by this profile.") + return + } + h.mutate(w, r, raw, func() error { return h.Adapter.Reset(r.Context(), in.ResetType) }) +} + +func (h *Handler) mutate(w http.ResponseWriter, r *http.Request, raw []byte, effect func() error) { + now := h.now() + authority := h.authority() + if now.After(authority.ExpiresAt) { + writeError(w, http.StatusForbidden, "Fleet.1.0.SessionExpired", "The machine-management session has expired.") + return + } + if now.After(authority.FreshUntil) { + writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.AuthorityStale", "Allocation authority is stale; the gateway has failed closed.") + return + } + id := journal.Identity(authority.SessionUID, r.Method, r.URL.Path, raw) + unlock := h.Journal.MachineLock(authority.MachineUID) + defer unlock() + op, fresh, err := h.Journal.Admit(journal.Operation{ID: id, SessionUID: authority.SessionUID, SessionCorrelationID: authority.SessionCorrelationID, OperationCorrelationID: authority.OperationCorrelationID, ClaimUID: authority.ClaimUID, MachineUID: authority.MachineUID, BindingID: authority.BindingID, BindingEpoch: authority.BindingEpoch, Method: r.Method, VirtualTarget: r.URL.Path, AcceptedBody: append([]byte(nil), raw...), PhysicalTarget: h.Adapter.PhysicalTarget(), IdempotencyIdentity: id, OperationEpoch: authority.OperationEpoch, ConflictPrecondition: fmt.Sprintf("binding=%s epoch=%d fresh-before=%s", authority.BindingID, authority.BindingEpoch, authority.FreshUntil.UTC().Format(time.RFC3339)), AdapterRoute: authority.AdapterRoute}) + if err != nil { + writeError(w, http.StatusInternalServerError, "Fleet.1.0.JournalUnavailable", "The mutation could not be durably admitted.") + return + } + if !fresh { + h.writeExistingTask(w, op) + return + } + if err := effect(); err != nil { + if errors.Is(err, ErrResponseLost) { + op, _ = h.Journal.Finish(id, journal.Unknown, 0, "effect submitted; response lost; recover before retry") + fleetmetrics.Operations.WithLabelValues("unknown").Inc() + fleetmetrics.UnknownOperations.Inc() + h.writeExistingTask(w, op) + return + } + op, _ = h.Journal.Finish(id, journal.Failed, http.StatusBadGateway, "adapter returned a bounded non-secret failure") + fleetmetrics.Operations.WithLabelValues("failed").Inc() + writeError(w, http.StatusBadGateway, "Fleet.1.0.BMCOperationFailed", "The allocated system did not complete the requested operation.") + return + } + op, _ = h.Journal.Finish(id, journal.Succeeded, http.StatusOK, "adapter response received") + fleetmetrics.Operations.WithLabelValues("succeeded").Inc() + w.Header().Set("Location", "/redfish/v1/TaskService/Tasks/"+op.ID) + writeJSON(w, http.StatusAccepted, taskBody(op)) +} + +func (h *Handler) writeExistingTask(w http.ResponseWriter, op journal.Operation) { + w.Header().Set("Location", "/redfish/v1/TaskService/Tasks/"+op.ID) + writeJSON(w, http.StatusAccepted, taskBody(op)) +} +func (h *Handler) taskService(w http.ResponseWriter) { + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#TaskService.v1_2_0.TaskService", "@odata.id": "/redfish/v1/TaskService", "Id": "TaskService", "Name": "Task Service", "ServiceEnabled": true, "Tasks": odata("/redfish/v1/TaskService/Tasks")}) +} +func (h *Handler) tasks(w http.ResponseWriter) { + operations, err := h.Journal.List() + if err != nil { + writeError(w, http.StatusInternalServerError, "Fleet.1.0.JournalUnavailable", "Tasks could not be read from the durable journal.") + return + } + members := make([]any, 0, len(operations)) + for _, operation := range operations { + if operation.SessionUID == h.authority().SessionUID { + members = append(members, odata("/redfish/v1/TaskService/Tasks/"+operation.ID)) + } + } + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#TaskCollection.TaskCollection", "@odata.id": "/redfish/v1/TaskService/Tasks", "Name": "Tasks", "Members": members, "Members@odata.count": len(members)}) +} +func (h *Handler) task(w http.ResponseWriter, id string) { + op, err := h.Journal.Get(id) + if err != nil || op.SessionUID != h.authority().SessionUID { + writeError(w, http.StatusNotFound, "Base.1.18.ResourceMissingAtURI", "Task not found.") + return + } + writeJSON(w, http.StatusOK, taskBody(op)) +} + +func taskBody(op journal.Operation) map[string]any { + state, status := "Running", "OK" + if op.Outcome == journal.Succeeded { + state = "Completed" + } + if op.Outcome == journal.Failed { + state = "Exception" + status = "Critical" + } + if op.Outcome == journal.Unknown { + state = "Exception" + status = "Warning" + } + return map[string]any{"@odata.type": "#Task.v1_7_4.Task", "@odata.id": "/redfish/v1/TaskService/Tasks/" + op.ID, "Id": op.ID, "Name": "Fleet machine operation", "TaskState": state, "TaskStatus": status, "Messages": []any{map[string]any{"MessageId": "Fleet.1.0." + string(op.Outcome), "Message": op.Evidence, "Severity": status, "Resolution": "Inspect or recover the existing operation; do not resubmit an unknown effect."}}} +} +func odata(path string) map[string]string { return map[string]string{"@odata.id": path} } +func setODataHeaders(w http.ResponseWriter) { + w.Header().Set("OData-Version", "4.0") + w.Header().Set("Content-Type", "application/json") +} +func writeJSON(w http.ResponseWriter, status int, v any) { + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} +func writeError(w http.ResponseWriter, status int, id, message string) { + writeJSON(w, status, map[string]any{ + "error": map[string]any{ + "code": id, + "message": message, + "@Message.ExtendedInfo": []any{map[string]any{ + "MessageId": id, + "Message": message, + "Severity": "Critical", + "Resolution": "Use only resources and values declared by the Fleet Provisioning profile.", + }}, + }, + }) +} +func readBody(r *http.Request) ([]byte, error) { + defer r.Body.Close() + b, err := io.ReadAll(io.LimitReader(r.Body, 64<<10)) + if err != nil { + return nil, err + } + if len(b) == 0 { + return nil, errors.New("request body is required") + } + var v any + if json.Unmarshal(b, &v) != nil { + return nil, errors.New("request body must be valid JSON") + } + return b, nil +} +func decodeExact(r *http.Request, v any) error { + defer r.Body.Close() + d := json.NewDecoder(io.LimitReader(r.Body, 64<<10)) + d.DisallowUnknownFields() + return d.Decode(v) +} +func (h *Handler) now() time.Time { + if h.Now != nil { + return h.Now() + } + return time.Now() +} + +func (h *Handler) authority() Authority { + if h.CurrentAuthority != nil { + return h.CurrentAuthority() + } + return h.Authority +} diff --git a/internal/redfish/handler_test.go b/internal/redfish/handler_test.go new file mode 100644 index 00000000..5eb2c530 --- /dev/null +++ b/internal/redfish/handler_test.go @@ -0,0 +1,147 @@ +package redfish + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "go.datum.net/fleet/internal/journal" +) + +type fakeAdapter struct { + resets int + boots int + lost bool +} + +func (a *fakeAdapter) Observe(context.Context) (System, error) { + return System{PowerState: "Off", BootTarget: "Hdd"}, nil +} +func (a *fakeAdapter) SetOneTimeBoot(context.Context, string) error { a.boots++; return nil } +func (a *fakeAdapter) Reset(context.Context, string) error { + a.resets++ + if a.lost { + a.lost = false + return ErrResponseLost + } + return nil +} +func (a *fakeAdapter) PhysicalTarget() string { return "private-target" } + +func newHandler(t *testing.T, a Adapter) *Handler { + t.Helper() + s, err := journal.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + now := time.Unix(1000, 0) + return &Handler{Adapter: a, Journal: s, Now: func() time.Time { return now }, Authority: Authority{SessionUID: "session", ClaimUID: "claim", MachineUID: "machine", BindingID: "binding", BindingEpoch: 7, AdapterRoute: "sushy-libvirt", OperationEpoch: 1, ExpiresAt: now.Add(time.Hour), FreshUntil: now.Add(time.Minute)}} +} + +func request(h http.Handler, method, path, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.Host = "127.0.0.1:9443" + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +func TestNarrowProfileAndSingleSystem(t *testing.T) { + h := newHandler(t, &fakeAdapter{}) + for _, p := range []string{"/redfish/v1/AccountService", "/redfish/v1/Managers", "/redfish/v1/UpdateService", "/redfish/v1/Systems/guessed", "/redfish/v1/Systems/allocated/Oem/Reset"} { + if got := request(h, http.MethodGet, p, "").Code; got != http.StatusNotFound { + t.Errorf("%s: %d", p, got) + } + } + w := request(h, http.MethodGet, "/redfish/v1/Systems", "") + if w.Code != 200 || strings.Contains(w.Body.String(), "private-target") { + t.Fatalf("systems: %d %s", w.Code, w.Body.String()) + } + var body map[string]any + if json.Unmarshal(w.Body.Bytes(), &body) != nil || body["Members@odata.count"].(float64) != 1 { + t.Fatalf("unexpected collection %s", w.Body.String()) + } + r := httptest.NewRequest(http.MethodGet, "/redfish/v1/Systems", nil) + r.Host = "second-bmc.internal" + rr := httptest.NewRecorder() + h.ServeHTTP(rr, r) + if rr.Code != http.StatusBadRequest { + t.Fatalf("Host manipulation accepted: %d", rr.Code) + } +} + +func TestUnsupportedMutationsRejected(t *testing.T) { + a := &fakeAdapter{} + h := newHandler(t, a) + bad := []string{`{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Usb"}}`, `{"AssetTag":"x"}`} + for _, body := range bad { + if got := request(h, http.MethodPatch, "/redfish/v1/Systems/allocated", body).Code; got != 400 { + t.Fatalf("patch %s: %d", body, got) + } + } + if got := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"Nmi"}`).Code; got != 400 { + t.Fatalf("reset: %d", got) + } + if a.boots != 0 || a.resets != 0 { + t.Fatal("rejected request reached adapter") + } +} + +func TestLostResponseIsUnknownAndNeverDuplicatesReset(t *testing.T) { + a := &fakeAdapter{lost: true} + h := newHandler(t, a) + body := `{"ResetType":"ForceRestart"}` + w1 := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", body) + w2 := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", body) + if w1.Code != 202 || w2.Code != 202 { + t.Fatalf("codes %d %d", w1.Code, w2.Code) + } + if a.resets != 1 { + t.Fatalf("reset executed %d times", a.resets) + } + if !strings.Contains(w2.Body.String(), "Unknown") { + t.Fatalf("retry did not preserve unknown: %s", w2.Body.String()) + } +} + +func TestTaskCollectionListsOnlyCurrentSession(t *testing.T) { + h := newHandler(t, &fakeAdapter{}) + mutation := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"On"}`) + if mutation.Code != http.StatusAccepted { + t.Fatalf("mutation: %d %s", mutation.Code, mutation.Body.String()) + } + collection := request(h, http.MethodGet, "/redfish/v1/TaskService/Tasks", "") + if collection.Code != http.StatusOK || !strings.Contains(collection.Body.String(), `"Members@odata.count":1`) { + t.Fatalf("tasks: %d %s", collection.Code, collection.Body.String()) + } +} + +func TestStaleAuthorityFailsClosed(t *testing.T) { + h := newHandler(t, &fakeAdapter{}) + h.Authority.FreshUntil = time.Unix(999, 0) + w := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"On"}`) + if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "AuthorityStale") { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } +} + +func TestExpiredSessionFailsClosed(t *testing.T) { + a := &fakeAdapter{} + h := newHandler(t, a) + h.Authority.ExpiresAt = time.Unix(999, 0) + w := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"On"}`) + if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "SessionExpired") || a.resets != 0 { + t.Fatalf("expired request: code=%d resets=%d body=%s", w.Code, a.resets, w.Body.String()) + } +} + +func TestAdapterResponseLostSentinel(t *testing.T) { + if !errors.Is(ErrResponseLost, ErrResponseLost) { + t.Fatal("sentinel") + } +} diff --git a/internal/relay/relay.go b/internal/relay/relay.go new file mode 100644 index 00000000..a9a5fb2b --- /dev/null +++ b/internal/relay/relay.go @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package relay pairs one outbound location connection with one client. After +// pairing it copies opaque bytes and cannot inspect the inner TLS/Redfish data. +package relay + +import ( + "bufio" + "crypto/subtle" + "fmt" + "io" + "net" + "strings" + "sync" + "time" +) + +type Server struct { + GatewayToken string + mu sync.Mutex + routes map[string]net.Conn +} + +func NewServer(token string) *Server { + return &Server{GatewayToken: token, routes: map[string]net.Conn{}} +} + +func (s *Server) Serve(l net.Listener) error { + for { + c, err := l.Accept() + if err != nil { + return err + } + go s.handle(c) + } +} + +func (s *Server) handle(c net.Conn) { + _ = c.SetReadDeadline(time.Now().Add(10 * time.Second)) + br := bufio.NewReader(io.LimitReader(c, 4096)) + line, err := br.ReadString('\n') + if err != nil { + _ = c.Close() + return + } + parts := strings.Fields(line) + switch { + case len(parts) == 3 && parts[0] == "GATEWAY": + if subtle.ConstantTimeCompare([]byte(parts[2]), []byte(s.GatewayToken)) != 1 { + reject(c, "gateway authentication failed") + return + } + s.register(parts[1], c) + case len(parts) == 2 && parts[0] == "CLIENT": + s.connect(parts[1], c) + default: + reject(c, "invalid relay preface") + } +} + +func (s *Server) register(route string, c net.Conn) { + s.mu.Lock() + if old := s.routes[route]; old != nil { + s.mu.Unlock() + reject(c, "route already registered") + return + } + s.routes[route] = c + s.mu.Unlock() + _ = c.SetDeadline(time.Time{}) + if _, err := io.WriteString(c, "WAIT\n"); err != nil { + s.remove(route, c) + _ = c.Close() + } +} + +func (s *Server) connect(route string, client net.Conn) { + s.mu.Lock() + gateway := s.routes[route] + delete(s.routes, route) // the first connector consumes the route + s.mu.Unlock() + if gateway == nil { + reject(client, "route unavailable or already consumed") + return + } + _ = client.SetDeadline(time.Time{}) + if _, err := io.WriteString(client, "OK\n"); err != nil { + _ = client.Close() + _ = gateway.Close() + return + } + if _, err := io.WriteString(gateway, "OK\n"); err != nil { + _ = client.Close() + _ = gateway.Close() + return + } + proxy(client, gateway) +} + +func (s *Server) remove(route string, c net.Conn) { + s.mu.Lock() + defer s.mu.Unlock() + if s.routes[route] == c { + delete(s.routes, route) + } +} + +func reject(c net.Conn, reason string) { _, _ = fmt.Fprintf(c, "ERROR %s\n", reason); _ = c.Close() } + +func proxy(a, b net.Conn) { + var once sync.Once + closeBoth := func() { _ = a.Close(); _ = b.Close() } + go func() { _, _ = io.Copy(a, b); once.Do(closeBoth) }() + go func() { _, _ = io.Copy(b, a); once.Do(closeBoth) }() +} + +func Register(conn net.Conn, route, token string) error { + if _, err := fmt.Fprintf(conn, "GATEWAY %s %s\n", route, token); err != nil { + return err + } + line, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + return err + } + if line != "WAIT\n" { + return fmt.Errorf("relay rejected gateway: %s", strings.TrimSpace(line)) + } + return nil +} + +func Connect(conn net.Conn, route string) error { + if _, err := fmt.Fprintf(conn, "CLIENT %s\n", route); err != nil { + return err + } + line, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + return err + } + if line != "OK\n" { + return fmt.Errorf("relay refused route: %s", strings.TrimSpace(line)) + } + return nil +} diff --git a/internal/relay/relay_test.go b/internal/relay/relay_test.go new file mode 100644 index 00000000..3758b5e5 --- /dev/null +++ b/internal/relay/relay_test.go @@ -0,0 +1,30 @@ +package relay + +import ( + "bufio" + "net" + "strings" + "testing" +) + +func TestFirstConnectorConsumesRoute(t *testing.T) { + s := NewServer("separate-gateway-token") + g, relayGateway := net.Pipe() + go s.handle(relayGateway) + if err := Register(g, "route-a", "separate-gateway-token"); err != nil { + t.Fatal(err) + } + c1, relayClient1 := net.Pipe() + go s.handle(relayClient1) + if err := Connect(c1, "route-a"); err != nil { + t.Fatal(err) + } + if line, _ := bufio.NewReader(g).ReadString('\n'); line != "OK\n" { + t.Fatalf("gateway got %q", line) + } + c2, relayClient2 := net.Pipe() + go s.handle(relayClient2) + if err := Connect(c2, "route-a"); err == nil || !strings.Contains(err.Error(), "consumed") { + t.Fatalf("second connector: %v", err) + } +} diff --git a/test/e2e/machine-management/compose.openvpn.yaml b/test/e2e/machine-management/compose.openvpn.yaml new file mode 100644 index 00000000..c425a199 --- /dev/null +++ b/test/e2e/machine-management/compose.openvpn.yaml @@ -0,0 +1,4 @@ +services: + virtual-bmc: + environment: + FLEET_OPENVPN: "1" diff --git a/test/e2e/machine-management/compose.yaml b/test/e2e/machine-management/compose.yaml new file mode 100644 index 00000000..6424391a --- /dev/null +++ b/test/e2e/machine-management/compose.yaml @@ -0,0 +1,21 @@ +services: + virtual-bmc: + platform: linux/amd64 + build: ./virtual-bmc + container_name: fleet-e2e-virtual-bmc + privileged: true + environment: + FLEET_FORCE_QEMU: ${FLEET_FORCE_QEMU:-0} + networks: + management: + ipv4_address: 172.30.0.10 + volumes: + - ${FLEET_E2E_STATE:?set FLEET_E2E_STATE}/evidence:/evidence + - ${FLEET_E2E_STATE:?set FLEET_E2E_STATE}/images:/var/lib/libvirt/images +networks: + management: + name: fleet-management-e2e + internal: true + ipam: + config: + - subnet: 172.30.0.0/24 diff --git a/test/e2e/machine-management/generic-client.py b/test/e2e/machine-management/generic-client.py new file mode 100755 index 00000000..81516b03 --- /dev/null +++ b/test/e2e/machine-management/generic-client.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Exercise Fleet through DMTF's unmodified Python Redfish client.""" + +import json +import os + +import redfish + + +with open(os.environ["FLEET_CREDENTIAL_FILE"], encoding="utf-8") as source: + credential = json.load(source) + +client = redfish.redfish_client( + base_url=credential["endpoint"].removesuffix("/redfish/v1/"), + username=credential["username"], + password=credential["password"], + cafile=os.environ.get("FLEET_CA_BUNDLE", credential["caBundle"]), + default_prefix="/redfish/v1", +) +client.login(auth="session") +root = client.get("/redfish/v1/") +systems = client.get("/redfish/v1/Systems") +system = client.get("/redfish/v1/Systems/allocated") +assert root.status == 200, root.status +assert systems.status == 200 and systems.dict["Members@odata.count"] == 1 +assert system.status == 200 and system.dict["Id"] == "allocated" +assert "Managers" not in root.dict and "AccountService" not in root.dict +client.logout() +print("generic DMTF Redfish client: PASS") diff --git a/test/e2e/machine-management/kind-location.yaml b/test/e2e/machine-management/kind-location.yaml new file mode 100644 index 00000000..1543cccb --- /dev/null +++ b/test/e2e/machine-management/kind-location.yaml @@ -0,0 +1,11 @@ +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +networking: + apiServerAddress: 127.0.0.1 +nodes: + - role: control-plane + extraPortMappings: + - containerPort: 30443 + hostPort: 30443 + listenAddress: 127.0.0.1 + protocol: TCP diff --git a/test/e2e/machine-management/kind-management.yaml b/test/e2e/machine-management/kind-management.yaml new file mode 100644 index 00000000..f64b87e8 --- /dev/null +++ b/test/e2e/machine-management/kind-management.yaml @@ -0,0 +1,4 @@ +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +nodes: + - role: control-plane diff --git a/test/e2e/machine-management/openvpn/Dockerfile b/test/e2e/machine-management/openvpn/Dockerfile new file mode 100644 index 00000000..bbdaf95a --- /dev/null +++ b/test/e2e/machine-management/openvpn/Dockerfile @@ -0,0 +1,5 @@ +FROM debian:12.12-slim +RUN apt-get update && apt-get install -y --no-install-recommends curl iptables openvpn && rm -rf /var/lib/apt/lists/* +COPY entrypoint.sh /usr/local/bin/entrypoint +RUN chmod 0755 /usr/local/bin/entrypoint +ENTRYPOINT ["/usr/local/bin/entrypoint"] diff --git a/test/e2e/machine-management/openvpn/client.yaml b/test/e2e/machine-management/openvpn/client.yaml new file mode 100644 index 00000000..42b314ce --- /dev/null +++ b/test/e2e/machine-management/openvpn/client.yaml @@ -0,0 +1,26 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: fleet-openvpn-client + namespace: machine-access-system +spec: + selector: {matchLabels: {app.kubernetes.io/name: fleet-openvpn-client}} + template: + metadata: {labels: {app.kubernetes.io/name: fleet-openvpn-client}} + spec: + hostNetwork: true + automountServiceAccountToken: false + containers: + - name: openvpn + image: fleet-openvpn-client:e2e + imagePullPolicy: IfNotPresent + securityContext: + privileged: true + volumeMounts: + - {name: key, mountPath: /var/run/openvpn, readOnly: true} + - {name: tun, mountPath: /dev/net/tun} + volumes: + - name: key + secret: {secretName: fleet-openvpn-key, defaultMode: 0400} + - name: tun + hostPath: {path: /dev/net/tun, type: CharDevice} diff --git a/test/e2e/machine-management/openvpn/entrypoint.sh b/test/e2e/machine-management/openvpn/entrypoint.sh new file mode 100755 index 00000000..59da712e --- /dev/null +++ b/test/e2e/machine-management/openvpn/entrypoint.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +openvpn --daemon --dev tun --ifconfig 10.88.0.2 10.88.0.1 \ + --secret /var/run/openvpn/openvpn.key --remote 172.30.0.10 1194 --proto udp \ + --cipher AES-256-CBC --auth SHA256 +for _ in $(seq 1 30); do + ip link show tun0 >/dev/null 2>&1 && break + sleep 1 +done +ip link show tun0 >/dev/null +iptables -t nat -A POSTROUTING -d 10.88.0.1/32 -j MASQUERADE +exec sleep infinity diff --git a/test/e2e/machine-management/seed/allocation.yaml b/test/e2e/machine-management/seed/allocation.yaml new file mode 100644 index 00000000..6f73e877 --- /dev/null +++ b/test/e2e/machine-management/seed/allocation.yaml @@ -0,0 +1,24 @@ +apiVersion: fleet.datumapis.com/v1alpha1 +kind: MachineAllocationBinding +metadata: + name: db-01-allocation + namespace: fleet-system + labels: + fleet.datumapis.com/claim-uid: CLAIM_UID +spec: + consumerProjectUID: 11111111-1111-4111-8111-111111111111 + providerProjectUID: 22222222-2222-4222-8222-222222222222 + claimNamespace: default + claimName: db-01 + claimUID: CLAIM_UID + machineName: synthetic-allocated + machineUID: 33333333-3333-4333-8333-333333333333 + bindingID: allocation-e2e-1 + bindingEpoch: 1 + locationUID: 44444444-4444-4444-8444-444444444444 + locationRevision: location-prototype-r1 + bareMetalMachineUID: 55555555-5555-4555-8555-555555555555 + accessProfileRevision: fleet-provisioning-v1.0.0 + adapterRoute: sushy-libvirt-v1 + bmcSystemID: allocated + active: true diff --git a/test/e2e/machine-management/seed/claim.yaml b/test/e2e/machine-management/seed/claim.yaml new file mode 100644 index 00000000..fff045bb --- /dev/null +++ b/test/e2e/machine-management/seed/claim.yaml @@ -0,0 +1,7 @@ +apiVersion: fleet.datumapis.com/v1alpha1 +kind: MachineClaim +metadata: + name: db-01 + namespace: default +spec: + machineClassRef: {name: synthetic-libvirt} diff --git a/test/e2e/machine-management/seed/test-identities.yaml b/test/e2e/machine-management/seed/test-identities.yaml new file mode 100644 index 00000000..6a46589e --- /dev/null +++ b/test/e2e/machine-management/seed/test-identities.yaml @@ -0,0 +1,25 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-authorized, namespace: default} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-viewer, namespace: default} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-authorized-claim-view, namespace: default} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machineclaim-viewer} +subjects: [{kind: ServiceAccount, name: fleet-authorized, namespace: default}] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-viewer-claim-view, namespace: default} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machineclaim-viewer} +subjects: [{kind: ServiceAccount, name: fleet-viewer, namespace: default}] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-authorized-machine-management, namespace: default} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machine-management-session-creator} +subjects: [{kind: ServiceAccount, name: fleet-authorized, namespace: default}] diff --git a/test/e2e/machine-management/tools/Dockerfile b/test/e2e/machine-management/tools/Dockerfile new file mode 100644 index 00000000..9e9a5ff8 --- /dev/null +++ b/test/e2e/machine-management/tools/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13.9-slim-bookworm + +RUN python -m pip install --no-cache-dir \ + redfish==3.4.2 \ + redfish-service-validator==3.1.8 \ + redfish-interop-validator==3.0.3 + +WORKDIR /work +ENTRYPOINT ["/bin/sh", "-c"] diff --git a/test/e2e/machine-management/virtual-bmc/Dockerfile b/test/e2e/machine-management/virtual-bmc/Dockerfile new file mode 100644 index 00000000..4c0a2aa6 --- /dev/null +++ b/test/e2e/machine-management/virtual-bmc/Dockerfile @@ -0,0 +1,15 @@ +FROM ubuntu:24.04@sha256:2198e4c65076e9cb0b3d695219df667c0e3b0072da64ca3c2648aca17dcecaf5 +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + busybox-static cpio curl dnsmasq-base iptables ipxe libvirt-clients \ + libvirt-daemon-system linux-image-virtual nginx openvpn ovmf pxelinux python3 \ + python3-libvirt python3-venv qemu-system-x86 qemu-utils syslinux-common zstd && \ + rm -rf /var/lib/apt/lists/* && \ + python3 -m venv --system-site-packages /opt/sushy && \ + /opt/sushy/bin/pip install --no-cache-dir sushy-tools==2.2.0 +COPY emulator.conf /etc/sushy-emulator.conf +COPY callback.py /usr/local/bin/pxe-callback +COPY entrypoint.sh /usr/local/bin/virtual-bmc-entrypoint +RUN chmod 0755 /usr/local/bin/virtual-bmc-entrypoint /usr/local/bin/pxe-callback +EXPOSE 8000 +ENTRYPOINT ["/usr/local/bin/virtual-bmc-entrypoint"] diff --git a/test/e2e/machine-management/virtual-bmc/callback.py b/test/e2e/machine-management/virtual-bmc/callback.py new file mode 100755 index 00000000..a27c873e --- /dev/null +++ b/test/e2e/machine-management/virtual-bmc/callback.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +import datetime +import http.server +import json +import pathlib + +LOG = pathlib.Path('/evidence/pxe-callbacks.jsonl') +BOOT_DIR = pathlib.Path('/var/lib/libvirt/dnsmasq/tftp') + +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + entry = {'time': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'path': self.path, 'client': self.client_address[0]} + with LOG.open('a', encoding='utf-8') as out: + out.write(json.dumps(entry) + '\n') + out.flush() + if self.path == '/boot.ipxe': + body = (b'#!ipxe\n' + b'kernel http://192.168.124.1:8080/vmlinuz console=ttyS0 ip=dhcp\n' + b'initrd http://192.168.124.1:8080/initramfs.gz\n' + b'boot\n') + self.send_response(200) + self.send_header('Content-Type', 'text/plain') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if self.path in ('/vmlinuz', '/initramfs.gz'): + body = (BOOT_DIR / self.path.removeprefix('/')).read_bytes() + self.send_response(200) + self.send_header('Content-Type', 'application/octet-stream') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if not self.path.startswith('/pxe/'): + self.send_error(404) + return + self.send_response(204) + self.end_headers() + def log_message(self, *_): + pass + +http.server.ThreadingHTTPServer(('192.168.124.1', 8080), Handler).serve_forever() diff --git a/test/e2e/machine-management/virtual-bmc/emulator.conf b/test/e2e/machine-management/virtual-bmc/emulator.conf new file mode 100644 index 00000000..9c5908d3 --- /dev/null +++ b/test/e2e/machine-management/virtual-bmc/emulator.conf @@ -0,0 +1,6 @@ +SUSHY_EMULATOR_LISTEN_IP = '0.0.0.0' +SUSHY_EMULATOR_LISTEN_PORT = 8000 +SUSHY_EMULATOR_FEATURE_SET = 'minimum' +SUSHY_EMULATOR_LIBVIRT_URI = 'qemu:///system' +SUSHY_EMULATOR_IGNORE_BOOT_DEVICE = False +SUSHY_EMULATOR_STATE_DIR = '/var/lib/sushy-emulator' diff --git a/test/e2e/machine-management/virtual-bmc/entrypoint.sh b/test/e2e/machine-management/virtual-bmc/entrypoint.sh new file mode 100755 index 00000000..97b70a20 --- /dev/null +++ b/test/e2e/machine-management/virtual-bmc/entrypoint.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /run/libvirt /var/lib/libvirt/images /var/lib/sushy-emulator /evidence +# Docker/Lima exposes cgroup v2 to this privileged test appliance, but nested +# per-domain cgroup creation is not portable across runners. Libvirt still owns +# the QEMU process lifecycle; resource isolation is supplied by the container. +sed -i 's/^#cgroup_controllers = .*/cgroup_controllers = []/' /etc/libvirt/qemu.conf +# The persisted test disks are bind-mounted so diagnostics survive appliance +# recreation. macOS/virtiofs does not permit libvirt's DAC ownership rewrites; +# the appliance is already isolated and privileged, so keep QEMU root-owned and +# disable dynamic ownership inside this test-only container. +sed -i \ + -e 's/^#security_driver = .*/security_driver = "none"/' \ + -e 's/^#user = .*/user = "root"/' \ + -e 's/^#group = .*/group = "root"/' \ + -e 's/^#dynamic_ownership = .*/dynamic_ownership = 0/' \ + /etc/libvirt/qemu.conf +virtlogd >/evidence/virtlogd.log 2>&1 & +libvirtd >/evidence/libvirtd.log 2>&1 & +for _ in $(seq 1 60); do + virsh -c qemu:///system list >/dev/null 2>&1 && break + sleep 1 +done +virsh -c qemu:///system list >/dev/null + +domain_type=qemu +if [[ ${FLEET_FORCE_QEMU:-0} != 1 && -c /dev/kvm && -r /dev/kvm && -w /dev/kvm ]]; then + domain_type=kvm +fi +echo "domain_type=${domain_type}" > /evidence/acceleration.txt + +mkdir -p /var/lib/libvirt/dnsmasq/tftp/pxelinux.cfg /tmp/initramfs/{bin,dev,etc,proc,sys,lib} +cp /usr/lib/PXELINUX/pxelinux.0 /var/lib/libvirt/dnsmasq/tftp/ +cp /usr/lib/syslinux/modules/bios/ldlinux.c32 /var/lib/libvirt/dnsmasq/tftp/ +kernel_path=$(find /boot -maxdepth 1 -name 'vmlinuz-*' -type f | sort | tail -1) +kernel_version=${kernel_path##*/vmlinuz-} +cp "${kernel_path}" /var/lib/libvirt/dnsmasq/tftp/vmlinuz +e1000_module=$(modinfo -k "${kernel_version}" -F filename e1000) +case "${e1000_module}" in + *.zst) zstd -q -d -c "${e1000_module}" > /tmp/initramfs/lib/e1000.ko ;; + *.ko) cp "${e1000_module}" /tmp/initramfs/lib/e1000.ko ;; + *) echo "unsupported e1000 module format: ${e1000_module}" >&2; exit 1 ;; +esac +cp /bin/busybox /tmp/initramfs/bin/busybox +for app in sh mount ip udhcpc wget poweroff sleep insmod; do ln -sf busybox "/tmp/initramfs/bin/${app}"; done +cat >/tmp/initramfs/bin/udhcpc-script <<'DHCP' +#!/bin/sh +case "$1" in + bound|renew) + ip addr flush dev "$interface" + ip addr add "$ip/24" dev "$interface" + ip link set "$interface" up + ;; +esac +DHCP +chmod +x /tmp/initramfs/bin/udhcpc-script +cat >/tmp/initramfs/init <<'INIT' +#!/bin/sh +mount -t proc proc /proc +mount -t sysfs sysfs /sys +mount -t devtmpfs devtmpfs /dev +insmod /lib/e1000.ko +ip link set eth0 up +udhcpc -i eth0 -q -n -s /bin/udhcpc-script +mac=$(cat /sys/class/net/eth0/address | tr ':' '-') +wget -q -O /dev/null "http://192.168.124.1:8080/pxe/${mac}" +sleep 2 +poweroff -f +INIT +chmod +x /tmp/initramfs/init +(cd /tmp/initramfs && find . -print0 | cpio --null -o --format=newc | gzip -9) >/var/lib/libvirt/dnsmasq/tftp/initramfs.gz +cat >/var/lib/libvirt/dnsmasq/tftp/pxelinux.cfg/default <<'PXE' +DEFAULT fleet +PROMPT 0 +TIMEOUT 1 +LABEL fleet + KERNEL vmlinuz + INITRD initramfs.gz + APPEND console=ttyS0 ip=dhcp +PXE + +cat >/tmp/provisioning.xml <<'XML' + + fleet-provisioning + + + + + + + + + + +XML +virsh net-define /tmp/provisioning.xml >/dev/null 2>&1 || true +virsh net-start fleet-provisioning >/dev/null 2>&1 || true + +define_domain() { + local name=$1 mac=$2 + if [[ ! -f "/var/lib/libvirt/images/${name}.qcow2" ]]; then + qemu-img create -f qcow2 "/var/lib/libvirt/images/${name}.qcow2" 128M >/dev/null + fi + cat >"/tmp/${name}.xml" < + ${name} + 256 + 1 + hvm + + + + + + + + +XML + virsh define "/tmp/${name}.xml" >/dev/null +} + +define_domain allocated 52:54:00:aa:00:01 +define_domain unallocated 52:54:00:aa:00:02 + +/usr/local/bin/pxe-callback & +# The optional qualification profile moves gateway traffic onto a real tun +# interface. The default profile admits only the attached location Kind node. +if [[ ${FLEET_OPENVPN:-0} == 1 ]]; then + if [[ ! -f /evidence/openvpn.key ]]; then + openvpn --genkey secret /evidence/openvpn.key + chmod 0600 /evidence/openvpn.key + fi + openvpn --daemon --dev tun --ifconfig 10.88.0.1 10.88.0.2 \ + --secret /evidence/openvpn.key --proto udp --local 172.30.0.10 --port 1194 \ + --cipher AES-256-CBC --auth SHA256 + iptables -I INPUT -p tcp --dport 8000 -s 10.88.0.2 -j ACCEPT +else + iptables -I INPUT -p tcp --dport 8000 -s 172.30.0.20 -j ACCEPT +fi +iptables -A INPUT -p tcp --dport 8000 -j DROP + +exec /opt/sushy/bin/sushy-emulator --config /etc/sushy-emulator.conf From e3bec5b4da94f9ce27d54db7c8078e969b17c246 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 19:50:56 -0600 Subject: [PATCH 04/24] ci: qualify secure BMC prototype branch --- .github/workflows/test-e2e.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index b028064e..ab35dba7 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -3,7 +3,9 @@ name: machine-management-e2e on: pull_request: push: - branches: [main] + branches: + - main + - prototype/secure-bmc-access-ci permissions: contents: read From a5f75f492480386222c0ead12dce0614b79711e3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 19:52:34 -0600 Subject: [PATCH 05/24] ci: install tools in runner temp directory --- .github/workflows/test-e2e.yml | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index ab35dba7..847404d9 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -22,16 +22,22 @@ jobs: cache: true - name: Install pinned tools run: | - curl -fsSL https://github.com/kubernetes-sigs/kind/releases/download/v0.33.0/kind-linux-amd64 -o /usr/local/bin/kind + set -euxo pipefail + tools_bin="${RUNNER_TEMP}/fleet-tools" + mkdir -p "${tools_bin}" + curl -fsSL https://github.com/kubernetes-sigs/kind/releases/download/v0.33.0/kind-linux-amd64 -o "${tools_bin}/kind" curl -fsSL https://github.com/kubernetes-sigs/kind/releases/download/v0.33.0/kind-linux-amd64.sha256sum -o /tmp/kind.sha256 - sed 's#kind-linux-amd64#/usr/local/bin/kind#' /tmp/kind.sha256 | sha256sum -c - - chmod 0755 /usr/local/bin/kind - curl -fsSL https://dl.k8s.io/release/v1.37.0/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl + sed "s#kind-linux-amd64#${tools_bin}/kind#" /tmp/kind.sha256 | sha256sum -c - + chmod 0755 "${tools_bin}/kind" + curl -fsSL https://dl.k8s.io/release/v1.37.0/bin/linux/amd64/kubectl -o "${tools_bin}/kubectl" curl -fsSL https://dl.k8s.io/release/v1.37.0/bin/linux/amd64/kubectl.sha256 -o /tmp/kubectl.sha256 - echo "$(cat /tmp/kubectl.sha256) /usr/local/bin/kubectl" | sha256sum -c - - chmod 0755 /usr/local/bin/kubectl - go install github.com/go-task/task/v3/cmd/task@v3.41.0 - install -m 0755 "$(go env GOPATH)/bin/task" /usr/local/bin/task + echo "$(cat /tmp/kubectl.sha256) ${tools_bin}/kubectl" | sha256sum -c - + chmod 0755 "${tools_bin}/kubectl" + GOBIN="${tools_bin}" go install github.com/go-task/task/v3/cmd/task@v3.41.0 + echo "${tools_bin}" >>"${GITHUB_PATH}" + "${tools_bin}/kind" version + "${tools_bin}/kubectl" version --client + "${tools_bin}/task" --version - name: Portable tests run: task test - name: Start virtual-BMC environment From 2e5c110f4414de4785ab534623171ec4c810c2a5 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 20:04:27 -0600 Subject: [PATCH 06/24] ci: surface end-to-end failure details --- .github/workflows/test-e2e.yml | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index 847404d9..1fe9f3b8 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -43,10 +43,18 @@ jobs: - name: Start virtual-BMC environment run: task e2e:up - name: End-to-end scenarios - run: task e2e:test + run: | + set -o pipefail + task e2e:test 2>&1 | tee .e2e/e2e-test.log - name: Collect diagnostics if: failure() - run: task e2e:diagnostics + run: | + task e2e:diagnostics || true + if [[ -f .e2e/e2e-test.log ]]; then + tail -n 100 .e2e/e2e-test.log + message=$(tail -n 20 .e2e/e2e-test.log | tr '\n' ' ' | sed 's/%/%25/g; s/\r/%0D/g; s/\n/%0A/g') + echo "::error title=E2E failure::${message}" + fi - name: Upload diagnostics and validator reports if: always() uses: actions/upload-artifact@v4 From 8020e84f3d36379bec5a28958c49ca634f16da4b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 20:16:37 -0600 Subject: [PATCH 07/24] e2e: give Redfish validators writable workdirs --- hack/e2e/validators.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hack/e2e/validators.sh b/hack/e2e/validators.sh index 35556924..e166b583 100755 --- a/hack/e2e/validators.sh +++ b/hack/e2e/validators.sh @@ -23,13 +23,13 @@ if [[ $(uname -s) == Darwin ]]; then --authtype Session --nooemcheck --logdir "${REPORT_DIR}/interop" \ "${ROOT_DIR}/config/redfish/FleetProvisioning.v1_0_0.json" else - docker run --rm --network host \ + docker run --rm --network host --workdir /state/validators/service \ -e REQUESTS_CA_BUNDLE=/state/ca.pem \ -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ fleet-redfish-tools:e2e \ "rf_service_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/service" - docker run --rm --network host \ + docker run --rm --network host --workdir /state/validators/interop \ -e REQUESTS_CA_BUNDLE=/state/ca.pem \ -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ fleet-redfish-tools:e2e \ From 3dabd1a3b72002fe28cba624da5f75dcdbfc18e5 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 20:30:56 -0600 Subject: [PATCH 08/24] e2e: fence gateway restart and preserve ownership --- .github/workflows/test-e2e.yml | 9 ++++++++- hack/e2e/test.sh | 2 ++ hack/e2e/validators.sh | 4 ++-- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index 1fe9f3b8..266e7fa3 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -52,7 +52,14 @@ jobs: task e2e:diagnostics || true if [[ -f .e2e/e2e-test.log ]]; then tail -n 100 .e2e/e2e-test.log - message=$(tail -n 20 .e2e/e2e-test.log | tr '\n' ' ' | sed 's/%/%25/g; s/\r/%0D/g; s/\n/%0A/g') + { + tail -n 20 .e2e/e2e-test.log + if [[ -f .e2e/proxy.log ]]; then + echo "proxy log:" + tail -n 20 .e2e/proxy.log + fi + } >"${RUNNER_TEMP}/fleet-e2e-error.txt" + message=$(tr '\n' ' ' <"${RUNNER_TEMP}/fleet-e2e-error.txt" | sed 's/%/%25/g; s/\r/%0D/g; s/\n/%0A/g') echo "::error title=E2E failure::${message}" fi - name: Upload diagnostics and validator reports diff --git a/hack/e2e/test.sh b/hack/e2e/test.sh index aa903e8e..3a963fa8 100755 --- a/hack/e2e/test.sh +++ b/hack/e2e/test.sh @@ -280,6 +280,8 @@ wait_for "new allocation domain power-on" "[[ \$(docker exec fleet-e2e-virtual-b # Fault-inject a lost BMC response. Retrying the identical admitted operation # must recover its Unknown task without sending a second physical reset. stop_proxy +wait_for "prior location projection teardown" \ + "! kubectl --kubeconfig '${LOCATION_KUBECONFIG}' -n machine-access-system get projectedmachinemanagementsessions.fleet.datumapis.com -o name 2>/dev/null | grep -q ." kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch deployment fleet-gateway --type=json \ -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--fault-drop-reset-response-once"}]' kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s diff --git a/hack/e2e/validators.sh b/hack/e2e/validators.sh index e166b583..66b7495d 100755 --- a/hack/e2e/validators.sh +++ b/hack/e2e/validators.sh @@ -23,13 +23,13 @@ if [[ $(uname -s) == Darwin ]]; then --authtype Session --nooemcheck --logdir "${REPORT_DIR}/interop" \ "${ROOT_DIR}/config/redfish/FleetProvisioning.v1_0_0.json" else - docker run --rm --network host --workdir /state/validators/service \ + docker run --rm --network host --user "$(id -u):$(id -g)" --workdir /state/validators/service \ -e REQUESTS_CA_BUNDLE=/state/ca.pem \ -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ fleet-redfish-tools:e2e \ "rf_service_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/service" - docker run --rm --network host --workdir /state/validators/interop \ + docker run --rm --network host --user "$(id -u):$(id -g)" --workdir /state/validators/interop \ -e REQUESTS_CA_BUNDLE=/state/ca.pem \ -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ fleet-redfish-tools:e2e \ From d896513432c8dd6fe20f5a79a2b50fc7896cbd42 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 20:52:29 -0600 Subject: [PATCH 09/24] ci: run qualification on pull requests --- .github/workflows/test-e2e.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index 266e7fa3..0c44199e 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -5,7 +5,6 @@ on: push: branches: - main - - prototype/secure-bmc-access-ci permissions: contents: read From f612f645c8a7f0f32d3f09302665fa8e13dab8a2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 21:07:04 -0600 Subject: [PATCH 10/24] build: include public API in manager image --- .dockerignore | 2 ++ build/manager.Dockerfile | 1 + 2 files changed, 3 insertions(+) diff --git a/.dockerignore b/.dockerignore index f026529a..ead4d050 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,6 +1,8 @@ ** !go.mod !go.sum +!api/ +!api/** !cmd/ !cmd/** !internal/ diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index 9981f758..9092a95c 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -3,6 +3,7 @@ ARG TARGETOS TARGETARCH WORKDIR /src COPY go.mod go.sum ./ RUN go mod download +COPY api/ ./api/ COPY cmd/ ./cmd/ COPY internal/ ./internal/ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-manager ./cmd/fleet-manager From 5781a3c9f3b3503542d8f0c4556dfc3a928d51c5 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 11 Nov 2026 22:09:32 -0600 Subject: [PATCH 11/24] feat: federate management sessions with Karmada --- .github/workflows/test-e2e.yml | 8 + README.md | 7 +- Taskfile.yaml | 2 +- api/v1alpha1/types.go | 34 +++-- cmd/fleet-controller/main.go | 12 +- config/README.md | 7 + ...tumapis.com_machineallocationbindings.yaml | 6 + ....com_machinemanagementsessionbindings.yaml | 3 + ...om_projectedmachinemanagementsessions.yaml | 6 + config/federation/interpreter.yaml | 68 +++++++++ config/federation/kustomization.yaml | 5 + .../rbac.yaml} | 27 ++-- config/manager/controller.yaml | 8 +- config/manager/networkpolicy.yaml | 3 + .../machine-management-prototype.md | 60 ++++++-- hack/e2e/diagnostics.sh | 4 + hack/e2e/test.sh | 16 +- hack/e2e/up.sh | 120 ++++++++++++--- internal/controller/projection.go | 141 ++++++++++++------ internal/controller/projection_test.go | 30 +++- internal/controller/session.go | 6 +- internal/controller/session_test.go | 2 +- internal/gateway/gateway.go | 11 ++ .../machine-management/Dockerfile.prebuilt | 5 + .../machine-management/kind-management.yaml | 5 + .../machine-management/seed/allocation.yaml | 1 + .../virtual-bmc/entrypoint.sh | 16 +- 27 files changed, 484 insertions(+), 129 deletions(-) create mode 100644 config/federation/interpreter.yaml create mode 100644 config/federation/kustomization.yaml rename config/{rbac/projector-location.yaml => federation/rbac.yaml} (56%) create mode 100644 test/e2e/machine-management/Dockerfile.prebuilt diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index 0c44199e..f53e2436 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -32,10 +32,18 @@ jobs: curl -fsSL https://dl.k8s.io/release/v1.37.0/bin/linux/amd64/kubectl.sha256 -o /tmp/kubectl.sha256 echo "$(cat /tmp/kubectl.sha256) ${tools_bin}/kubectl" | sha256sum -c - chmod 0755 "${tools_bin}/kubectl" + helm_version=v3.17.3 + curl -fsSL "https://get.helm.sh/helm-${helm_version}-linux-amd64.tar.gz" -o /tmp/helm.tgz + curl -fsSL "https://get.helm.sh/helm-${helm_version}-linux-amd64.tar.gz.sha256sum" -o /tmp/helm.sha256 + helm_sha=$(awk '{print $1}' /tmp/helm.sha256) + echo "${helm_sha} /tmp/helm.tgz" | sha256sum -c - + tar -xzf /tmp/helm.tgz -C /tmp + install -m 0755 /tmp/linux-amd64/helm "${tools_bin}/helm" GOBIN="${tools_bin}" go install github.com/go-task/task/v3/cmd/task@v3.41.0 echo "${tools_bin}" >>"${GITHUB_PATH}" "${tools_bin}/kind" version "${tools_bin}/kubectl" version --client + "${tools_bin}/helm" version "${tools_bin}/task" --version - name: Portable tests run: task test diff --git a/README.md b/README.md index 28cefb9d..39b43c7b 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ task test task build ``` -The complete path requires Linux, Docker with Compose, Kind, kubectl, jq, +The complete path requires Linux, Docker with Compose, Kind, kubectl, Helm, jq, OpenSSL, curl, and Task. It builds all images locally and loads them into Kind; it does not require a registry. @@ -95,7 +95,10 @@ task e2e:openvpn:up task e2e:down ``` -`e2e:up` and `e2e:down` are idempotent. The latter removes only the two named +`e2e:up` installs pinned Karmada into the management Kind cluster and registers +the location Kind cluster as its member. The repository-local harness does not +yet consume `datum-cloud/test-infra`; that remains production-environment +packaging work. `e2e:up` and `e2e:down` are idempotent. The latter removes only the two named Kind clusters, the `fleet-bmc-e2e` Compose project, its isolated network, and the repository-local `.e2e` directory. diff --git a/Taskfile.yaml b/Taskfile.yaml index 4b97b2b3..6ff5c6bd 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -25,7 +25,7 @@ tasks: - env GOCACHE={{.GO_CACHE}} go build -o bin/fleet-relay ./cmd/fleet-relay e2e:up: - desc: Create the two Kind clusters and real sushy/libvirt BMC environment + desc: Create Karmada management/member Kind clusters and the real sushy/libvirt BMC environment cmds: - ./hack/e2e/up.sh diff --git a/api/v1alpha1/types.go b/api/v1alpha1/types.go index 0b0c87cf..7862daa0 100644 --- a/api/v1alpha1/types.go +++ b/api/v1alpha1/types.go @@ -8,8 +8,10 @@ import ( ) const ( - SessionFinalizer = "fleet.datumapis.com/machine-management-session" - ConditionReady = "Ready" + SessionFinalizer = "fleet.datumapis.com/machine-management-session" + ConditionReady = "Ready" + ProjectionActive = "Active" + ProjectionRevoked = "Revoked" ) // MachineClaim is the public allocation handle. The prototype seeds it; the @@ -100,17 +102,20 @@ type MachineAllocationBinding struct { } type MachineAllocationBindingSpec struct { - ConsumerProjectUID types.UID `json:"consumerProjectUID"` - ProviderProjectUID types.UID `json:"providerProjectUID"` - ClaimNamespace string `json:"claimNamespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - MachineName string `json:"machineName"` - MachineUID types.UID `json:"machineUID"` - BindingID string `json:"bindingID"` - BindingEpoch int64 `json:"bindingEpoch"` - LocationUID types.UID `json:"locationUID"` - LocationRevision string `json:"locationRevision"` + ConsumerProjectUID types.UID `json:"consumerProjectUID"` + ProviderProjectUID types.UID `json:"providerProjectUID"` + ClaimNamespace string `json:"claimNamespace"` + ClaimName string `json:"claimName"` + ClaimUID types.UID `json:"claimUID"` + MachineName string `json:"machineName"` + MachineUID types.UID `json:"machineUID"` + BindingID string `json:"bindingID"` + BindingEpoch int64 `json:"bindingEpoch"` + LocationUID types.UID `json:"locationUID"` + LocationRevision string `json:"locationRevision"` + // MemberCluster is the protected Karmada member identity selected by the + // allocator/location registry. It is never supplied by the customer. + MemberCluster string `json:"memberCluster"` BareMetalMachineUID types.UID `json:"bareMetalMachineUID"` AccessProfileRevision string `json:"accessProfileRevision"` AdapterRoute string `json:"adapterRoute"` @@ -151,6 +156,7 @@ type MachineManagementSessionBindingSpec struct { BindingEpoch int64 `json:"bindingEpoch"` LocationUID types.UID `json:"locationUID"` LocationRevision string `json:"locationRevision"` + MemberCluster string `json:"memberCluster"` BareMetalMachineUID types.UID `json:"bareMetalMachineUID"` AccessProfileRevision string `json:"accessProfileRevision"` ClientPublicKey string `json:"clientPublicKey"` @@ -185,6 +191,8 @@ type ProjectedMachineManagementSession struct { } type ProjectedMachineManagementSessionSpec struct { + // +kubebuilder:validation:Enum=Active;Revoked + DesiredState string `json:"desiredState"` SessionUID types.UID `json:"sessionUID"` ClaimUID types.UID `json:"claimUID"` MachineUID types.UID `json:"machineUID"` diff --git a/cmd/fleet-controller/main.go b/cmd/fleet-controller/main.go index 18ebbf5d..5e4e523a 100644 --- a/cmd/fleet-controller/main.go +++ b/cmd/fleet-controller/main.go @@ -23,7 +23,7 @@ import ( ) func main() { - locationKubeconfig := flag.String("location-kubeconfig", "", "kubeconfig for the authoritative location cluster") + federationKubeconfig := flag.String("federation-kubeconfig", "", "kubeconfig for the Karmada federation API") webhookCertDir := flag.String("webhook-cert-dir", "/var/run/fleet-webhook", "webhook serving certificate directory") metrics := flag.String("metrics-bind-address", ":8080", "metrics address") probe := flag.String("health-probe-bind-address", ":8081", "probe address") @@ -31,23 +31,23 @@ func main() { perClaimLimit := flag.Int("per-claim-session-limit", 1, "maximum concurrent sessions for one claim") perProjectLimit := flag.Int("per-project-session-limit", 5, "maximum concurrent sessions for one consumer project") flag.Parse() - if *locationKubeconfig == "" { - slog.Error("--location-kubeconfig is required") + if *federationKubeconfig == "" { + slog.Error("--federation-kubeconfig is required") os.Exit(2) } scheme := runtime.NewScheme() must(clientgoscheme.AddToScheme(scheme)) must(fleetv1alpha1.AddToScheme(scheme)) - locationConfig, err := clientcmd.BuildConfigFromFlags("", *locationKubeconfig) + federationConfig, err := clientcmd.BuildConfigFromFlags("", *federationKubeconfig) must(err) - locationClient, err := client.New(locationConfig, client.Options{Scheme: scheme}) + federationClient, err := client.New(federationConfig, client.Options{Scheme: scheme}) must(err) wh := webhook.NewServer(webhook.Options{CertDir: *webhookCertDir}) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{Scheme: scheme, Metrics: metricsserver.Options{BindAddress: *metrics}, HealthProbeBindAddress: *probe, WebhookServer: wh}) must(err) mgr.GetWebhookServer().Register("/mutate-fleet-datumapis-com-v1alpha1-machinemanagementsession", &admission.Webhook{Handler: controller.SessionAdmission{}}) must((&controller.SessionReconciler{PerClaimLimit: *perClaimLimit, PerProjectLimit: *perProjectLimit}).SetupWithManager(mgr)) - must((&controller.ProjectionReconciler{LocationClient: locationClient, Freshness: *authorityFreshness}).SetupWithManager(mgr)) + must((&controller.ProjectionReconciler{FederationClient: federationClient, Freshness: *authorityFreshness}).SetupWithManager(mgr)) must(mgr.AddHealthzCheck("healthz", healthz.Ping)) must(mgr.AddReadyzCheck("readyz", healthz.Ping)) slog.Info("starting Fleet session controllers") diff --git a/config/README.md b/config/README.md index 46ef73c3..300ff94e 100644 --- a/config/README.md +++ b/config/README.md @@ -8,6 +8,13 @@ API servers and must be reconciled independently. | `config/milo` | Milo root control plane | Fleet CRDs, IAM protected resources and roles, service registration, and machine quota registration | | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, the manager workload and RBAC, private-record namespaces, and admission fences | +The secure machine-management prototype additionally applies +`config/federation` to the Karmada API. It contains the projected-session status +interpreter and least-privilege hub RBAC; the generated projected-session CRD is +applied to the Karmada API separately. This component is not yet part of either +published production root because environment-owned Karmada identity and member +registration have not been selected. + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. diff --git a/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml b/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml index 63b85d74..98daf66e 100644 --- a/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml +++ b/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml @@ -91,6 +91,11 @@ spec: don't ONLY use UUIDs, this is an alias to string. Being a type captures intent and helps make sure that UIDs and names do not get conflated. type: string + memberCluster: + description: |- + MemberCluster is the protected Karmada member identity selected by the + allocator/location registry. It is never supplied by the customer. + type: string providerProjectUID: description: |- UID is a type that holds unique ID values, including UUIDs. Because we @@ -113,6 +118,7 @@ spec: - locationUID - machineName - machineUID + - memberCluster - providerProjectUID type: object required: diff --git a/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml b/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml index e90dc6da..bd7d916e 100644 --- a/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml +++ b/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml @@ -94,6 +94,8 @@ spec: don't ONLY use UUIDs, this is an alias to string. Being a type captures intent and helps make sure that UIDs and names do not get conflated. type: string + memberCluster: + type: string operationCorrelationID: type: string providerProjectUID: @@ -133,6 +135,7 @@ spec: - locationUID - machineName - machineUID + - memberCluster - operationCorrelationID - providerProjectUID - requestingPrincipal diff --git a/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml b/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml index 18b61e60..e9f3a9a8 100644 --- a/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml +++ b/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml @@ -70,6 +70,11 @@ spec: connectBefore: format: date-time type: string + desiredState: + enum: + - Active + - Revoked + type: string expiresAt: format: date-time type: string @@ -108,6 +113,7 @@ spec: - claimUID - clientPublicKey - connectBefore + - desiredState - expiresAt - locationRevision - locationUID diff --git a/config/federation/interpreter.yaml b/config/federation/interpreter.yaml new file mode 100644 index 00000000..b102181d --- /dev/null +++ b/config/federation/interpreter.yaml @@ -0,0 +1,68 @@ +# The gateway writes status only on its cell-local copy. Karmada reflects all +# member statuses and this interpreter accepts only the member identity pinned +# into the protected allocation binding and hub-copy label. A claimed route can +# only be replaced by status for the same route. +apiVersion: config.karmada.io/v1alpha1 +kind: ResourceInterpreterCustomization +metadata: + name: fleet-projected-machine-management-session +spec: + target: + apiVersion: fleet.datumapis.com/v1alpha1 + kind: ProjectedMachineManagementSession + customizations: + statusReflection: + luaScript: | + function ReflectStatus(observedObj) + if observedObj.status == nil then + return nil + end + return observedObj.status + end + statusAggregation: + luaScript: | + local function weight(status) + if status == nil then return 0 end + if status.conditions ~= nil then + for i = 1, #status.conditions do + if status.conditions[i].type == "CleanupConfirmed" and status.conditions[i].status == "True" then + return 4 + end + end + end + if status.connection ~= nil then return 3 end + if status.conditions == nil then return 0 end + for i = 1, #status.conditions do + if status.conditions[i].type == "Ready" and status.conditions[i].status == "False" then + return 2 + end + end + if #status.conditions > 0 then return 1 end + return 0 + end + + function AggregateStatus(desiredObj, statusItems) + if statusItems == nil or desiredObj.metadata == nil or desiredObj.metadata.labels == nil then + return desiredObj + end + local member = desiredObj.metadata.labels["fleet.datumapis.com/member-cluster"] + if member == nil or member == "" then return desiredObj end + local claimed = nil + if desiredObj.status ~= nil and desiredObj.status.connection ~= nil then + claimed = desiredObj.status.connection.routeID + end + local best = nil + local bestWeight = 0 + for i = 1, #statusItems do + local item = statusItems[i] + local status = item.status + local sameClaim = claimed == nil or status == nil or status.connection == nil or status.connection.routeID == claimed + if item.clusterName == member and sameClaim and weight(status) > bestWeight then + best = status + bestWeight = weight(status) + end + end + if best == nil or bestWeight < weight(desiredObj.status) then return desiredObj end + desiredObj.status = best + return desiredObj + end diff --git a/config/federation/kustomization.yaml b/config/federation/kustomization.yaml new file mode 100644 index 00000000..01954f61 --- /dev/null +++ b/config/federation/kustomization.yaml @@ -0,0 +1,5 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - interpreter.yaml + - rbac.yaml diff --git a/config/rbac/projector-location.yaml b/config/federation/rbac.yaml similarity index 56% rename from config/rbac/projector-location.yaml rename to config/federation/rbac.yaml index 9cc22286..746d5648 100644 --- a/config/rbac/projector-location.yaml +++ b/config/federation/rbac.yaml @@ -1,14 +1,7 @@ -apiVersion: v1 -kind: ServiceAccount -metadata: - name: fleet-projector - namespace: machine-access-system ---- apiVersion: rbac.authorization.k8s.io/v1 -kind: Role +kind: ClusterRole metadata: - name: fleet-projector - namespace: machine-access-system + name: fleet-federation-projector rules: - apiGroups: [fleet.datumapis.com] resources: [projectedmachinemanagementsessions] @@ -16,17 +9,19 @@ rules: - apiGroups: [fleet.datumapis.com] resources: [projectedmachinemanagementsessions/status] verbs: [get] + - apiGroups: [policy.karmada.io] + resources: [propagationpolicies] + verbs: [get, list, watch, create, update, patch, delete] --- apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding +kind: ClusterRoleBinding metadata: - name: fleet-projector - namespace: machine-access-system + name: fleet-federation-projector roleRef: apiGroup: rbac.authorization.k8s.io - kind: Role - name: fleet-projector + kind: ClusterRole + name: fleet-federation-projector subjects: - kind: ServiceAccount - name: fleet-projector - namespace: machine-access-system + name: fleet-controller + namespace: fleet-system diff --git a/config/manager/controller.yaml b/config/manager/controller.yaml index 64cb8b11..f1785ed9 100644 --- a/config/manager/controller.yaml +++ b/config/manager/controller.yaml @@ -22,7 +22,7 @@ spec: image: fleet-controller:e2e imagePullPolicy: IfNotPresent args: - - --location-kubeconfig=/var/run/fleet-location/kubeconfig + - --federation-kubeconfig=/var/run/fleet-federation/kubeconfig - --webhook-cert-dir=/var/run/fleet-webhook # Test-only short window; the binary's product-oriented default is 2m. - --authority-freshness=15s @@ -44,12 +44,12 @@ spec: requests: {cpu: 25m, memory: 64Mi} limits: {memory: 256Mi} volumeMounts: - - {name: location, mountPath: /var/run/fleet-location, readOnly: true} + - {name: federation, mountPath: /var/run/fleet-federation, readOnly: true} - {name: webhook, mountPath: /var/run/fleet-webhook, readOnly: true} - {name: tmp, mountPath: /tmp} volumes: - - name: location - secret: {secretName: fleet-location-kubeconfig, defaultMode: 0440} + - name: federation + secret: {secretName: fleet-federation-kubeconfig, defaultMode: 0440} - name: webhook secret: {secretName: fleet-webhook-tls, defaultMode: 0440} - name: tmp diff --git a/config/manager/networkpolicy.yaml b/config/manager/networkpolicy.yaml index d50da2b2..b1747cc1 100644 --- a/config/manager/networkpolicy.yaml +++ b/config/manager/networkpolicy.yaml @@ -14,6 +14,9 @@ spec: ports: [{protocol: TCP, port: 443}] - to: [{ipBlock: {cidr: 172.16.0.0/12}}] ports: [{protocol: TCP, port: 6443}] + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: karmada-system}} + ports: [{protocol: TCP, port: 5443}] - to: - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}} podSelector: {matchLabels: {k8s-app: kube-dns}} diff --git a/docs/implementation/machine-management-prototype.md b/docs/implementation/machine-management-prototype.md index 664e8bd3..307f8091 100644 --- a/docs/implementation/machine-management-prototype.md +++ b/docs/implementation/machine-management-prototype.md @@ -24,9 +24,15 @@ and epoch, location UID/revision, private BareMetalMachine UID, profile revision client key, deadlines, adapter route, and correlation IDs. None of the private target fields are copied to the public session. -The projector writes a least-privileged session to the location API and refreshes -only its cached-authority deadline while every pinned input still matches. The -location gateway registers an outbound opaque route with the relay. Public status +The controller writes a least-privileged session to the separate Karmada API and +creates an exact-cluster `PropagationPolicy` using the member identity retained +from protected allocation state. It has a Karmada-scoped credential and no cell +kubeconfig. Karmada creates a `Work` only for that member and reflects cell-written +status through a Fleet-specific `ResourceInterpreterCustomization`; the +interpreter rejects status from any other member and prevents a claimed route +from changing identity. The controller refreshes only the cached-authority +deadline while every pinned input still matches. The location gateway registers +an outbound opaque route with the relay. Public status contains only its relay URL, random route, proof audience, protocol version, and gateway certificate fingerprint. The central API and controllers are not in the Redfish request/response path. @@ -58,9 +64,10 @@ selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or 2. Admission retains the authenticated principal. The controller resolves the current claim UID and exact active allocation, enforces limits, and persists the protected binding before projection. -3. The projector checks the authoritative allocation on every refresh. The - location gateway establishes an outbound relay route and publishes non-secret - rendezvous status back through the projector. +3. The projector checks the authoritative allocation on every refresh, creates a + Karmada hub copy and exact-member policy, and waits for status from that member. + The gateway reads only its cell-local copy, establishes an outbound relay + route, and writes non-secret rendezvous status to that copy. 4. The plugin consumes the route, verifies the pinned TLS identity, proves its admitted private key, and opens the loopback Redfish service. 5. Before a boot or reset effect, the gateway fsyncs an operation containing the @@ -72,10 +79,13 @@ selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or 6. A lost adapter response becomes `Unknown`; replaying the exact request returns the existing task without a second adapter call. Failed or unknown effects are never rewritten as success. -7. Expiry, public deletion, allocation release, or changed binding inputs closes - the location stream. Release writes a terminal revocation annotation so later - claim-name reuse or record reactivation cannot resurrect the session. If the - location cannot confirm deletion, the central cleanup condition is `Unknown`. +7. Expiry, public deletion, allocation release, or changed binding inputs changes + the hub copy's desired state to `Revoked`. Karmada carries the fence to the + selected cell; the gateway closes the stream and writes `CleanupConfirmed` + before the controller removes the policy and hub copy. Release also writes a + terminal revocation annotation so later claim-name reuse or reactivation cannot + resurrect the session. Deletion alone is never teardown proof; if the cell + cannot acknowledge the fence, central cleanup is `Unknown`. ## API and deployment artifacts @@ -85,7 +95,8 @@ profile, key encoding, and TTL. Conditions carry `observedGeneration`, explicit reasons, and true/false/unknown outcomes. RBAC is in `config/rbac`; controller and location workloads are in -`config/manager` and `config/location`. Containers run as non-root with read-only +`config/manager` and `config/location`. `config/federation` contains the Karmada +status interpreter and hub-only projector RBAC. Containers run as non-root with read-only root filesystems, no added Linux capabilities, and `RuntimeDefault` seccomp. NetworkPolicy permits the outbound relay, the one private BMC address, DNS, and the Kubernetes API; it does not expose gateway ingress. Metrics cover admission, @@ -98,8 +109,8 @@ The declared DMTF interoperability profile is ## Reproducible Linux environment -The qualified prerequisite is Linux with Docker Engine and Compose v2, Kind, kubectl, Go 1.26.4, -Task, jq, OpenSSL, and curl. KVM is used when `/dev/kvm` is available; otherwise +The qualified prerequisite is Linux with Docker Engine and Compose v2, Kind, +kubectl, Helm, Go 1.26.4, Task, jq, OpenSSL, and curl. KVM is used when `/dev/kvm` is available; otherwise the same real libvirt domain runs with QEMU software emulation. There is no in-memory or static-JSON BMC fallback. The scripts can also attempt the QEMU path on Docker-backed macOS for development, but CI qualification remains Linux. @@ -107,6 +118,8 @@ on Docker-backed macOS for development, but CI qualification remains Linux. `task e2e:up` builds and starts: - management and location Kind clusters; +- pinned Karmada 1.16.0 in the management cluster, with the location Kind + cluster registered as a member; - locally built controller, relay, and gateway images; - a privileged test-only Ubuntu 24.04 container running libvirt/QEMU and pinned sushy-tools 2.2.0; @@ -116,6 +129,12 @@ on Docker-backed macOS for development, but CI qualification remains Linux. Kind node; and - pinned DMTF Python Redfish client and validator tools. +The harness is repository-local and does not currently consume +`datum-cloud/test-infra`. Production/environment installation is expected to be +owned there (or in `infra`) once hub identity, member registration, and location +registration contracts are selected. This is a prototype choice, not a proposal +change. + The sushy port accepts only the location node address. The customer process sees only loopback ports for the relay and local Redfish connector. The default CI profile relies on this isolated internal network. After `e2e:up`, the separate @@ -136,7 +155,10 @@ The test calls the actual `datumctl fleet ...` command. A repository-local test Datum session stores synthetic service-account tokens through datumctl's file keyring format, after which the plugin must still call datumctl's credential helper. `e2e:up` explicitly trusts the locally built plugin by its path and SHA-256 -using datumctl's unmanaged-plugin trust command. It exercises generic DMTF client login, profile narrowing, distinct RBAC, +using datumctl's unmanaged-plugin trust command. The test requires a real Karmada +`Work` in `karmada-es-fleet-location-e2e`, verifies the hub received the selected +cell's route status, and proves management has no direct location credential. It +exercises generic DMTF client login, profile narrowing, distinct RBAC, per-claim and per-project limits, one-shot rendezvous, real PXE and libvirt power effects, DMTF validators, central API loss and freshness failure, release fencing, claim recreation, route isolation, response-loss recovery, and bounded BMC errors. @@ -149,11 +171,14 @@ Validator versions are `redfish` 3.4.2, ## Troubleshooting Run `task e2e:diagnostics` before teardown. It captures both clusters' resources, -events and logs, protected/public session state, libvirt domain state/XML, virtual +events and logs, Karmada clusters/Works/bindings and hub session state, +protected/public session state, libvirt domain state/XML, virtual BMC logs, validator reports, acceleration selection, and PXE callbacks. - A gateway stuck on `RelayUnavailable` usually indicates relay DNS/token or NetworkPolicy failure in the location cluster. +- A missing cell projection: inspect the hub `PropagationPolicy`, the Work in + `karmada-es-`, member `Ready`, and the Fleet status interpreter. - `BMCUnavailable` is intentionally bounded; inspect the gateway and virtual-BMC diagnostics rather than expecting a private address in the customer response. - No PXE callback: inspect `allocated-console.log`, libvirt network state, and the @@ -174,6 +199,11 @@ contract. Important gaps are: - Delegated Kubernetes authentication/RBAC models the intended Compute/Milo pattern, but the production Datum API aggregation and IAM permission names are not selected. +- Karmada projection and status aggregation are implemented and exercised, but + the prototype stores the member name directly in the protected synthetic + allocation. Production needs an authoritative location-to-member registration + controller, credential rotation, HA operations, failover policy, and + environment packaging in `test-infra`/`infra`. - The relay is a small Fleet-specific opaque TCP rendezvous with inner TLS, not Compute's maintained relay deployment. A shared public transport package and operational ownership decision are still required; Fleet does not import diff --git a/hack/e2e/diagnostics.sh b/hack/e2e/diagnostics.sh index 8ff78742..35846dca 100755 --- a/hack/e2e/diagnostics.sh +++ b/hack/e2e/diagnostics.sh @@ -17,6 +17,10 @@ for cluster in management location; do fi fi done +if [[ -f "${E2E_DIR}/karmada.kubeconfig" ]]; then + kubectl --kubeconfig "${E2E_DIR}/karmada.kubeconfig" get clusters,works.work.karmada.io,resourcebindings.work.karmada.io -A -o yaml >"${OUT}/karmada-resources.yaml" 2>&1 || true + kubectl --kubeconfig "${E2E_DIR}/karmada.kubeconfig" get projectedmachinemanagementsessions,propagationpolicies -A -o yaml >"${OUT}/karmada-fleet.yaml" 2>&1 || true +fi docker logs fleet-e2e-virtual-bmc >"${OUT}/virtual-bmc.log" 2>&1 || true docker exec fleet-e2e-virtual-bmc virsh list --all >"${OUT}/libvirt-domains.txt" 2>&1 || true docker exec fleet-e2e-virtual-bmc virsh dumpxml allocated >"${OUT}/allocated-domain.xml" 2>&1 || true diff --git a/hack/e2e/test.sh b/hack/e2e/test.sh index 3a963fa8..e52094e7 100755 --- a/hack/e2e/test.sh +++ b/hack/e2e/test.sh @@ -6,10 +6,11 @@ E2E_DIR="${ROOT_DIR}/.e2e" TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" MGMT_KUBECONFIG="${E2E_DIR}/management.kubeconfig" LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" +KARMADA_KUBECONFIG="${E2E_DIR}/karmada.kubeconfig" PATH="${E2E_DIR}/bin:${PATH}" export PATH -for file in "${MGMT_KUBECONFIG}" "${LOCATION_KUBECONFIG}" "${E2E_DIR}/management-ca.crt"; do +for file in "${MGMT_KUBECONFIG}" "${LOCATION_KUBECONFIG}" "${KARMADA_KUBECONFIG}" "${E2E_DIR}/management-ca.crt"; do [[ -f "${file}" ]] || { echo "missing ${file}; run task e2e:up" >&2; exit 1; } done # Each run must prove a new boot rather than accepting evidence left by an @@ -97,6 +98,18 @@ if curl --fail --silent --connect-timeout 2 http://172.30.0.10:8000/redfish/v1/ fail "customer test process reached the private sushy endpoint" fi session_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.name}') +session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsession "${session_name}" -o jsonpath='{.metadata.uid}') +# This is an actual Karmada Work proof, not a direct controller write to the +# member API: the selected cell owns the one Work containing this projection, +# and status has returned through the hub copy before the public session readied. +work_clusters=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get works.work.karmada.io -A -o json | jq -r --arg uid "${session_uid}" ' + .items[] | select(any(.spec.workload.manifests[]?; .kind == "ProjectedMachineManagementSession" and .metadata.name == $uid)) | .metadata.namespace' | sort -u) +[[ "${work_clusters}" == karmada-es-fleet-location-e2e ]] || fail "projection Work was not isolated to fleet-location-e2e: ${work_clusters}" +[[ $(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n machine-access-system get projectedmachinemanagementsession "${session_uid}" -o jsonpath='{.metadata.labels.fleet\.datumapis\.com/member-cluster}') == fleet-location-e2e ]] || fail "hub projection lost its admitted member identity" +[[ -n $(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n machine-access-system get projectedmachinemanagementsession "${session_uid}" -o jsonpath='{.status.connection.routeID}') ]] || fail "cell status was not reflected through Karmada" +if kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get secret fleet-location-kubeconfig >/dev/null 2>&1; then + fail "management cluster retained a direct location credential" +fi if kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default patch machinemanagementsession "${session_name}" --type=merge -p '{"spec":{"ttl":"10m"}}' >/dev/null 2>&1; then fail "immutable public session spec was mutable" fi @@ -184,6 +197,7 @@ spec: bindingEpoch: 1 locationUID: 44444444-4444-4444-8444-444444444444 locationRevision: location-prototype-r1 + memberCluster: fleet-location-e2e bareMetalMachineUID: "${machine_uid}" accessProfileRevision: fleet-provisioning-v1.0.0 adapterRoute: sushy-libvirt-v1 diff --git a/hack/e2e/up.sh b/hack/e2e/up.sh index 7b37346a..563a6aa9 100755 --- a/hack/e2e/up.sh +++ b/hack/e2e/up.sh @@ -8,7 +8,7 @@ MGMT_KUBECONFIG="${E2E_DIR}/management.kubeconfig" LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" export FLEET_E2E_STATE="${E2E_DIR}/virtual-bmc" -for tool in docker kind kubectl go jq openssl; do +for tool in docker kind kubectl helm curl go jq openssl; do command -v "${tool}" >/dev/null || { echo "missing required tool: ${tool}" >&2; exit 1; } done if [[ $(uname -s) != Linux ]]; then @@ -39,8 +39,81 @@ if ! docker network inspect fleet-management-e2e | jq -e '.[0].Containers | to_e docker network connect --ip 172.30.0.20 fleet-management-e2e fleet-location-e2e-control-plane fi +# Install the same pinned Karmada release used by Datum Compute. The Karmada +# API is a separate control plane hosted inside the management Kind cluster; +# only it receives the member-cluster credential. +KARMADA_VERSION=v1.16.0 +KARMADA_KUBECONFIG="${E2E_DIR}/karmada.kubeconfig" +if [[ ! -x "${E2E_DIR}/bin/karmadactl" ]]; then + os=$(uname -s | tr '[:upper:]' '[:lower:]') + arch=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/') + curl -sSfL "https://github.com/karmada-io/karmada/releases/download/${KARMADA_VERSION}/karmadactl-${os}-${arch}.tgz" | + tar -xz -C "${E2E_DIR}/bin" karmadactl + chmod 0755 "${E2E_DIR}/bin/karmadactl" +fi +if ! helm repo list 2>/dev/null | grep -q '^karmada-charts'; then + helm repo add karmada-charts https://raw.githubusercontent.com/karmada-io/karmada/master/charts +fi +helm repo update karmada-charts +if ! kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n karmada-system get deployment karmada-apiserver >/dev/null 2>&1; then + helm install karmada karmada-charts/karmada \ + --kubeconfig "${MGMT_KUBECONFIG}" --namespace karmada-system --create-namespace \ + --version "${KARMADA_VERSION}" --set apiServer.serviceType=NodePort \ + --set apiServer.nodePort=32443 --wait --timeout 10m +fi +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n karmada-system wait \ + --for=condition=Available deployment --all --timeout=10m +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n karmada-system get secret karmada-kubeconfig \ + -o jsonpath='{.data.kubeconfig}' | base64 -d >"${KARMADA_KUBECONFIG}" +karmada_cluster=$(kubectl config get-clusters --kubeconfig "${KARMADA_KUBECONFIG}" | tail -n 1) +kubectl config set-cluster "${karmada_cluster}" --kubeconfig "${KARMADA_KUBECONFIG}" \ + --server=https://127.0.0.1:32443 --insecure-skip-tls-verify=true >/dev/null +chmod 0600 "${KARMADA_KUBECONFIG}" + +for _ in $(seq 1 90); do + kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get clusters >/dev/null 2>&1 && break + sleep 2 +done +if ! kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get cluster fleet-location-e2e >/dev/null 2>&1; then + for attempt in 1 2 3 4 5; do + if "${E2E_DIR}/bin/karmadactl" join fleet-location-e2e \ + --kubeconfig "${KARMADA_KUBECONFIG}" \ + --cluster-kubeconfig "${LOCATION_KUBECONFIG}" \ + --cluster-context kind-fleet-location-e2e; then + break + fi + [[ ${attempt} -lt 5 ]] || { echo "failed to join location cluster to Karmada" >&2; exit 1; } + sleep 10 + done +fi +cp "${LOCATION_KUBECONFIG}" "${E2E_DIR}/location-internal.kubeconfig" +location_cluster=$(kubectl config get-clusters --kubeconfig "${E2E_DIR}/location-internal.kubeconfig" | tail -n 1) +location_ip=$(docker inspect fleet-location-e2e-control-plane | jq -r '.[0].NetworkSettings.Networks.kind.IPAddress') +kubectl config set-cluster "${location_cluster}" --kubeconfig "${E2E_DIR}/location-internal.kubeconfig" \ + --server="https://${location_ip}:6443" --insecure-skip-tls-verify=true >/dev/null +member_secret=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get cluster fleet-location-e2e -o jsonpath='{.spec.secretRef.name}') +member_secret_namespace=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get cluster fleet-location-e2e -o jsonpath='{.spec.secretRef.namespace}') +member_secret_namespace=${member_secret_namespace:-karmada-system} +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n "${member_secret_namespace}" create secret generic "${member_secret}" \ + --from-file=kubeconfig="${E2E_DIR}/location-internal.kubeconfig" --dry-run=client -o yaml | + kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" patch cluster fleet-location-e2e --type=merge \ + -p "{\"spec\":{\"apiEndpoint\":\"https://${location_ip}:6443\"}}" +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" label cluster fleet-location-e2e \ + topology.datum.net/location=44444444-4444-4444-8444-444444444444 --overwrite +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" wait cluster/fleet-location-e2e \ + --for=condition=Ready --timeout=180s + build_image() { local image=$1 package=$2 binary=$3 + if [[ $(uname -s) == Darwin ]]; then + mkdir -p "${E2E_DIR}/image-bin/${binary}" + env GOOS=linux GOARCH=amd64 CGO_ENABLED=0 GOCACHE="${E2E_DIR}/go-cache" \ + go build -trimpath -ldflags='-s -w' -o "${E2E_DIR}/image-bin/${binary}/${binary}" "${package}" + docker build -t "${image}:e2e" --build-arg "BINARY=${binary}" \ + -f "${TEST_DIR}/Dockerfile.prebuilt" "${E2E_DIR}/image-bin/${binary}" + return + fi docker build -t "${image}:e2e" --build-arg "PACKAGE=${package}" --build-arg "BINARY=${binary}" "${ROOT_DIR}" } build_image fleet-controller ./cmd/fleet-controller fleet-controller @@ -52,13 +125,17 @@ kind load docker-image fleet-gateway:e2e fleet-relay:e2e --name fleet-location-e kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/crd" kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/crd" +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply \ + -f "${ROOT_DIR}/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml" --server-side --validate=false +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply -k "${ROOT_DIR}/config/federation" --server-side --validate=false +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" create namespace machine-access-system --dry-run=client -o yaml | + kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply -f - kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/machine-management/base" kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/machine-management/base" kubectl --kubeconfig "${MGMT_KUBECONFIG}" wait --for=condition=Established --timeout=60s crd/machinemanagementsessions.fleet.datumapis.com kubectl --kubeconfig "${LOCATION_KUBECONFIG}" wait --for=condition=Established --timeout=60s crd/projectedmachinemanagementsessions.fleet.datumapis.com kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/controller.yaml" kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/controller.yaml" -kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/projector-location.yaml" relay_token=$(openssl rand -hex 32) kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create secret generic fleet-relay-token \ @@ -68,30 +145,32 @@ kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create se --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - unset relay_token -projector_token=$(kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create token fleet-projector --duration=2h) -location_ca=$(kubectl config view --kubeconfig "${LOCATION_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}') -location_ip=$(docker inspect fleet-location-e2e-control-plane | jq -r '.[0].NetworkSettings.Networks.kind.IPAddress') -cat >"${E2E_DIR}/projector.kubeconfig" <"${E2E_DIR}/federation.kubeconfig" </dev/null +fi # Docker/Lima exposes cgroup v2 to this privileged test appliance, but nested # per-domain cgroup creation is not portable across runners. Libvirt still owns # the QEMU process lifecycle; resource isolation is supplied by the container. @@ -95,7 +102,14 @@ cat >/tmp/provisioning.xml <<'XML' XML virsh net-define /tmp/provisioning.xml >/dev/null 2>&1 || true -virsh net-start fleet-provisioning >/dev/null 2>&1 || true +if [[ $(virsh net-info fleet-provisioning | awk '/Active:/ {print $2}') != yes ]]; then + virsh net-start fleet-provisioning >/dev/null +fi +for _ in $(seq 1 30); do + ip addr show virbr-pxe 2>/dev/null | grep -q '192.168.124.1' && break + sleep 1 +done +ip addr show virbr-pxe | grep -q '192.168.124.1' define_domain() { local name=$1 mac=$2 From 82531f299ac10b4931dbb5014f22f9d512842ed3 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 13:33:55 -0600 Subject: [PATCH 12/24] docs: simplify secure BMC access design --- docs/enhancements/secure-bmc-access.md | 478 +++++++++++++++++-------- 1 file changed, 330 insertions(+), 148 deletions(-) diff --git a/docs/enhancements/secure-bmc-access.md b/docs/enhancements/secure-bmc-access.md index eb314b13..9bd5e152 100644 --- a/docs/enhancements/secure-bmc-access.md +++ b/docs/enhancements/secure-bmc-access.md @@ -10,7 +10,10 @@ This enhancement proposes allocation-scoped customer access to a narrow Redfish API without exposing a BMC, its management network, or its credentials directly. It extends the provisional [Fleet design context](../design.md) and the pinned [bare-metal provisioning proposal][fleet-provisioning]. No API or behavior in -this document is implemented or verified in Fleet today. +this document is an accepted production contract. The repository contains a +[working prototype](../implementation/machine-management-prototype.md), but its +internal binding and projection schemas predate the simplified design below and +must not be treated as the proposed product API. The architecture borrows the session and data-path separation used by Datum Compute's provisional [instance shell sessions][compute-shell]: the platform @@ -22,11 +25,13 @@ components. ## Summary -Customers with an active `MachineClaim` can request a short-lived management -session for the machine allocated to that claim. Datum authenticates the caller -with the normal platform identity, authorizes the requested capability against -the current allocation, and binds the session to the consumer project, principal, -Claim UID, Machine UID, binding identifier and binding epoch. +Customers with an active consumer `Machine` can request a short-lived management +session. Datum authenticates the caller with the normal platform identity, +authorizes the requested capability against the Machine's current immutable +allocation, and resolves it to one provider `MachineCapacity` and location. +Kubernetes UIDs remain private admission evidence in the API server that issued +them; binding identifiers, binding epochs and cross-cluster UIDs are not part of +the session contract. After admission, Redfish traffic travels through an encrypted relay path to a location-local Redfish gateway. The gateway exposes a small, provider-neutral @@ -36,8 +41,9 @@ Supermicro integration, that network is expected to be reachable through an operator-managed OpenVPN connection. Customers do not receive VPN access, a BMC address, or BMC credentials. -The central API handles session admission, binding, status, audit and revocation. -It does not proxy each Redfish request. Relay capacity and location gateways +The central API handles session admission, allocation resolution, status, audit +and revocation. It does not proxy each Redfish request. Relay capacity and +location gateways scale independently, and a location can continue serving already admitted, still-valid sessions during a bounded control-plane interruption. @@ -56,7 +62,7 @@ service to maintain routes into every management network. Fleet instead needs an access contract that: -- reuses the existing MachineClaim allocation authority; +- reuses the existing customer Machine allocation authority; - preserves a standard Redfish API for customer provisioning software; - keeps BMC endpoints, credentials and management networks private; - routes once when a session is admitted instead of globally routing every @@ -66,8 +72,8 @@ Fleet instead needs an access contract that: ## Goals -- Let an authorized human or service identity operate the machine currently - allocated to its `MachineClaim` through a documented Redfish interoperability +- Let an authorized human or service identity operate its active customer + `Machine` through a documented Redfish interoperability profile. - Support customer-controlled PXE provisioning through one-time boot selection and bounded power actions before full Fleet installation automation exists. @@ -102,18 +108,20 @@ Fleet instead needs an access contract that: The consumer has: -- an active `MachineClaim` bound through Fleet's allocator; -- an IAM grant that permits creation of management sessions for that claim; +- an active `Machine` allocated through Fleet's allocator; +- an IAM grant that permits creation of management sessions for that Machine; - a machine offering that advertises the requested Redfish access profile; and - a supported client connector, supplied as a CLI command, sidecar or SDK component. -The caller never supplies a Machine, BMC address, location route or provider -credential. Those are resolved from the claim's private retained binding. +The caller supplies only the customer Machine name. It never supplies the +provider `MachineCapacity`, `Device`, BMC address, location route or provider +credential. Fleet resolves those from protected allocation state. ### Manual access -The exact command is illustrative: +The first supported connector is the first-party `datumctl-fleet` plugin and is +dispatched through the real `datumctl` executable: ```console $ datumctl fleet machine-management proxy db-01 @@ -137,7 +145,7 @@ the transport private key or a reusable BMC credential to disk by default. ### Customer provisioning automation An automated provisioner uses a Datum service identity to create a session for a -MachineClaim in its project. A connector sidecar owns the ephemeral transport +Machine in its project. A connector sidecar owns the ephemeral transport key and presents the provisioner with the same Redfish base URL for the session's lifetime. The provisioner can then: @@ -164,6 +172,24 @@ future deployment may expose the same gateway through regional HTTPS ingress and short-lived scoped credentials. That is a transport alternative, not a reason to change the allocation, authorization, operation or Redfish contracts. +### Control-plane ownership + +| State | Authoritative control plane | +| --- | --- | +| Customer `Machine` and `MachineManagementSession` | Customer Milo project API | +| Provider `Device` and `MachineCapacity` | Provider Milo project API | +| Immutable `MachineAllocation` and private admission evidence | Fleet management GKE cluster | +| Karmada policy and hub copies | Karmada control plane in the Fleet management cluster | +| Safe `Device`, `MachineCapacity` and session copies | Selected location member cluster | +| Owned-hardware enrollment, operation journal and materialized Secrets | Selected location member cluster | +| Authoritative BMC credential and trust material | Regional environment secret manager | + +Milo supplies project identity, IAM, service enablement and quota. The Fleet +management GKE cluster runs the trusted controllers and Karmada hub; it is not a +customer Kubernetes API and has no BMC-network route. A location cluster has no +consumer-project credential and cannot make or change the global allocation +decision. + ## Proposed Redfish profile The gateway presents a virtual Redfish service rather than forwarding the BMC's @@ -187,6 +213,12 @@ network configuration, virtual media, log deletion, OEM actions, arbitrary `Actions` targets or links outside the allowlisted virtual resource tree. Later profiles require explicit review, capability publication and authorization. +The initial `Provisioning` profile accepts one-time `Pxe` and `Hdd` boot targets. +It accepts `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart` and +`ForceRestart` reset types only after the owned-hardware adapter qualifies the +corresponding BMC behavior. An unsupported target or reset type returns a +Redfish extended error; the gateway never substitutes a more disruptive action. + Redfish supports HTTP Basic, Redfish login sessions, and optional delegated OAuth 2.0 bearer authentication. This proposal does not depend on the physical BMC implementing Datum OAuth. Platform identity authorizes creation of the Fleet @@ -198,68 +230,105 @@ path; the gateway authenticates to the BMC with operator-held credentials. ### Request and data paths ```text - control and status path - client ── OAuth ──> Fleet project API ──> session admission and binding - │ │ - │ v - │ location-local session projection - │ │ - │ encrypted Redfish data path v - └────────> Datum relay ───────────────> location Redfish gateway - │ - │ private target and credential - v - OpenVPN / management network - │ - v - BMC + control and status path + client ── OAuth ──> Fleet project API ──> session admission + │ │ + │ Fleet management GKE v + │ Karmada hub ──> exact location member + │ │ + │ encrypted Redfish data path v + └─────────> Datum relay ──────────────> location Redfish gateway + │ + │ owned-hardware adapter + v + private management network + │ + v + BMC ``` -The exact projection mechanism is not selected here. It must deliver the bound -session and revocations to the authoritative location without giving the -location agent broad credentials to the consumer project API. Status returns -through the same controlled synchronization contract. A location cannot choose -itself or replace an already bound endpoint through status. +Karmada is the selected control-plane delivery mechanism. Fleet creates a +minimal location representation of the admitted session in the Karmada hub and +an exact-member propagation policy selected from protected Location +configuration. Karmada delivers the session and revocations without giving the +location credentials to the consumer project API. A Fleet resource interpreter +accepts status only from the selected member. The member cannot choose itself, +change centrally owned session input or redirect the session through status. +Karmada `Work`, `ResourceBinding` and propagation resources are federation +implementation details, not Fleet product resources. ### Responsibilities - **Fleet project API:** authenticates the user or service identity, authorizes the requested session, validates immutable input and exposes lifecycle status. -- **Management-session admission:** resolves the private active allocation, - checks current capability and conflicts, retains the exact binding and chooses - the authoritative location from trusted allocation state. -- **Session projection:** carries the least-privileged location-local session - copy and revocation state. It is not the Redfish request path. +- **Management-session admission:** resolves the active customer Machine through + its immutable allocation to one provider `MachineCapacity`, checks current + capability and conflicts, retains private admission evidence, and chooses the + authoritative location from trusted allocation state. +- **Karmada session delivery:** carries the least-privileged resolved session and + revocation state to exactly one location. It is not another authorization + decision and is not the Redfish request path. - **Relay endpoint:** maintains outbound connectivity from the location and forwards an end-to-end encrypted stream. It has no BMC credential and may reach only the location gateway. - **Location Redfish gateway:** verifies possession of the session key, consumes or attaches the session, enforces its profile, virtualizes Redfish resources, retains mutating operations and calls the selected adapter. -- **BMC adapter:** translates the profile to a qualified physical BMC, holds or - obtains its credentials from location-scoped secret custody, and normalizes - supported observations and results. +- **Datum owned-hardware adapter:** resolves the selected `MachineCapacity` + through its immutable `Device`, verifies the enrolled physical identity, + translates the profile to a qualified BMC, obtains credentials from + location-scoped secret custody, and normalizes observations and results. - **Operation journal:** durably records admitted mutating requests, exact - binding, target, normalized request body, idempotency identity, execution route - and evidence before effects. + session and asset preconditions, normalized request body, idempotency + identity, privately resolved target and evidence before effects. The gateway and adapter may be one deployment initially, but their responsibilities and credential boundaries remain distinct. The relay endpoint must not become an unrestricted HTTP CONNECT service to the management network. +### End-to-end sequence + +1. `datumctl-fleet` generates an ephemeral Ed25519 key pair and creates a public + `MachineManagementSession` referring to the customer Machine by name. +2. Milo authenticates the project context and authorizes the distinct session + create permission. Ordinary Machine read access is insufficient. +3. Fleet resolves the exact live customer Machine through its immutable + `MachineAllocation` to one provider `MachineCapacity`, its immutable Device + and authoritative Location. It retains the decision before reporting + admission success. +4. Fleet creates a minimal `LocationMachineManagementSession` in the Karmada + hub and targets the Location's exact member cluster through protected + configuration. +5. The cell verifies that its safe MachineCapacity and Device copies match and + that the owned-hardware adapter currently reports management availability for + that physical identity. +6. The gateway registers a one-use outbound relay route and returns only + non-secret rendezvous status through Karmada. Fleet reflects that status to + the public session. +7. The connector pins the gateway certificate, presents a timestamped signed + proof for the route and keeps the private key in memory. The first valid + connector consumes the route. +8. The gateway exposes the virtual Redfish profile. Before each mutation, the + location journals the exact accepted request and physical preconditions; the + adapter then resolves local enrollment and reaches the BMC. +9. Expiry, public deletion or Machine release changes the location session to + `Revoked`. The cell closes the stream and reports cleanup; missing confirmation + remains `Unknown` and prevents unsafe capacity reuse. + ### Authentication and authorization Session admission uses Datum's existing human and service identity flows. IAM defines a management-session create permission separately from ordinary -MachineClaim read or update. Admission evaluates that permission against the -consumer project and target MachineClaim and then resolves the private binding; -possession of a claim name or UID is not authorization. +Machine read or update. Admission evaluates that permission against the +consumer project and target Machine and then resolves its private allocation; +possession of a Machine name or locally observed UID is not authorization. -The client generates an ephemeral Ed25519 key pair. Only the public key enters -the proposed session resource. On connection, the gateway verifies a signature -covering at least the session UID, protocol version, connection timestamp and -gateway audience. The first accepted connection consumes the connection window. -Replay, a changed route or a second concurrent connector is rejected. +The client generates an ephemeral Ed25519 key pair. The private key remains in +client memory and only the public key enters the session resource. On +connection, the gateway verifies a domain-separated signature covering at least +the one-use route ID, protocol version, timestamp, nonce and gateway audience. +The first accepted connection consumes the connection window. Replay, a changed +rendezvous or a second concurrent connector is rejected. The admitted access profile is selected from provider-published capabilities and the caller's grant. The caller cannot supply an arbitrary path allowlist or ask @@ -268,34 +337,89 @@ accepted; it cannot expand the offering. The physical BMC sees only the gateway's location-scoped identity. BMC credentials must never appear in the public session, its status, audit events, client errors -or relay configuration. Credential rotation does not change Machine identity or +or relay configuration. Credential rotation does not change the customer +Machine, provider `MachineCapacity` or physical Device identity and does not create a customer session. -### Binding and routing +### Allocation resolution and routing Routing is a one-time admission decision, not a lookup on each Redfish request. -The protected session binding retains: - -- consumer and provider Project UIDs; -- requesting principal identity; -- MachineClaim name and UID; -- Machine name and UID; -- allocation binding identifier and epoch; -- selected location UID and location-service revision; -- selected BareMetalMachine and adapter identity; -- admitted access-profile revision; -- client public key, creation time, connect deadline and expiry; and -- session and operation correlation identifiers. - -The consumer-visible object does not reveal the provider project, Machine, -BareMetalMachine, BMC endpoint or adapter route. The location gateway resolves -the retained target through its private provider records and verifies that every -request still matches the projected binding epoch. - -If an allocation moves, is released or is replaced, a new session is required. -The old endpoint cannot be rebound to the successor. A location-revision change -requires controlled handover or session replacement; mutable discovery must not -silently redirect an active session. +The customer Machine's allocation is an immutable, service-owned resource whose +generated Kubernetes name is its identity. Release is terminal; Fleet never +reactivates or retargets that allocation, so the session contract needs neither +a duplicated binding ID nor an epoch. + +For Datum-owned hardware, the selected provider `MachineCapacity` has an +immutable `deviceRef`. Hardware replacement creates a new `Device` and +`MachineCapacity`; Fleet never redirects the old capacity name to another +physical asset. Credential, certificate, endpoint and private-route rotation may +change while the same enrolled Device identity remains. These implementation +changes do not require a management revision in the session. + +Admission privately retains the authenticated principal, consumer and provider +project identities, the exact local source-object identities used during the +decision, the allocation resource name, selected `MachineCapacity` and +`Device`, client public key, deadlines and audit correlation. Local Kubernetes +UIDs may be used as same-API-server recreation preconditions, but they are not +authored references and never cross through Karmada. + +The Karmada-delivered location session contains only the provider +`MachineCapacity` name, access profile, client public key, deadlines and desired +state. The owned-hardware adapter resolves the capacity through its immutable +Device relationship and private enrollment. Neither the public nor location +session contains a BMC endpoint, physical system identifier, Secret reference, +adapter route or Karmada member name. + +If the allocation is released, the session is revoked. Hardware replacement +requires new capacity, allocation and session resources. The old endpoint cannot +be rebound to a successor, and provider discovery cannot silently redirect an +active session. + +### Owned-hardware enrollment and secret custody + +The Fleet management cluster intentionally has no route to location BMC +networks. Each location's Datum owned-hardware adapter maintains private +enrollment keyed by the provider `MachineCapacity` and its immutable `Device`. +Enrollment retains the BMC endpoint, physical Redfish system identifier, +qualified adapter configuration and verified physical identity. These values are +provider-backend state, not Fleet product resources. + +Before a capacity can become eligible, Fleet mirrors a safe, read-only location +copy of its provider `MachineCapacity` and registered `Device` through Karmada +to the authoritative member. The provider-project objects remain authoritative; +the copies preserve names and immutable `deviceRef` but have their own local +Kubernetes metadata and no cross-cluster UID relationship. The location writes +only management observations, which Karmada returns through a constrained status +interpreter. This gives the adapter the MachineCapacity-to-Device association without +placing provider-project credentials in the cell. + +BMC credentials and trust material are authoritative in the environment's +regional secret manager. External Secrets Operator may materialize them into a +protected namespace in the location cluster. Only the owned-hardware adapter or +another explicitly selected provider executor may read those Secrets. The +gateway submits typed operations to the adapter and cannot read physical BMC +credentials itself. Relay credentials, gateway transport identity and BMC +credentials are separate. + +The materialized management Secret is associated with the local Device copy by +a service-owned label or adapter index, not by a customer-authored reference. +It may contain the private endpoint, physical system identifier, credential and +CA bundle. Secret names, contents and resource versions remain local provider +state and never enter MachineCapacity or session specs. + +Enrollment is observational until explicitly enabled for management. The +adapter verifies that BMC-reported physical identity matches the registered +Device before reporting `ManagementAvailable`. Registration, credential +materialization or a successful observation does not authorize a power, boot, +cleaning or installation effect; the adapter executes only a retained admitted +operation. + +Endpoint, certificate, credential and private-route rotation may update the +same enrollment while physical identity remains unchanged. If the enrolled BMC +reports a different Device identity, management becomes `Unknown` or `False`, +active sessions close, and mutations fail closed. The adapter never follows a +customer URL, Host header, returned BMC link or guessed Redfish identifier to +select a physical target. ### Session lifecycle @@ -310,11 +434,11 @@ that any requested hardware state was reached. `Connected` means the ephemeral client key was accepted. Session expiry and command outcome remain separate. Deleting or closing a session immediately denies new central admission and -propagates revocation to the location. Release of the MachineClaim has higher -priority: it fences new operations, revokes all sessions for that binding and -waits for active gateways to confirm teardown or records the result as unknown. -The allocator must not make the Machine available to a later consumer until the -release contract has accounted for those sessions. +propagates revocation to the location. Release of the customer Machine has +higher priority: it fences new operations, revokes all sessions for its +allocation and waits for active gateways to confirm teardown or records the +result as unknown. The allocator must not make the `MachineCapacity` available +to a later consumer until the release contract has accounted for those sessions. The gateway fails closed when its allocation/session projection exceeds its freshness limit. A partition does not turn cached authorization into an @@ -327,12 +451,13 @@ Read-only Redfish requests can be served from current BMC observations within the session profile. Before forwarding a boot or power mutation, the gateway retains a protected operation containing: -- the session and allocation identities; +- the location session resource name; +- the selected `MachineCapacity` and immutable `Device` names; - the normalized Redfish method, virtual target and exact accepted body; -- the physical target resolved by the adapter; -- an idempotency identity and operation epoch; -- current binding, session and conflict preconditions; and -- the selected adapter route and credential revision without secret material. +- the physical target and enrolled identity resolved privately by the adapter; +- an idempotency key derived from the operation resource name; +- current session, asset and conflict preconditions; and +- execution evidence without secret material. The operation journal is the authority for the effect. A gateway process lease or an open relay stream is not sufficient. Installation, release, power intent @@ -361,13 +486,17 @@ and mutations rather than falling back to raw BMC access. ### Audit and observability The project activity log records session creation with the requesting human or -service identity. Lifecycle events record the session UID, project, claim UID, -access profile, bound location, start and end times, and terminal reason. It must -not record private keys, session-local bearer values, BMC credentials, raw -provider endpoints or secret-bearing response bodies. - -Every mutating request receives a Fleet operation correlation identifier. Audit -records include its normalized operation type and outcome. Request bodies are +service identity. Lifecycle events record the session resource name, project, +customer Machine name, access profile, bound location, start and end times, and +terminal reason. Private same-API-server object identities may be retained in +protected admission evidence but are not customer audit fields. Audit must not +record private keys, session-local bearer values, BMC credentials, raw provider +endpoints or secret-bearing response bodies. + +Every mutating request creates an operation with a generated Kubernetes name; +that name is also its audit correlation value rather than being duplicated in +spec. Audit records include its normalized operation type and outcome. Request +bodies are retained in protected operation state when needed for recovery; customer-facing activity uses a safe summary. Session byte streams and Redfish response bodies are not recorded by default. @@ -385,9 +514,9 @@ session. It is a consumer-project resource and does not expose a raw BMC handle. ### MachineManagementSession -Each resource represents one short-lived connection to one immutable claim -binding. The spec is immutable; changing the claim, key, profile or TTL requires -a new resource. +Each resource represents one short-lived connection for one active customer +Machine. The spec is immutable; changing the Machine, key, profile or TTL +requires a new resource. ```yaml apiVersion: fleet.datumapis.com/v1alpha1 @@ -396,7 +525,7 @@ metadata: generateName: db-01- namespace: acme spec: - machineClaimRef: + machineRef: name: db-01 protocol: Redfish accessProfile: Provisioning @@ -404,10 +533,11 @@ spec: ttl: 15m status: connection: - endpointID: abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 - relayURLs: - - https://relay.us-central-1.example.invalid - target: redfish-gateway-0.machine-access-system.svc:8443 + relayURL: https://relay.us-central-1.example.invalid + routeID: abcdef0123456789abcdef0123456789 + gatewayAudience: fleet-redfish-iad1 + gatewayCertSHA256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + protocolVersion: redfish-v1alpha1 connectBefore: "2026-11-11T19:01:00Z" expiresAt: "2026-11-11T19:15:00Z" conditions: @@ -419,41 +549,88 @@ status: lastTransitionTime: "2026-11-11T19:00:01Z" ``` -`machineClaimRef.name` is a consumer lookup handle in the authenticated project; -the consumer does not supply or manage allocation identities. During session -admission, Fleet resolves the name and retains the current Claim UID, Machine UID, -binding identifier and binding epoch in the protected session binding before the -session can become Ready or authorize an effect. Admission requires the resolved -claim to be bound and active. If the claim or binding changes before that commit, -admission fails or restarts resolution rather than following stale state. A later -claim that reuses the same name cannot receive an already admitted session. +`machineRef.name` identifies the customer Machine in the authenticated project; +the consumer does not supply or manage allocation or provider identities. During +session admission, Fleet resolves the exact live Machine and its immutable +allocation before the session can become Ready or authorize an effect. If the +Machine or allocation changes before that commit, admission fails or restarts +resolution rather than following stale state. A later Machine that reuses the +same name cannot receive an already admitted session because local object +identity is checked during admission and the old allocation is terminal. `protocol` is initially only `Redfish`. `accessProfile` refers to a versioned platform-defined profile; arbitrary methods or paths are not accepted in the spec. `ttl` begins no later than connection acceptance and is capped by policy. `status.connection` is rendezvous information, not a bearer capability. Holding -the matching ephemeral private key is required to connect. The target is a -virtual gateway service and must not contain a BMC address. Generally readable -status contains neither the private allocation binding nor credentials. +the matching ephemeral private key is required to connect. The rendezvous +reaches a virtual gateway service and must not contain a BMC address. Generally +readable +status contains neither the private allocation nor credentials. Deleting the resource requests revocation. Finalization or equivalent retained -service state keeps the private session binding until the location confirms +service state keeps the private admission evidence until the location confirms teardown or the platform records that confirmation as unknown. Deletion alone is not teardown evidence. -### Protected session binding +### Private admission evidence and location representation + +Admission durably retains private evidence outside the consumer project's +deletion domain. That persistence is a service implementation boundary, not a +customer API or a second access grant. It records the authenticated decision and +the exact immutable allocation and provider capacity selected at that time. Only +the admission service writes it. + +Fleet then creates one internal `LocationMachineManagementSession` in the +Karmada hub. Its spec contains only `machineCapacityRef.name`, `accessProfile`, +`clientPublicKey`, `connectBefore`, `expiresAt`, a shorter refreshed +`freshUntil`, and monotonic `desiredState: Active|Revoked`. The authority fields +are immutable; only `freshUntil` may advance within `expiresAt`, and +`desiredState` may move from `Active` to `Revoked`. The selected location can +write conditions and non-secret rendezvous status but cannot alter spec. + +```yaml +apiVersion: internal.fleet.datumapis.com/v1alpha1 +kind: LocationMachineManagementSession +metadata: + name: session-01jcc5 + namespace: machine-access-system +spec: + machineCapacityRef: + name: iad1-r12-srv01 + protocol: Redfish + accessProfile: Provisioning + clientPublicKey: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + connectBefore: "2026-11-11T19:01:00Z" + expiresAt: "2026-11-11T19:15:00Z" + freshUntil: "2026-11-11T19:02:00Z" + desiredState: Active +status: + connection: + relayURL: https://relay.us-central-1.example.invalid + routeID: abcdef0123456789abcdef0123456789 + gatewayAudience: fleet-redfish-iad1 + gatewayCertSHA256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + protocolVersion: redfish-v1alpha1 + conditions: + - type: Ready + status: "True" + reason: RelayRegistered + observedGeneration: 1 + lastTransitionTime: "2026-11-11T19:00:01Z" +``` -Admission creates a private service-owned binding record outside the consumer -project's deletion domain. It contains the routing and fencing fields listed in -[Binding and routing](#binding-and-routing). Only the session admission service -can create it; the location gateway can observe only the sessions routed to its -location and can update only their location-local status. +The propagation policy, member-cluster name and private admission evidence are +not fields on this resource. Fleet owns those in its management-plane delivery +configuration. Fleet generates a globally unique Kubernetes name for the +location copy; it does not duplicate that name as a `sessionID` field. The +profile name is an immutable versioned contract within the API version; +incompatible profile behavior requires a new profile name or API version rather +than a mutable revision field. -This record is intentionally separate from `MachineClaim.status`. A public -session may be short-lived or deleted while its audit, revocation and release -obligations remain. The claim remains the allocation authority; creating a -session cannot alter the binding or machine lifecycle. +Private evidence survives long enough to complete revocation, release and audit +even if the public session or customer project is deleted. Creating a session +cannot alter the Machine allocation or lifecycle. ### Permission model @@ -467,7 +644,7 @@ The initial permission model should distinguish at least: Default viewer access does not imply session creation. Service identities receive an explicit grant. The admission service rechecks current source capability, -claim authority and allocation state at creation; an old IAM decision or copied +Machine authority and allocation state at creation; an old IAM decision or copied session object is not sufficient. ### API and Redfish errors @@ -481,16 +658,20 @@ BMC and unknown execution outcome without disclosing the physical route. ## Security considerations - **Compromised customer credential:** IAM limits session creation to authorized - claims; quotas, short connection windows and activity alerts bound abuse. + customer Machines; quotas, short connection windows and activity alerts bound + abuse. - **Stolen ephemeral private key:** keys live only in connector memory, have a - short lifetime and are bound to one session, gateway audience and allocation. + short lifetime and are bound to a single one-use route, gateway audience and + admitted location copy. - **Compromised relay:** end-to-end encryption prevents the relay from reading or modifying Redfish traffic; the relay holds no allocation or BMC credential. -- **Replay or stale allocation:** session UID, Claim UID, Machine UID, binding - epoch, key proof, timestamps and gateway audience are checked together. Release - propagates revocation and blocks reuse until sessions are accounted for. -- **Confused deputy:** the gateway resolves targets only from retained bindings, - never from a customer URL, host header, Redfish link or BMC identifier. +- **Replay or stale allocation:** the immutable session input, first-connector + consumption, key proof, timestamps, nonce, gateway audience and current + Karmada-delivered state are checked together. Release propagates revocation and + blocks capacity reuse until sessions are accounted for. +- **Confused deputy:** the gateway resolves targets only from the trusted + location session and owned-hardware enrollment, never from a customer URL, + host header, Redfish link or BMC identifier. - **Compromised location gateway:** network policy and credentials limit it to machines in its location. Credential isolation and one authoritative adapter reduce blast radius; a compromised gateway remains a high-severity management @@ -515,8 +696,8 @@ BMC and unknown execution outcome without disclosing the physical route. hardware over the management OpenVPN path. Verify correct-host identity, one-time PXE boot, supported power actions, task recovery, credential rotation, rate limits and network isolation. -4. **Allocation integration:** authorize sessions against real MachineClaims and - retain the private binding epoch. Exercise concurrent allocation/release, +4. **Allocation integration:** authorize sessions against real customer Machines + and immutable MachineAllocations. Exercise concurrent allocation/release, project deletion, location loss, stale session replay and uncertain BMC responses. 5. **Customer pilot:** enable an explicit IAM grant and session quota for selected @@ -531,9 +712,11 @@ BMC and unknown execution outcome without disclosing the physical route. - The customer cannot discover or reach the BMC address, management VPN, another machine, an OEM endpoint or an unlisted Redfish field/action through the gateway. - Human and service identities use normal Datum authentication; an explicit IAM - grant and current MachineClaim binding are required for session creation. -- Two claims, projects or overlapping classes cannot cause a session to bind the - wrong Machine. A reused claim name or stale binding epoch is rejected. + grant and current customer Machine allocation are required for session + creation. +- Two customer Machines, projects or overlapping classes cannot cause a session + to bind the wrong `MachineCapacity`. Reuse of a customer Machine name cannot + inherit a prior session or terminal allocation. - Release and project deletion deny new operations, actively close sessions and prevent capacity reuse until teardown is confirmed or represented as unknown. - A mutating request is retained before the BMC effect. Lost responses and gateway @@ -545,25 +728,24 @@ BMC and unknown execution outcome without disclosing the physical route. ## Open questions -- Whether the first connector is embedded in `datumctl`, shipped as a sidecar, - exposed through an SDK, or provided in more than one form. - Which existing Redfish clients must be supported and what loopback TLS and - session-login behavior they require. -- The exact first-version access profile, allowed `ResetType` values and boot - targets for each qualified Supermicro model and firmware revision. + session-login behavior they require beyond the qualified DMTF client and + validators used by the prototype. +- Which Datum-owned BMC models and firmware revisions qualify each operation in + the initial `Provisioning` profile. - Whether an established Datum Connect deployment can satisfy browser, CLI and service automation requirements, or whether a dedicated relay profile is needed. -- The session projection and revocation transport, freshness limit and behavior - during control-plane or location partitions. +- The production Karmada topology, member-registration ownership, refresh + interval and maximum `freshUntil` window during control-plane partitions. - Durable storage and concurrency boundaries between Fleet admission, the location operation journal and provider adapters. - Whether future regional HTTPS ingress is needed for customers that cannot run a connector, and how its bearer credentials would be scoped and revoked. - Session quotas, TTLs, per-machine concurrency, request rate limits and activity alert thresholds for the initial pilot. -- Ownership and deployment boundaries for the gateway, relay endpoint, BMC - adapter and management OpenVPN connection. +- Production ownership and deployment boundaries for the gateway, relay + endpoint, owned-hardware adapter and optional management OpenVPN connection. ## References From 2f886b6ab9c4f5692cb6496032d2b9e28287ab29 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 15:45:36 -0600 Subject: [PATCH 13/24] feat: align secure BMC access with machine allocations --- Taskfile.yaml | 2 +- api/v1alpha1/groupversion_info.go | 28 --- api/v1alpha1/types.go | 227 ------------------ api/v1alpha1/zz_generated.deepcopy.go | 58 ----- cmd/fleet-controller/main.go | 4 +- cmd/fleet-gateway/main.go | 16 +- ...tumapis.com_machineallocationbindings.yaml | 128 ---------- .../fleet.datumapis.com_machineclaims.yaml | 116 --------- ....com_machinemanagementsessionbindings.yaml | 82 +++---- ...tumapis.com_machinemanagementsessions.yaml | 13 +- ...om_projectedmachinemanagementsessions.yaml | 91 +++---- config/crd/kustomization.yaml | 2 - config/location/access.yaml | 7 +- config/rbac/controller.yaml | 16 +- docs/enhancements/secure-bmc-access.md | 7 +- .../machine-management-prototype.md | 78 +++--- hack/e2e/diagnostics.sh | 2 +- hack/e2e/openvpn-up.sh | 5 +- hack/e2e/test.sh | 123 ++++++---- hack/e2e/up.sh | 20 +- {api => internal/api/session}/v1alpha1/doc.go | 2 +- internal/api/session/v1alpha1/types.go | 204 ++++++++++++++++ internal/api/session/v1alpha1/types_test.go | 76 ++++++ internal/cmd/fleet/root.go | 25 +- internal/controller/admission.go | 2 +- internal/controller/admission_test.go | 4 +- internal/controller/projection.go | 48 +++- internal/controller/projection_test.go | 52 ++-- internal/controller/session.go | 150 ++++++++---- internal/controller/session_test.go | 62 +++-- internal/gateway/gateway.go | 99 ++++++-- internal/gateway/gateway_test.go | 41 +++- internal/journal/journal.go | 41 ++-- internal/journal/journal_test.go | 2 +- internal/redfish/handler.go | 38 +-- internal/redfish/handler_test.go | 2 +- .../machine-management/seed/allocation.yaml | 38 ++- .../seed/location-management.yaml | 51 ++++ .../seed/{claim.yaml => machine.yaml} | 5 +- .../seed/test-identities.yaml | 4 +- 40 files changed, 948 insertions(+), 1023 deletions(-) delete mode 100644 api/v1alpha1/groupversion_info.go delete mode 100644 api/v1alpha1/types.go delete mode 100644 api/v1alpha1/zz_generated.deepcopy.go delete mode 100644 config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml delete mode 100644 config/crd/bases/fleet.datumapis.com_machineclaims.yaml rename {api => internal/api/session}/v1alpha1/doc.go (61%) create mode 100644 internal/api/session/v1alpha1/types.go create mode 100644 internal/api/session/v1alpha1/types_test.go create mode 100644 test/e2e/machine-management/seed/location-management.yaml rename test/e2e/machine-management/seed/{claim.yaml => machine.yaml} (53%) diff --git a/Taskfile.yaml b/Taskfile.yaml index 6ff5c6bd..560111e2 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -7,7 +7,7 @@ tasks: generate: desc: Regenerate the provisional CRDs from Kubebuilder markers cmds: - - go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.23.0 crd paths=./api/... output:crd:artifacts:config=config/crd/bases + - go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.23.0 crd paths=./internal/api/session/... output:crd:artifacts:config=config/crd/bases test: desc: Run portable unit and API/controller integration tests diff --git a/api/v1alpha1/groupversion_info.go b/api/v1alpha1/groupversion_info.go deleted file mode 100644 index 6309fc30..00000000 --- a/api/v1alpha1/groupversion_info.go +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -// Package v1alpha1 contains the provisional Fleet machine-management APIs. -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -var ( - GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme -) - -func addKnownTypes(s *runtime.Scheme) error { - s.AddKnownTypes(GroupVersion, - &MachineClaim{}, &MachineClaimList{}, - &MachineManagementSession{}, &MachineManagementSessionList{}, - &MachineAllocationBinding{}, &MachineAllocationBindingList{}, - &MachineManagementSessionBinding{}, &MachineManagementSessionBindingList{}, - &ProjectedMachineManagementSession{}, &ProjectedMachineManagementSessionList{}, - ) - metav1.AddToGroupVersion(s, GroupVersion) - return nil -} diff --git a/api/v1alpha1/types.go b/api/v1alpha1/types.go deleted file mode 100644 index 7862daa0..00000000 --- a/api/v1alpha1/types.go +++ /dev/null @@ -1,227 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -const ( - SessionFinalizer = "fleet.datumapis.com/machine-management-session" - ConditionReady = "Ready" - ProjectionActive = "Active" - ProjectionRevoked = "Revoked" -) - -// MachineClaim is the public allocation handle. The prototype seeds it; the -// protected MachineAllocationBinding remains the authoritative allocation. -// +kubebuilder:object:root=true -// +kubebuilder:subresource:status -type MachineClaim struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - Spec MachineClaimSpec `json:"spec,omitempty"` - Status MachineClaimStatus `json:"status,omitempty"` -} - -type MachineClaimSpec struct { - MachineClassRef LocalObjectReference `json:"machineClassRef"` -} - -type MachineClaimStatus struct { - Conditions []metav1.Condition `json:"conditions,omitempty"` -} - -type LocalObjectReference struct { - Name string `json:"name"` -} - -// +kubebuilder:object:root=true -type MachineClaimList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []MachineClaim `json:"items"` -} - -// MachineManagementSession is a short-lived public request for the machine -// currently bound to a claim. Resolved allocation details never enter it. -// +kubebuilder:object:root=true -// +kubebuilder:subresource:status -type MachineManagementSession struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="spec is immutable" - Spec MachineManagementSessionSpec `json:"spec"` - Status MachineManagementSessionStatus `json:"status,omitempty"` -} - -type MachineManagementSessionSpec struct { - MachineClaimRef LocalObjectReference `json:"machineClaimRef"` - // +kubebuilder:validation:Enum=Redfish - Protocol string `json:"protocol"` - // +kubebuilder:validation:Enum=Provisioning - AccessProfile string `json:"accessProfile"` - // +kubebuilder:validation:Pattern=`^[0-9a-f]{64}$` - ClientPublicKey string `json:"clientPublicKey"` - // +kubebuilder:validation:XValidation:rule="duration(self) >= duration('1m') && duration(self) <= duration('15m')",message="ttl must be between 1m and 15m" - TTL metav1.Duration `json:"ttl"` -} - -type MachineManagementSessionStatus struct { - Connection *SessionConnection `json:"connection,omitempty"` - ConnectBefore *metav1.Time `json:"connectBefore,omitempty"` - ExpiresAt *metav1.Time `json:"expiresAt,omitempty"` - Conditions []metav1.Condition `json:"conditions,omitempty"` -} - -// SessionConnection is non-secret rendezvous information. It never names a -// physical endpoint or adapter target. -type SessionConnection struct { - RelayURL string `json:"relayURL"` - RouteID string `json:"routeID"` - GatewayAudience string `json:"gatewayAudience"` - GatewayCertSHA256 string `json:"gatewayCertSHA256"` - ProtocolVersion string `json:"protocolVersion"` -} - -// +kubebuilder:object:root=true -type MachineManagementSessionList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []MachineManagementSession `json:"items"` -} - -// MachineAllocationBinding is synthetic prototype input owned by the allocator. -// It is protected in fleet-system and is never returned to customers. -// +kubebuilder:object:root=true -type MachineAllocationBinding struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - Spec MachineAllocationBindingSpec `json:"spec"` -} - -type MachineAllocationBindingSpec struct { - ConsumerProjectUID types.UID `json:"consumerProjectUID"` - ProviderProjectUID types.UID `json:"providerProjectUID"` - ClaimNamespace string `json:"claimNamespace"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - MachineName string `json:"machineName"` - MachineUID types.UID `json:"machineUID"` - BindingID string `json:"bindingID"` - BindingEpoch int64 `json:"bindingEpoch"` - LocationUID types.UID `json:"locationUID"` - LocationRevision string `json:"locationRevision"` - // MemberCluster is the protected Karmada member identity selected by the - // allocator/location registry. It is never supplied by the customer. - MemberCluster string `json:"memberCluster"` - BareMetalMachineUID types.UID `json:"bareMetalMachineUID"` - AccessProfileRevision string `json:"accessProfileRevision"` - AdapterRoute string `json:"adapterRoute"` - BMCSystemID string `json:"bmcSystemID"` - Active bool `json:"active"` -} - -// +kubebuilder:object:root=true -type MachineAllocationBindingList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []MachineAllocationBinding `json:"items"` -} - -// MachineManagementSessionBinding is the service-owned admission record. -// +kubebuilder:object:root=true -// +kubebuilder:subresource:status -type MachineManagementSessionBinding struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="admitted binding inputs are immutable" - Spec MachineManagementSessionBindingSpec `json:"spec"` - Status MachineManagementSessionBindingStatus `json:"status,omitempty"` -} - -type MachineManagementSessionBindingSpec struct { - SessionNamespace string `json:"sessionNamespace"` - SessionName string `json:"sessionName"` - SessionUID types.UID `json:"sessionUID"` - RequestingPrincipal string `json:"requestingPrincipal"` - ConsumerProjectUID types.UID `json:"consumerProjectUID"` - ProviderProjectUID types.UID `json:"providerProjectUID"` - ClaimName string `json:"claimName"` - ClaimUID types.UID `json:"claimUID"` - MachineName string `json:"machineName"` - MachineUID types.UID `json:"machineUID"` - BindingID string `json:"bindingID"` - BindingEpoch int64 `json:"bindingEpoch"` - LocationUID types.UID `json:"locationUID"` - LocationRevision string `json:"locationRevision"` - MemberCluster string `json:"memberCluster"` - BareMetalMachineUID types.UID `json:"bareMetalMachineUID"` - AccessProfileRevision string `json:"accessProfileRevision"` - ClientPublicKey string `json:"clientPublicKey"` - ConnectBefore metav1.Time `json:"connectBefore"` - ExpiresAt metav1.Time `json:"expiresAt"` - SessionCorrelationID string `json:"sessionCorrelationID"` - OperationCorrelationID string `json:"operationCorrelationID"` - AdapterRoute string `json:"adapterRoute"` - BMCSystemID string `json:"bmcSystemID"` -} - -type MachineManagementSessionBindingStatus struct { - Connection *SessionConnection `json:"connection,omitempty"` - Conditions []metav1.Condition `json:"conditions,omitempty"` -} - -// +kubebuilder:object:root=true -type MachineManagementSessionBindingList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []MachineManagementSessionBinding `json:"items"` -} - -// ProjectedMachineManagementSession is the least-privileged location copy. -// +kubebuilder:object:root=true -// +kubebuilder:subresource:status -type ProjectedMachineManagementSession struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - Spec ProjectedMachineManagementSessionSpec `json:"spec"` - Status ProjectedMachineManagementSessionStatus `json:"status,omitempty"` -} - -type ProjectedMachineManagementSessionSpec struct { - // +kubebuilder:validation:Enum=Active;Revoked - DesiredState string `json:"desiredState"` - SessionUID types.UID `json:"sessionUID"` - ClaimUID types.UID `json:"claimUID"` - MachineUID types.UID `json:"machineUID"` - BindingID string `json:"bindingID"` - BindingEpoch int64 `json:"bindingEpoch"` - LocationUID types.UID `json:"locationUID"` - LocationRevision string `json:"locationRevision"` - BareMetalMachineUID types.UID `json:"bareMetalMachineUID"` - AccessProfileRevision string `json:"accessProfileRevision"` - ClientPublicKey string `json:"clientPublicKey"` - ConnectBefore metav1.Time `json:"connectBefore"` - ExpiresAt metav1.Time `json:"expiresAt"` - AuthorityFreshUntil metav1.Time `json:"authorityFreshUntil"` - SessionCorrelationID string `json:"sessionCorrelationID"` - OperationCorrelationID string `json:"operationCorrelationID"` - AdapterRoute string `json:"adapterRoute"` - BMCSystemID string `json:"bmcSystemID"` -} - -type ProjectedMachineManagementSessionStatus struct { - Connection *SessionConnection `json:"connection,omitempty"` - ConnectedAt *metav1.Time `json:"connectedAt,omitempty"` - EndedAt *metav1.Time `json:"endedAt,omitempty"` - Conditions []metav1.Condition `json:"conditions,omitempty"` -} - -// +kubebuilder:object:root=true -type ProjectedMachineManagementSessionList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []ProjectedMachineManagementSession `json:"items"` -} diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index fe621bbb..00000000 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -// This file is intentionally hand-maintained until generation is added to the -// repository. The JSON round-trip keeps the prototype correct for pointer, -// slice, map, and metav1 fields; `task generate` replaces it in production. -package v1alpha1 - -import ( - "encoding/json" - - "k8s.io/apimachinery/pkg/runtime" -) - -func copyJSON[T any](in *T) *T { - if in == nil { - return nil - } - b, err := json.Marshal(in) - if err != nil { - panic(err) - } - out := new(T) - if err := json.Unmarshal(b, out); err != nil { - panic(err) - } - return out -} - -func (in *MachineClaim) DeepCopy() *MachineClaim { return copyJSON(in) } -func (in *MachineClaim) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *MachineClaimList) DeepCopy() *MachineClaimList { return copyJSON(in) } -func (in *MachineClaimList) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *MachineManagementSession) DeepCopy() *MachineManagementSession { return copyJSON(in) } -func (in *MachineManagementSession) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *MachineManagementSessionList) DeepCopy() *MachineManagementSessionList { return copyJSON(in) } -func (in *MachineManagementSessionList) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *MachineAllocationBinding) DeepCopy() *MachineAllocationBinding { return copyJSON(in) } -func (in *MachineAllocationBinding) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *MachineAllocationBindingList) DeepCopy() *MachineAllocationBindingList { return copyJSON(in) } -func (in *MachineAllocationBindingList) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *MachineManagementSessionBinding) DeepCopy() *MachineManagementSessionBinding { - return copyJSON(in) -} -func (in *MachineManagementSessionBinding) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *MachineManagementSessionBindingList) DeepCopy() *MachineManagementSessionBindingList { - return copyJSON(in) -} -func (in *MachineManagementSessionBindingList) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *ProjectedMachineManagementSession) DeepCopy() *ProjectedMachineManagementSession { - return copyJSON(in) -} -func (in *ProjectedMachineManagementSession) DeepCopyObject() runtime.Object { return in.DeepCopy() } -func (in *ProjectedMachineManagementSessionList) DeepCopy() *ProjectedMachineManagementSessionList { - return copyJSON(in) -} -func (in *ProjectedMachineManagementSessionList) DeepCopyObject() runtime.Object { - return in.DeepCopy() -} diff --git a/cmd/fleet-controller/main.go b/cmd/fleet-controller/main.go index 5e4e523a..a55b6c22 100644 --- a/cmd/fleet-controller/main.go +++ b/cmd/fleet-controller/main.go @@ -18,7 +18,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" ) @@ -37,6 +38,7 @@ func main() { } scheme := runtime.NewScheme() must(clientgoscheme.AddToScheme(scheme)) + must(fleetv1.AddToScheme(scheme)) must(fleetv1alpha1.AddToScheme(scheme)) federationConfig, err := clientcmd.BuildConfigFromFlags("", *federationKubeconfig) must(err) diff --git a/cmd/fleet-gateway/main.go b/cmd/fleet-gateway/main.go index 86f922dd..5a7b053a 100644 --- a/cmd/fleet-gateway/main.go +++ b/cmd/fleet-gateway/main.go @@ -15,21 +15,20 @@ import ( "sigs.k8s.io/controller-runtime/pkg/healthz" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/gateway" ) func main() { var cfg gateway.Config - var tokenFile, userFile, passwordFile string + var tokenFile string flag.StringVar(&cfg.RelayAddress, "relay-address", "fleet-relay.machine-access-system.svc:8443", "relay address") flag.StringVar(&cfg.RelayPublicURL, "relay-public-url", "tcp://127.0.0.1:8443", "client-visible relay URL") flag.StringVar(&tokenFile, "relay-token-file", "/var/run/secrets/fleet/relay-token", "relay registration token") flag.StringVar(&cfg.Audience, "audience", "fleet-gateway/location-prototype/r1", "proof audience") - flag.StringVar(&cfg.AdapterRoute, "adapter-route", "sushy-libvirt-v1", "qualified adapter route") - flag.StringVar(&cfg.BMCBaseURL, "bmc-url", "http://sushy-emulator:8000", "private sushy-emulator URL") - flag.StringVar(&userFile, "bmc-username-file", "/var/run/secrets/fleet/bmc-username", "BMC username file") - flag.StringVar(&passwordFile, "bmc-password-file", "/var/run/secrets/fleet/bmc-password", "BMC password file") + flag.StringVar(&cfg.SupportedAdapter, "supported-adapter", "sushy-libvirt-v1", "qualified local enrollment adapter") + flag.StringVar(&cfg.EnrollmentNamespace, "enrollment-namespace", "machine-access-system", "namespace containing safe capacity copies and private enrollments") flag.StringVar(&cfg.JournalDir, "journal-dir", "/var/lib/fleet", "durable journal directory") flag.StringVar(&cfg.StateDir, "state-dir", "/var/lib/fleet/sessions", "gateway state directory") flag.BoolVar(&cfg.DropResetResponseOnce, "fault-drop-reset-response-once", false, "test-only lost response injection") @@ -37,10 +36,9 @@ func main() { probe := flag.String("health-probe-bind-address", ":8081", "probe address") flag.Parse() cfg.RelayGatewayToken = readSecret(tokenFile) - cfg.BMCUsername = readSecret(userFile) - cfg.BMCPassword = readSecret(passwordFile) scheme := runtime.NewScheme() must(clientgoscheme.AddToScheme(scheme)) + must(fleetv1.AddToScheme(scheme)) must(fleetv1alpha1.AddToScheme(scheme)) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, @@ -54,7 +52,7 @@ func main() { must((&gateway.Reconciler{Config: cfg}).SetupWithManager(mgr)) must(mgr.AddHealthzCheck("healthz", healthz.Ping)) must(mgr.AddReadyzCheck("readyz", healthz.Ping)) - slog.Info("starting location gateway", "audience", cfg.Audience, "adapterRoute", cfg.AdapterRoute) + slog.Info("starting location gateway", "audience", cfg.Audience, "supportedAdapter", cfg.SupportedAdapter) must(mgr.Start(ctrl.SetupSignalHandler())) } func readSecret(path string) string { diff --git a/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml b/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml deleted file mode 100644 index 98daf66e..00000000 --- a/config/crd/bases/fleet.datumapis.com_machineallocationbindings.yaml +++ /dev/null @@ -1,128 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.23.0 - name: machineallocationbindings.fleet.datumapis.com -spec: - group: fleet.datumapis.com - names: - kind: MachineAllocationBinding - listKind: MachineAllocationBindingList - plural: machineallocationbindings - singular: machineallocationbinding - scope: Namespaced - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - MachineAllocationBinding is synthetic prototype input owned by the allocator. - It is protected in fleet-system and is never returned to customers. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - properties: - accessProfileRevision: - type: string - active: - type: boolean - adapterRoute: - type: string - bareMetalMachineUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - bindingEpoch: - format: int64 - type: integer - bindingID: - type: string - bmcSystemID: - type: string - claimName: - type: string - claimNamespace: - type: string - claimUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - consumerProjectUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - locationRevision: - type: string - locationUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - machineName: - type: string - machineUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - memberCluster: - description: |- - MemberCluster is the protected Karmada member identity selected by the - allocator/location registry. It is never supplied by the customer. - type: string - providerProjectUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - required: - - accessProfileRevision - - active - - adapterRoute - - bareMetalMachineUID - - bindingEpoch - - bindingID - - bmcSystemID - - claimName - - claimNamespace - - claimUID - - consumerProjectUID - - locationRevision - - locationUID - - machineName - - machineUID - - memberCluster - - providerProjectUID - type: object - required: - - spec - type: object - served: true - storage: true diff --git a/config/crd/bases/fleet.datumapis.com_machineclaims.yaml b/config/crd/bases/fleet.datumapis.com_machineclaims.yaml deleted file mode 100644 index 82067e83..00000000 --- a/config/crd/bases/fleet.datumapis.com_machineclaims.yaml +++ /dev/null @@ -1,116 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.23.0 - name: machineclaims.fleet.datumapis.com -spec: - group: fleet.datumapis.com - names: - kind: MachineClaim - listKind: MachineClaimList - plural: machineclaims - singular: machineclaim - scope: Namespaced - versions: - - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - MachineClaim is the public allocation handle. The prototype seeds it; the - protected MachineAllocationBinding remains the authoritative allocation. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - properties: - machineClassRef: - properties: - name: - type: string - required: - - name - type: object - required: - - machineClassRef - type: object - status: - properties: - conditions: - items: - description: Condition contains details for one aspect of the current - state of this API Resource. - properties: - lastTransitionTime: - description: |- - lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - message is a human readable message indicating details about the transition. - This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: |- - observedGeneration represents the .metadata.generation that the condition was set based upon. - For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date - with respect to the current state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: |- - reason contains a programmatic identifier indicating the reason for the condition's last transition. - Producers of specific condition types may define expected values and meanings for this field, - and whether the values are considered a guaranteed API. - The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - type: array - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml b/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml index bd7d916e..028ceaa8 100644 --- a/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml +++ b/config/crd/bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml @@ -17,8 +17,10 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: MachineManagementSessionBinding is the service-owned admission - record. + description: |- + MachineManagementSessionBinding is protected admission evidence. Local UIDs + are retained only as same-API-server recreation preconditions and are never + projected through Karmada. properties: apiVersion: description: |- @@ -39,26 +41,11 @@ spec: type: object spec: properties: - accessProfileRevision: + accessProfile: type: string - adapterRoute: + allocationName: type: string - bareMetalMachineUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - bindingEpoch: - format: int64 - type: integer - bindingID: - type: string - bmcSystemID: - type: string - claimName: - type: string - claimUID: + allocationUID: description: |- UID is a type that holds unique ID values, including UUIDs. Because we don't ONLY use UUIDs, this is an alias to string. Being a type captures @@ -69,18 +56,20 @@ spec: connectBefore: format: date-time type: string - consumerProjectUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. + consumerProject: + type: string + deviceName: type: string expiresAt: format: date-time type: string - locationRevision: + locationName: + type: string + machineCapacityName: type: string - locationUID: + machineCapacityNamespace: + type: string + machineCapacityUID: description: |- UID is a type that holds unique ID values, including UUIDs. Because we don't ONLY use UUIDs, this is an alias to string. Being a type captures @@ -88,6 +77,8 @@ spec: type: string machineName: type: string + machineNamespace: + type: string machineUID: description: |- UID is a type that holds unique ID values, including UUIDs. Because we @@ -98,11 +89,9 @@ spec: type: string operationCorrelationID: type: string - providerProjectUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. + protocol: + type: string + providerProject: type: string requestingPrincipal: type: string @@ -119,25 +108,25 @@ spec: intent and helps make sure that UIDs and names do not get conflated. type: string required: - - accessProfileRevision - - adapterRoute - - bareMetalMachineUID - - bindingEpoch - - bindingID - - bmcSystemID - - claimName - - claimUID + - accessProfile + - allocationName + - allocationUID - clientPublicKey - connectBefore - - consumerProjectUID + - consumerProject + - deviceName - expiresAt - - locationRevision - - locationUID + - locationName + - machineCapacityName + - machineCapacityNamespace + - machineCapacityUID - machineName + - machineNamespace - machineUID - memberCluster - operationCorrelationID - - providerProjectUID + - protocol + - providerProject - requestingPrincipal - sessionCorrelationID - sessionName @@ -206,9 +195,8 @@ spec: type: object type: array connection: - description: |- - SessionConnection is non-secret rendezvous information. It never names a - physical endpoint or adapter target. + description: SessionConnection contains non-secret rendezvous information + only. properties: gatewayAudience: type: string diff --git a/config/crd/bases/fleet.datumapis.com_machinemanagementsessions.yaml b/config/crd/bases/fleet.datumapis.com_machinemanagementsessions.yaml index 38525424..cfaf5894 100644 --- a/config/crd/bases/fleet.datumapis.com_machinemanagementsessions.yaml +++ b/config/crd/bases/fleet.datumapis.com_machinemanagementsessions.yaml @@ -18,8 +18,8 @@ spec: schema: openAPIV3Schema: description: |- - MachineManagementSession is a short-lived public request for the machine - currently bound to a claim. Resolved allocation details never enter it. + MachineManagementSession is a short-lived public request for the Machine's + current allocation. Provider and location details never enter this object. properties: apiVersion: description: |- @@ -47,7 +47,7 @@ spec: clientPublicKey: pattern: ^[0-9a-f]{64}$ type: string - machineClaimRef: + machineRef: properties: name: type: string @@ -66,7 +66,7 @@ spec: required: - accessProfile - clientPublicKey - - machineClaimRef + - machineRef - protocol - ttl type: object @@ -135,9 +135,8 @@ spec: format: date-time type: string connection: - description: |- - SessionConnection is non-secret rendezvous information. It never names a - physical endpoint or adapter target. + description: SessionConnection contains non-secret rendezvous information + only. properties: gatewayAudience: type: string diff --git a/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml b/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml index e9f3a9a8..eebdf97e 100644 --- a/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml +++ b/config/crd/bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml @@ -17,8 +17,9 @@ spec: - name: v1alpha1 schema: openAPIV3Schema: - description: ProjectedMachineManagementSession is the least-privileged location - copy. + description: |- + ProjectedMachineManagementSession is the least-privileged Karmada-delivered + location copy. Its generated name is the location session identity. properties: apiVersion: description: |- @@ -39,32 +40,11 @@ spec: type: object spec: properties: - accessProfileRevision: - type: string - adapterRoute: + accessProfile: type: string authorityFreshUntil: format: date-time type: string - bareMetalMachineUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - bindingEpoch: - format: int64 - type: integer - bindingID: - type: string - bmcSystemID: - type: string - claimUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string clientPublicKey: type: string connectBefore: @@ -78,50 +58,36 @@ spec: expiresAt: format: date-time type: string - locationRevision: - type: string - locationUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - machineUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. - type: string - operationCorrelationID: - type: string - sessionCorrelationID: - type: string - sessionUID: - description: |- - UID is a type that holds unique ID values, including UUIDs. Because we - don't ONLY use UUIDs, this is an alias to string. Being a type captures - intent and helps make sure that UIDs and names do not get conflated. + machineCapacityRef: + properties: + name: + type: string + required: + - name + type: object + protocol: type: string required: - - accessProfileRevision - - adapterRoute + - accessProfile - authorityFreshUntil - - bareMetalMachineUID - - bindingEpoch - - bindingID - - bmcSystemID - - claimUID - clientPublicKey - connectBefore - desiredState - expiresAt - - locationRevision - - locationUID - - machineUID - - operationCorrelationID - - sessionCorrelationID - - sessionUID + - machineCapacityRef + - protocol type: object + x-kubernetes-validations: + - message: projected authority inputs are immutable + rule: self.machineCapacityRef == oldSelf.machineCapacityRef && self.protocol + == oldSelf.protocol && self.accessProfile == oldSelf.accessProfile + && self.clientPublicKey == oldSelf.clientPublicKey && self.connectBefore + == oldSelf.connectBefore && self.expiresAt == oldSelf.expiresAt + - message: revocation is terminal + rule: oldSelf.desiredState == 'Active' || self.desiredState == 'Revoked' + - message: authority freshness may only advance within expiry + rule: timestamp(self.authorityFreshUntil) >= timestamp(oldSelf.authorityFreshUntil) + && timestamp(self.authorityFreshUntil) <= timestamp(self.expiresAt) status: properties: conditions: @@ -184,9 +150,8 @@ spec: format: date-time type: string connection: - description: |- - SessionConnection is non-secret rendezvous information. It never names a - physical endpoint or adapter target. + description: SessionConnection contains non-secret rendezvous information + only. properties: gatewayAudience: type: string diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index b4a56aed..08949671 100644 --- a/config/crd/kustomization.yaml +++ b/config/crd/kustomization.yaml @@ -1,8 +1,6 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - - bases/fleet.datumapis.com_machineclaims.yaml - bases/fleet.datumapis.com_machinemanagementsessions.yaml - - bases/fleet.datumapis.com_machineallocationbindings.yaml - bases/fleet.datumapis.com_machinemanagementsessionbindings.yaml - bases/fleet.datumapis.com_projectedmachinemanagementsessions.yaml diff --git a/config/location/access.yaml b/config/location/access.yaml index b197a60e..8a49d790 100644 --- a/config/location/access.yaml +++ b/config/location/access.yaml @@ -65,10 +65,8 @@ spec: - --relay-public-url=tcp://127.0.0.1:30443 - --relay-token-file=/var/run/secrets/fleet/relay-token - --audience=fleet-gateway/location-prototype/r1 - - --adapter-route=sushy-libvirt-v1 - - --bmc-url=http://172.30.0.10:8000 - - --bmc-username-file=/var/run/secrets/fleet/bmc-username - - --bmc-password-file=/var/run/secrets/fleet/bmc-password + - --supported-adapter=sushy-libvirt-v1 + - --enrollment-namespace=machine-access-system - --journal-dir=/var/lib/fleet ports: [{name: metrics, containerPort: 8080}, {name: health, containerPort: 8081}] livenessProbe: {httpGet: {path: /healthz, port: health}} @@ -92,7 +90,6 @@ spec: defaultMode: 0440 sources: - secret: {name: fleet-relay-token} - - secret: {name: fleet-bmc-credentials} - name: journal persistentVolumeClaim: {claimName: fleet-gateway-journal} - name: tmp diff --git a/config/rbac/controller.yaml b/config/rbac/controller.yaml index 6aa1b9f4..7371d0bc 100644 --- a/config/rbac/controller.yaml +++ b/config/rbac/controller.yaml @@ -10,7 +10,7 @@ metadata: name: fleet-session-controller rules: - apiGroups: [fleet.datumapis.com] - resources: [machinemanagementsessions, machineclaims] + resources: [machinemanagementsessions, machines, machinecapacities, machineallocations] verbs: [get, list, watch] # The controller writes only metadata finalizers on the public object. CEL # validation keeps the customer-authored spec immutable. @@ -24,7 +24,7 @@ rules: resources: [machinemanagementsessions/finalizers] verbs: [update, patch] - apiGroups: [fleet.datumapis.com] - resources: [machineallocationbindings, machinemanagementsessionbindings] + resources: [machinemanagementsessionbindings] verbs: [get, list, watch, create, update, patch] - apiGroups: [fleet.datumapis.com] resources: [machinemanagementsessionbindings/status] @@ -43,14 +43,14 @@ subjects: name: fleet-controller namespace: fleet-system --- -# Claim read and management-session creation are deliberately separate grants. +# Machine read and management-session creation are deliberately separate grants. apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: - name: fleet-machineclaim-viewer + name: fleet-machine-viewer rules: - apiGroups: [fleet.datumapis.com] - resources: [machineclaims] + resources: [machines] verbs: [get, list, watch] --- apiVersion: rbac.authorization.k8s.io/v1 @@ -80,6 +80,12 @@ rules: - apiGroups: [fleet.datumapis.com] resources: [projectedmachinemanagementsessions/status] verbs: [get, update, patch] + - apiGroups: [fleet.datumapis.com] + resources: [machinecapacities] + verbs: [get, list, watch] + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/docs/enhancements/secure-bmc-access.md b/docs/enhancements/secure-bmc-access.md index 9bd5e152..7bfb671f 100644 --- a/docs/enhancements/secure-bmc-access.md +++ b/docs/enhancements/secure-bmc-access.md @@ -11,9 +11,10 @@ API without exposing a BMC, its management network, or its credentials directly. It extends the provisional [Fleet design context](../design.md) and the pinned [bare-metal provisioning proposal][fleet-provisioning]. No API or behavior in this document is an accepted production contract. The repository contains a -[working prototype](../implementation/machine-management-prototype.md), but its -internal binding and projection schemas predate the simplified design below and -must not be treated as the proposed product API. +[working prototype](../implementation/machine-management-prototype.md) aligned +with the Machine, MachineAllocation and MachineCapacity identity model below. +Its synthetic allocation, location registration and enrollment records remain +prototype fixtures and must not be treated as accepted product APIs. The architecture borrows the session and data-path separation used by Datum Compute's provisional [instance shell sessions][compute-shell]: the platform diff --git a/docs/implementation/machine-management-prototype.md b/docs/implementation/machine-management-prototype.md index 307f8091..dc9c61cf 100644 --- a/docs/implementation/machine-management-prototype.md +++ b/docs/implementation/machine-management-prototype.md @@ -15,14 +15,16 @@ an ephemeral Ed25519 key pair, and creates a public The management-cluster controller authenticates through the Kubernetes delegated request identity retained by the mutating admission webhook. Kubernetes RBAC -provides the prototype authorization decision: `machineclaims` read and +provides the prototype authorization decision: `machines` read and `machinemanagementsessions` create are separate grants. The controller resolves -the claim against a service-owned `MachineAllocationBinding` and creates a -protected `MachineManagementSessionBinding`. The latter pins the principal, -consumer and provider Project UIDs, claim and machine name/UID pairs, binding ID -and epoch, location UID/revision, private BareMetalMachine UID, profile revision, -client key, deadlines, adapter route, and correlation IDs. None of the private -target fields are copied to the public session. +the customer `Machine` through the immutable, terminal `MachineAllocation` to a +provider `MachineCapacity` and creates a protected +`MachineManagementSessionBinding`. The latter pins the principal, consumer and +provider project identities, the Machine, allocation, MachineCapacity and +immutable `deviceRef`, authoritative location and Karmada member, client key, +deadlines, and correlation IDs. Local object UIDs are retained only in that +management-API record as recreation preconditions. None cross through Karmada +or enter the public session. The controller writes a least-privileged session to the separate Karmada API and creates an exact-cluster `PropagationPolicy` using the member identity retained @@ -39,10 +41,11 @@ Redfish request/response path. The client consumes the route once, pins the per-session gateway TLS certificate, and signs every request with a timestamped, nonce-bearing, domain-separated -Ed25519 proof. The gateway rejects changed inputs, audiences, expired timestamps, -nonce replay, stale authority, and adapter-route mismatch. Relay registration and -gateway TLS/proof credentials are separate. The relay only pairs an opaque route; -it cannot select a BMC target and does not implement unrestricted CONNECT. +Ed25519 proof bound to that one-use route and gateway audience. The gateway +rejects changed projected inputs, audiences, expired timestamps, nonce replay, +and stale authority. Relay registration and gateway TLS/proof credentials are +separate. The relay only pairs an opaque route; it cannot select a BMC target and +does not implement unrestricted CONNECT. The plugin exposes a TLS endpoint only on loopback. It writes a one-time local username/password and CA bundle at mode `0600`, publishes a non-secret readiness @@ -50,8 +53,13 @@ JSON file, deletes local login tokens on Redfish logout, and removes all tempora files at shutdown. These credentials are unrelated to the gateway's private sushy credential. -At the location, the gateway exposes one virtual system named `allocated`. Its -adapter selects the physical sushy system solely from protected binding state. +At the location, the gateway exposes one virtual system named `allocated`. The +projected session contains only the selected MachineCapacity name and session +authority. The gateway resolves a safe location-local MachineCapacity copy +through its immutable `deviceRef`, then selects exactly one service-owned +management-enrollment Secret carrying the adapter, endpoint, physical system and +credential inputs. Its adapter selects the physical sushy system only from that +resolved enrollment. Customer paths, Hosts, OData links, and guessed identifiers never participate in physical routing. The only supported mutations are one-time `Pxe` or `Hdd` boot selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or @@ -59,11 +67,12 @@ selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or ## Session and operation sequence -1. `datumctl fleet machine-management proxy CLAIM` generates a key and asks the - management API for a session using only the claim name. +1. `datumctl fleet machine-management proxy MACHINE` generates a key and asks the + management API for a session using only the customer Machine name. 2. Admission retains the authenticated principal. The controller resolves the - current claim UID and exact active allocation, enforces limits, and persists - the protected binding before projection. + current Machine, exact active MachineAllocation, provider MachineCapacity and + immutable device relationship, enforces limits, and persists the protected + binding before projection. 3. The projector checks the authoritative allocation on every refresh, creates a Karmada hub copy and exact-member policy, and waits for status from that member. The gateway reads only its cell-local copy, establishes an outbound relay @@ -71,11 +80,12 @@ selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or 4. The plugin consumes the route, verifies the pinned TLS identity, proves its admitted private key, and opens the loopback Redfish service. 5. Before a boot or reset effect, the gateway fsyncs an operation containing the - session/allocation/correlation identities, normalized method and virtual URI, - exact accepted body, internally selected physical target, idempotency key, - operation and binding epochs, conflict/freshness preconditions, adapter route, - and later execution evidence. Effects for a machine are serialized across all - sessions in the gateway process. + location-session, MachineCapacity and Device identities, normalized method + and virtual URI, exact accepted body, internally selected physical target, + idempotency key, operation epoch, conflict/freshness preconditions, and later + execution evidence. Effects for a Device are serialized across all sessions + in the gateway process. The protected central binding supplies durable + correlation back to the MachineAllocation. 6. A lost adapter response becomes `Unknown`; replaying the exact request returns the existing task without a second adapter call. Failed or unknown effects are never rewritten as success. @@ -83,16 +93,19 @@ selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or the hub copy's desired state to `Revoked`. Karmada carries the fence to the selected cell; the gateway closes the stream and writes `CleanupConfirmed` before the controller removes the policy and hub copy. Release also writes a - terminal revocation annotation so later claim-name reuse or reactivation cannot - resurrect the session. Deletion alone is never teardown proof; if the cell - cannot acknowledge the fence, central cleanup is `Unknown`. + terminal revocation annotation so later Machine-name reuse or a new allocation + cannot resurrect the session. Deletion alone is never teardown proof; if the + cell cannot acknowledge the fence, central cleanup is `Unknown`. ## API and deployment artifacts -Kubebuilder-style Go types and generated CRDs are under `api/v1alpha1` and -`config/crd/bases`. CEL makes the public spec immutable and constrains protocol, -profile, key encoding, and TTL. Conditions carry `observedGeneration`, explicit -reasons, and true/false/unknown outcomes. +Kubebuilder-style session types are under `internal/api/session/v1alpha1`; they +share `fleet.datumapis.com/v1alpha1` with the canonical lifecycle types under +`internal/api/v1alpha1`. Generated session CRDs are under `config/crd/bases`, +while the lifecycle CRD bundle remains under `config/base/crd`. CEL makes the +public spec immutable and constrains protocol, profile, key encoding, and TTL. +Conditions carry `observedGeneration`, explicit reasons, and true/false/unknown +outcomes. RBAC is in `config/rbac`; controller and location workloads are in `config/manager` and `config/location`. `config/federation` contains the Karmada @@ -159,9 +172,9 @@ using datumctl's unmanaged-plugin trust command. The test requires a real Karmad `Work` in `karmada-es-fleet-location-e2e`, verifies the hub received the selected cell's route status, and proves management has no direct location credential. It exercises generic DMTF client login, profile narrowing, distinct RBAC, -per-claim and per-project limits, one-shot rendezvous, real PXE and libvirt power +per-Machine and per-project limits, one-shot rendezvous, real PXE and libvirt power effects, DMTF validators, central API loss and freshness failure, release fencing, -claim recreation, route isolation, response-loss recovery, and bounded BMC errors. +Machine recreation, route isolation, response-loss recovery, and bounded BMC errors. Validator versions are `redfish` 3.4.2, `redfish-service-validator` 3.1.8, and @@ -193,7 +206,8 @@ BMC logs, validator reports, acceleration selection, and PXE callbacks. Implemented-and-tested code must not be confused with a production-ready contract. Important gaps are: -- Allocation and claim data are synthetic and pre-bound. There is no allocator, +- Machine, MachineAllocation, MachineCapacity, location registration, and local + enrollment data are synthetic and pre-bound. There is no production allocator, quota transaction, installation controller, cleanup/quarantine workflow, or cross-project Milo policy integration. - Delegated Kubernetes authentication/RBAC models the intended Compute/Milo diff --git a/hack/e2e/diagnostics.sh b/hack/e2e/diagnostics.sh index 35846dca..b7e49f97 100755 --- a/hack/e2e/diagnostics.sh +++ b/hack/e2e/diagnostics.sh @@ -8,7 +8,7 @@ for cluster in management location; do kubeconfig="${E2E_DIR}/${cluster}.kubeconfig" if [[ -f "${kubeconfig}" ]]; then kubectl --kubeconfig "${kubeconfig}" get all,events -A -o wide >"${OUT}/${cluster}-resources.txt" 2>&1 || true - kubectl --kubeconfig "${kubeconfig}" get machinemanagementsessions,machineallocationbindings,machinemanagementsessionbindings,projectedmachinemanagementsessions -A -o yaml >"${OUT}/${cluster}-fleet.yaml" 2>&1 || true + kubectl --kubeconfig "${kubeconfig}" get machines,machinecapacities,machineallocations,machinemanagementsessions,machinemanagementsessionbindings,projectedmachinemanagementsessions -A -o yaml >"${OUT}/${cluster}-fleet.yaml" 2>&1 || true kubectl --kubeconfig "${kubeconfig}" logs -A --all-containers --prefix --tail=-1 >"${OUT}/${cluster}-logs.txt" 2>&1 || true if [[ "${cluster}" == location ]]; then kubectl --kubeconfig "${kubeconfig}" -n machine-access-system exec deployment/fleet-gateway -- \ diff --git a/hack/e2e/openvpn-up.sh b/hack/e2e/openvpn-up.sh index 1320c36f..9c715b9f 100755 --- a/hack/e2e/openvpn-up.sh +++ b/hack/e2e/openvpn-up.sh @@ -17,8 +17,9 @@ kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create se --from-file=openvpn.key="${FLEET_E2E_STATE}/evidence/openvpn.key" --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${TEST_DIR}/openvpn/client.yaml" kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status daemonset/fleet-openvpn-client --timeout=120s -kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch deployment fleet-gateway --type=json \ - -p='[{"op":"replace","path":"/spec/template/spec/containers/0/args/5","value":"--bmc-url=http://10.88.0.1:8000"}]' +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch secret enrollment-device-allocated --type=merge \ + -p="{\"stringData\":{\"endpoint\":\"http://10.88.0.1:8000\"}}" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout restart deployment/fleet-gateway kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s pod=$(kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system get pod -l app.kubernetes.io/name=fleet-openvpn-client -o jsonpath='{.items[0].metadata.name}') kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system exec "${pod}" -- curl --fail --silent http://10.88.0.1:8000/redfish/v1/Systems >/dev/null diff --git a/hack/e2e/test.sh b/hack/e2e/test.sh index e52094e7..140a03e7 100755 --- a/hack/e2e/test.sh +++ b/hack/e2e/test.sh @@ -50,7 +50,7 @@ file_mode() { api_server=$(kubectl config view --kubeconfig "${MGMT_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.server}') -# A claim reader cannot create a management session. This invokes datumctl's +# A Machine reader cannot create a management session. This invokes datumctl's # actual plugin discovery/dispatch and credential-helper path. set +e HOME="${E2E_DIR}/home-viewer" datumctl fleet machine-management proxy db-01 -- \ @@ -58,7 +58,7 @@ HOME="${E2E_DIR}/home-viewer" datumctl fleet machine-management proxy db-01 -- \ --ready-file "${E2E_DIR}/viewer-ready.json" >"${E2E_DIR}/viewer.log" 2>&1 viewer_status=$? set -e -[[ ${viewer_status} -eq 11 ]] || fail "claim-only principal exit=${viewer_status}, expected permission exit 11" +[[ ${viewer_status} -eq 11 ]] || fail "Machine-read-only principal exit=${viewer_status}, expected permission exit 11" [[ ! -e "${E2E_DIR}/viewer-ready.json" ]] || fail "unauthorized principal received a local endpoint" start_proxy() { @@ -99,14 +99,15 @@ if curl --fail --silent --connect-timeout 2 http://172.30.0.10:8000/redfish/v1/ fi session_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.name}') session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsession "${session_name}" -o jsonpath='{.metadata.uid}') +binding_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -l "fleet.datumapis.com/session-uid=${session_uid}" -o jsonpath='{.items[0].metadata.name}') # This is an actual Karmada Work proof, not a direct controller write to the # member API: the selected cell owns the one Work containing this projection, # and status has returned through the hub copy before the public session readied. -work_clusters=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get works.work.karmada.io -A -o json | jq -r --arg uid "${session_uid}" ' - .items[] | select(any(.spec.workload.manifests[]?; .kind == "ProjectedMachineManagementSession" and .metadata.name == $uid)) | .metadata.namespace' | sort -u) +work_clusters=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get works.work.karmada.io -A -o json | jq -r --arg name "${binding_name}" ' + .items[] | select(any(.spec.workload.manifests[]?; .kind == "ProjectedMachineManagementSession" and .metadata.name == $name)) | .metadata.namespace' | sort -u) [[ "${work_clusters}" == karmada-es-fleet-location-e2e ]] || fail "projection Work was not isolated to fleet-location-e2e: ${work_clusters}" -[[ $(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n machine-access-system get projectedmachinemanagementsession "${session_uid}" -o jsonpath='{.metadata.labels.fleet\.datumapis\.com/member-cluster}') == fleet-location-e2e ]] || fail "hub projection lost its admitted member identity" -[[ -n $(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n machine-access-system get projectedmachinemanagementsession "${session_uid}" -o jsonpath='{.status.connection.routeID}') ]] || fail "cell status was not reflected through Karmada" +[[ $(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n machine-access-system get projectedmachinemanagementsession "${binding_name}" -o jsonpath='{.metadata.labels.fleet\.datumapis\.com/member-cluster}') == fleet-location-e2e ]] || fail "hub projection lost its admitted member identity" +[[ -n $(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n machine-access-system get projectedmachinemanagementsession "${binding_name}" -o jsonpath='{.status.connection.routeID}') ]] || fail "cell status was not reflected through Karmada" if kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get secret fleet-location-kubeconfig >/dev/null 2>&1; then fail "management cluster retained a direct location credential" fi @@ -155,55 +156,60 @@ route=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanageme replay=$(run_timeout 3 bash -c "exec 9<>/dev/tcp/127.0.0.1/30443; printf 'CLIENT %s\\n' '${route}' >&9; IFS= read -r line <&9; printf '%s' \"\${line}\"") [[ "${replay}" == ERROR* ]] || fail "relay route replay was not rejected: ${replay}" -# Per-claim admission limit remains distinct from claim read permission. +# Per-Machine admission limit remains distinct from Machine read permission. set +e run_timeout 20 env HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-01 -- \ --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" >"${E2E_DIR}/second-session.log" 2>&1 second_status=$? set -e -[[ ${second_status} -ne 0 ]] || fail "second concurrent claim session was admitted" +[[ ${second_status} -ne 0 ]] || fail "second concurrent Machine session was admitted" grep -q SessionLimitExceeded "${E2E_DIR}/second-session.log" || fail "session limit rejection was not actionable" # The E2E controller uses a test-only project limit of two. A second distinct, -# pre-bound claim is admitted; a third is rejected by the real plugin workflow. -for claim in db-02 db-03; do +# pre-bound Machine is admitted; a third is rejected by the real plugin workflow. +for machine in db-02 db-03; do kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - < libvirt PXE effect, correlated by the allocated VM MAC callback. pxe_body='{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Pxe"}}' @@ -266,22 +273,37 @@ management_paused=false wait_for "authority refresh" "[[ \$(rf_status '${root}/redfish/v1/Systems/allocated') == 200 ]]" # Allocation release is a terminal fence for this admitted binding. -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system patch machineallocationbinding db-01-allocation --type=merge -p '{"spec":{"active":false}}' +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system patch machineallocation db-01-allocation --subresource=status --type=merge -p '{"status":{"phase":"Released"}}' wait_for "released stream closure" "[[ \$(rf_status '${root}/redfish/v1/Systems/allocated') != 200 ]]" old_session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.uid}') -old_claim_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machineclaim db-01 -o jsonpath='{.metadata.uid}') +old_machine_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machine db-01 -o jsonpath='{.metadata.uid}') +old_binding_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -l "fleet.datumapis.com/session-uid=${old_session_uid}" -o jsonpath='{.items[0].metadata.name}') stop_proxy -# Recreate the same claim name for the other real libvirt domain. The old -# admitted binding stays revoked and cannot inherit the new claim UID. -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machineclaim db-01 --wait=true -kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/claim.yaml" -new_claim_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machineclaim db-01 -o jsonpath='{.metadata.uid}') -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system patch machineallocationbinding db-01-allocation --type=merge \ - -p "{\"metadata\":{\"labels\":{\"fleet.datumapis.com/claim-uid\":\"${new_claim_uid}\"}},\"spec\":{\"claimUID\":\"${new_claim_uid}\",\"machineName\":\"synthetic-reallocated\",\"machineUID\":\"66666666-6666-4666-8666-666666666666\",\"bindingID\":\"allocation-e2e-2\",\"bindingEpoch\":2,\"bareMetalMachineUID\":\"99999999-9999-4999-8999-999999999999\",\"bmcSystemID\":\"unallocated\",\"active\":true}}" -[[ "${new_claim_uid}" != "${old_claim_uid}" ]] || fail "recreated claim retained its old UID" -[[ $(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${old_session_uid}" -o jsonpath='{.spec.claimUID}') == "${old_claim_uid}" ]] || fail "old session binding inherited the recreated claim" -old_binding_revoked=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${old_session_uid}" -o jsonpath='{.metadata.annotations.fleet\.datumapis\.com/revoked-at}') +# Recreate the same Machine name for the other real libvirt domain. The old +# terminal allocation and admitted binding remain pinned to the old incarnation. +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machine db-01 --wait=true +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/machine.yaml" +new_machine_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machine db-01 -o jsonpath='{.metadata.uid}') +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - </dev/null location_paused=true stop_proxy -cleanup_status=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${unknown_session_uid}" -o json | jq -r '.status.conditions[] | select(.type=="CleanupConfirmed") | .status + ":" + .reason') +cleanup_status=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${unknown_binding_name}" -o json | jq -r '.status.conditions[] | select(.type=="CleanupConfirmed") | .status + ":" + .reason') [[ "${cleanup_status}" == "Unknown:LocationUnconfirmed" ]] || fail "unconfirmed teardown was not Unknown: ${cleanup_status}" docker unpause fleet-location-e2e-control-plane >/dev/null location_paused=false diff --git a/hack/e2e/up.sh b/hack/e2e/up.sh index 563a6aa9..4a3d5f77 100755 --- a/hack/e2e/up.sh +++ b/hack/e2e/up.sh @@ -123,6 +123,8 @@ docker build -t fleet-redfish-tools:e2e "${TEST_DIR}/tools" kind load docker-image fleet-controller:e2e --name fleet-management-e2e kind load docker-image fleet-gateway:e2e fleet-relay:e2e --name fleet-location-e2e +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/base/crd" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/base/crd" kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/crd" kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/crd" kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply \ @@ -140,9 +142,6 @@ kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/ relay_token=$(openssl rand -hex 32) kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create secret generic fleet-relay-token \ --from-literal=relay-token="${relay_token}" --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - -kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create secret generic fleet-bmc-credentials \ - --from-literal=bmc-username=fleet-gateway --from-literal=bmc-password=synthetic-e2e-only \ - --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - unset relay_token kubectl --kubeconfig "${KARMADA_KUBECONFIG}" create namespace fleet-system --dry-run=client -o yaml | @@ -202,12 +201,17 @@ kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout s kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machinemanagementsessions --all --timeout=40s --ignore-not-found kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system delete projectedmachinemanagementsessions --all --ignore-not-found kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system delete machinemanagementsessionbindings --all --ignore-not-found -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machineclaims db-02 db-03 --ignore-not-found -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system delete machineallocationbindings db-02-allocation db-03-allocation --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machines db-01 db-02 db-03 --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system delete machineallocations --all --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-provider delete machinecapacities --all --ignore-not-found 2>/dev/null || true -kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/claim.yaml" -claim_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machineclaim db-01 -o jsonpath='{.metadata.uid}') -sed "s/CLAIM_UID/${claim_uid}/g" "${TEST_DIR}/seed/allocation.yaml" | kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${MGMT_KUBECONFIG}" create namespace fleet-provider --dry-run=client -o yaml | kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/machine.yaml" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/allocation.yaml" +machine_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machine db-01 -o jsonpath='{.metadata.uid}') +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system annotate machineallocation db-01-allocation fleet.datumapis.com/machine-uid="${machine_uid}" --overwrite +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system patch machineallocation db-01-allocation --subresource=status --type=merge -p '{"status":{"phase":"Active"}}' +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${TEST_DIR}/seed/location-management.yaml" kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/test-identities.yaml" authorized_token=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default create token fleet-authorized --duration=2h) diff --git a/api/v1alpha1/doc.go b/internal/api/session/v1alpha1/doc.go similarity index 61% rename from api/v1alpha1/doc.go rename to internal/api/session/v1alpha1/doc.go index 3d265053..167544c6 100644 --- a/api/v1alpha1/doc.go +++ b/internal/api/session/v1alpha1/doc.go @@ -1,6 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 +// Package v1alpha1 contains provisional Fleet machine-management session APIs. // +kubebuilder:object:generate=true // +groupName=fleet.datumapis.com - package v1alpha1 diff --git a/internal/api/session/v1alpha1/types.go b/internal/api/session/v1alpha1/types.go new file mode 100644 index 00000000..e72fd136 --- /dev/null +++ b/internal/api/session/v1alpha1/types.go @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 + +package v1alpha1 + +import ( + "encoding/json" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" +) + +var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} + +type LocalReference struct { + Name string `json:"name"` +} + +const ( + SessionFinalizer = "fleet.datumapis.com/machine-management-session" + ConditionReady = "Ready" + ProjectionActive = "Active" + ProjectionRevoked = "Revoked" +) + +// MachineManagementSession is a short-lived public request for the Machine's +// current allocation. Provider and location details never enter this object. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type MachineManagementSession struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="spec is immutable" + Spec MachineManagementSessionSpec `json:"spec"` + Status MachineManagementSessionStatus `json:"status,omitempty"` +} + +type MachineManagementSessionSpec struct { + MachineRef LocalReference `json:"machineRef"` + // +kubebuilder:validation:Enum=Redfish + Protocol string `json:"protocol"` + // +kubebuilder:validation:Enum=Provisioning + AccessProfile string `json:"accessProfile"` + // +kubebuilder:validation:Pattern=`^[0-9a-f]{64}$` + ClientPublicKey string `json:"clientPublicKey"` + // +kubebuilder:validation:XValidation:rule="duration(self) >= duration('1m') && duration(self) <= duration('15m')",message="ttl must be between 1m and 15m" + TTL metav1.Duration `json:"ttl"` +} + +type MachineManagementSessionStatus struct { + Connection *SessionConnection `json:"connection,omitempty"` + ConnectBefore *metav1.Time `json:"connectBefore,omitempty"` + ExpiresAt *metav1.Time `json:"expiresAt,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// SessionConnection contains non-secret rendezvous information only. +type SessionConnection struct { + RelayURL string `json:"relayURL"` + RouteID string `json:"routeID"` + GatewayAudience string `json:"gatewayAudience"` + GatewayCertSHA256 string `json:"gatewayCertSHA256"` + ProtocolVersion string `json:"protocolVersion"` +} + +// +kubebuilder:object:root=true +type MachineManagementSessionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineManagementSession `json:"items"` +} + +// MachineManagementSessionBinding is protected admission evidence. Local UIDs +// are retained only as same-API-server recreation preconditions and are never +// projected through Karmada. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type MachineManagementSessionBinding struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="admitted binding inputs are immutable" + Spec MachineManagementSessionBindingSpec `json:"spec"` + Status MachineManagementSessionBindingStatus `json:"status,omitempty"` +} + +type MachineManagementSessionBindingSpec struct { + SessionNamespace string `json:"sessionNamespace"` + SessionName string `json:"sessionName"` + SessionUID types.UID `json:"sessionUID"` + RequestingPrincipal string `json:"requestingPrincipal"` + ConsumerProject string `json:"consumerProject"` + ProviderProject string `json:"providerProject"` + MachineNamespace string `json:"machineNamespace"` + MachineName string `json:"machineName"` + MachineUID types.UID `json:"machineUID"` + AllocationName string `json:"allocationName"` + AllocationUID types.UID `json:"allocationUID"` + MachineCapacityNamespace string `json:"machineCapacityNamespace"` + MachineCapacityName string `json:"machineCapacityName"` + MachineCapacityUID types.UID `json:"machineCapacityUID"` + DeviceName string `json:"deviceName"` + LocationName string `json:"locationName"` + MemberCluster string `json:"memberCluster"` + Protocol string `json:"protocol"` + AccessProfile string `json:"accessProfile"` + ClientPublicKey string `json:"clientPublicKey"` + ConnectBefore metav1.Time `json:"connectBefore"` + ExpiresAt metav1.Time `json:"expiresAt"` + SessionCorrelationID string `json:"sessionCorrelationID"` + OperationCorrelationID string `json:"operationCorrelationID"` +} + +type MachineManagementSessionBindingStatus struct { + Connection *SessionConnection `json:"connection,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +type MachineManagementSessionBindingList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineManagementSessionBinding `json:"items"` +} + +// ProjectedMachineManagementSession is the least-privileged Karmada-delivered +// location copy. Its generated name is the location session identity. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type ProjectedMachineManagementSession struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec ProjectedMachineManagementSessionSpec `json:"spec"` + Status ProjectedMachineManagementSessionStatus `json:"status,omitempty"` +} + +// +kubebuilder:validation:XValidation:rule="self.machineCapacityRef == oldSelf.machineCapacityRef && self.protocol == oldSelf.protocol && self.accessProfile == oldSelf.accessProfile && self.clientPublicKey == oldSelf.clientPublicKey && self.connectBefore == oldSelf.connectBefore && self.expiresAt == oldSelf.expiresAt",message="projected authority inputs are immutable" +// +kubebuilder:validation:XValidation:rule="oldSelf.desiredState == 'Active' || self.desiredState == 'Revoked'",message="revocation is terminal" +// +kubebuilder:validation:XValidation:rule="timestamp(self.authorityFreshUntil) >= timestamp(oldSelf.authorityFreshUntil) && timestamp(self.authorityFreshUntil) <= timestamp(self.expiresAt)",message="authority freshness may only advance within expiry" +type ProjectedMachineManagementSessionSpec struct { + // +kubebuilder:validation:Enum=Active;Revoked + DesiredState string `json:"desiredState"` + MachineCapacityRef LocalReference `json:"machineCapacityRef"` + Protocol string `json:"protocol"` + AccessProfile string `json:"accessProfile"` + ClientPublicKey string `json:"clientPublicKey"` + ConnectBefore metav1.Time `json:"connectBefore"` + ExpiresAt metav1.Time `json:"expiresAt"` + AuthorityFreshUntil metav1.Time `json:"authorityFreshUntil"` +} + +type ProjectedMachineManagementSessionStatus struct { + Connection *SessionConnection `json:"connection,omitempty"` + ConnectedAt *metav1.Time `json:"connectedAt,omitempty"` + EndedAt *metav1.Time `json:"endedAt,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +type ProjectedMachineManagementSessionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ProjectedMachineManagementSession `json:"items"` +} + +func AddToScheme(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, + &MachineManagementSession{}, &MachineManagementSessionList{}, + &MachineManagementSessionBinding{}, &MachineManagementSessionBindingList{}, + &ProjectedMachineManagementSession{}, &ProjectedMachineManagementSessionList{}, + ) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} + +func (in *MachineManagementSession) DeepCopy() *MachineManagementSession { return copyJSON(in) } +func (in *MachineManagementSession) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionList) DeepCopy() *MachineManagementSessionList { return copyJSON(in) } +func (in *MachineManagementSessionList) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionBinding) DeepCopy() *MachineManagementSessionBinding { + return copyJSON(in) +} +func (in *MachineManagementSessionBinding) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionBindingList) DeepCopy() *MachineManagementSessionBindingList { + return copyJSON(in) +} +func (in *MachineManagementSessionBindingList) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *ProjectedMachineManagementSession) DeepCopy() *ProjectedMachineManagementSession { + return copyJSON(in) +} +func (in *ProjectedMachineManagementSession) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *ProjectedMachineManagementSessionList) DeepCopy() *ProjectedMachineManagementSessionList { + return copyJSON(in) +} +func (in *ProjectedMachineManagementSessionList) DeepCopyObject() runtime.Object { + return in.DeepCopy() +} + +func copyJSON[T any](in *T) *T { + b, _ := json.Marshal(in) + out := new(T) + _ = json.Unmarshal(b, out) + return out +} diff --git a/internal/api/session/v1alpha1/types_test.go b/internal/api/session/v1alpha1/types_test.go new file mode 100644 index 00000000..666f6c3a --- /dev/null +++ b/internal/api/session/v1alpha1/types_test.go @@ -0,0 +1,76 @@ +package v1alpha1 + +import ( + "os" + "path/filepath" + "testing" + + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/yaml" +) + +func TestAddToSchemeRegistersSessionKinds(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + for _, kind := range []string{"MachineManagementSession", "MachineManagementSessionList", "MachineManagementSessionBinding", "MachineManagementSessionBindingList", "ProjectedMachineManagementSession", "ProjectedMachineManagementSessionList"} { + if _, err := scheme.New(GroupVersion.WithKind(kind)); err != nil { + t.Errorf("kind %s is not registered: %v", kind, err) + } + } +} + +func TestGeneratedSessionCRDsDoNotProjectPrivateRouting(t *testing.T) { + public := readCRD(t, "fleet.datumapis.com_machinemanagementsessions.yaml") + publicSpec := property(t, public, "spec") + if _, ok := publicSpec.Properties["machineRef"]; !ok { + t.Fatal("public session does not reference Machine") + } + if _, ok := publicSpec.Properties["machineClaimRef"]; ok { + t.Fatal("legacy MachineClaim reference remains public") + } + if len(publicSpec.XValidations) == 0 { + t.Fatal("public session spec is mutable") + } + + projected := readCRD(t, "fleet.datumapis.com_projectedmachinemanagementsessions.yaml") + projectedSpec := property(t, projected, "spec") + for _, forbidden := range []string{"sessionUID", "machineUID", "allocationName", "bindingID", "bindingEpoch", "memberCluster", "locationUID", "adapterRoute", "bmcSystemID", "secretRef"} { + if _, ok := projectedSpec.Properties[forbidden]; ok { + t.Errorf("projected session leaks %s", forbidden) + } + } + if _, ok := projectedSpec.Properties["machineCapacityRef"]; !ok { + t.Fatal("projected session does not carry MachineCapacity identity") + } + if len(projectedSpec.XValidations) < 3 { + t.Fatal("projected session lacks immutable and monotonic authority validation") + } +} + +func readCRD(t *testing.T, name string) *extensionsv1.CustomResourceDefinition { + t.Helper() + data, err := os.ReadFile(filepath.Join("..", "..", "..", "..", "config", "crd", "bases", name)) + if err != nil { + t.Fatal(err) + } + var crd extensionsv1.CustomResourceDefinition + if err := yaml.Unmarshal(data, &crd); err != nil { + t.Fatal(err) + } + return &crd +} + +func property(t *testing.T, crd *extensionsv1.CustomResourceDefinition, name string) extensionsv1.JSONSchemaProps { + t.Helper() + if crd == nil || len(crd.Spec.Versions) != 1 || crd.Spec.Versions[0].Schema == nil || crd.Spec.Versions[0].Schema.OpenAPIV3Schema == nil { + t.Fatal("CRD schema is missing") + } + property, ok := crd.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties[name] + if !ok { + t.Fatalf("CRD has no %s", name) + } + return property +} diff --git a/internal/cmd/fleet/root.go b/internal/cmd/fleet/root.go index d7d3cbeb..53953e09 100644 --- a/internal/cmd/fleet/root.go +++ b/internal/cmd/fleet/root.go @@ -34,9 +34,8 @@ import ( "github.com/spf13/cobra" "go.datum.net/datumctl/plugin" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" "go.datum.net/fleet/internal/gateway" "go.datum.net/fleet/internal/protocol" "go.datum.net/fleet/internal/relay" @@ -67,8 +66,8 @@ func Command() *cobra.Command { root := plugin.NewRootCmd("fleet", "Manage Datum Fleet resources") mm := &cobra.Command{Use: "machine-management", Short: "Access allocation-scoped machine management"} o := &proxyOptions{} - proxy := &cobra.Command{Use: "proxy CLAIM", Short: "Open a short-lived local Redfish endpoint", Args: cobra.ExactArgs(1), SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { return o.run(cmd.Context(), cmd, args[0]) }} - proxy.Flags().StringVar(&o.namespace, "namespace", "default", "MachineClaim namespace") + proxy := &cobra.Command{Use: "proxy MACHINE", Short: "Open a short-lived local Redfish endpoint", Args: cobra.ExactArgs(1), SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { return o.run(cmd.Context(), cmd, args[0]) }} + proxy.Flags().StringVar(&o.namespace, "namespace", "default", "Machine namespace") proxy.Flags().StringVar(&o.listen, "listen", "127.0.0.1:0", "loopback address for the local Redfish endpoint") proxy.Flags().DurationVar(&o.ttl, "ttl", 15*time.Minute, "session lifetime (1m-15m)") proxy.Flags().StringVar(&o.credentialFile, "credential-file", "", "0600 JSON credential file (temporary when omitted)") @@ -81,7 +80,7 @@ func Command() *cobra.Command { return root } -func (o *proxyOptions) run(parent context.Context, cmd *cobra.Command, claim string) error { +func (o *proxyOptions) run(parent context.Context, cmd *cobra.Command, machine string) error { if o.ttl < time.Minute || o.ttl > 15*time.Minute { return &ExitError{ExitUsage, errors.New("--ttl must be between 1m and 15m")} } @@ -107,7 +106,7 @@ func (o *proxyOptions) run(parent context.Context, cmd *cobra.Command, claim str defer clear(privateKey) ctx, cancel := signal.NotifyContext(parent, os.Interrupt, syscall.SIGTERM) defer cancel() - session, err := api.create(ctx, o.namespace, claim, protocol.PublicKey(privateKey), o.ttl) + session, err := api.create(ctx, o.namespace, machine, protocol.PublicKey(privateKey), o.ttl) if err != nil { return classifyAPI(err) } @@ -126,7 +125,7 @@ func (o *proxyOptions) run(parent context.Context, cmd *cobra.Command, claim str return &ExitError{ExitConnect, err} } defer conn.Close() - cleanup, endpoint, err := o.serveLocal(ctx, privateKey, session.UID, session.Status.Connection, conn) + cleanup, endpoint, err := o.serveLocal(ctx, privateKey, session.Name, session.Status.Connection, conn) if err != nil { return &ExitError{ExitConnect, err} } @@ -202,8 +201,8 @@ func (a *apiClient) do(ctx context.Context, method, u string, body io.Reader, ou } return nil } -func (a *apiClient) create(ctx context.Context, ns, claim, key string, ttl time.Duration) (*fleetv1alpha1.MachineManagementSession, error) { - s := &fleetv1alpha1.MachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{GenerateName: claim + "-", Namespace: ns}, Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineClaimRef: fleetv1alpha1.LocalObjectReference{Name: claim}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: key, TTL: metav1.Duration{Duration: ttl}}} +func (a *apiClient) create(ctx context.Context, ns, machine, key string, ttl time.Duration) (*fleetv1alpha1.MachineManagementSession, error) { + s := &fleetv1alpha1.MachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{GenerateName: machine + "-", Namespace: ns}, Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineRef: fleetv1alpha1.LocalReference{Name: machine}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: key, TTL: metav1.Duration{Duration: ttl}}} b, _ := json.Marshal(s) var out fleetv1alpha1.MachineManagementSession if err := a.do(ctx, http.MethodPost, a.url(ns, ""), strings.NewReader(string(b)), &out); err != nil { @@ -297,7 +296,7 @@ func connectLocation(ctx context.Context, key ed25519.PrivateKey, s *fleetv1alph return tlsConn, nil } -func (o *proxyOptions) serveLocal(ctx context.Context, key ed25519.PrivateKey, sessionUID types.UID, c *fleetv1alpha1.SessionConnection, remote net.Conn) (func(), string, error) { +func (o *proxyOptions) serveLocal(ctx context.Context, key ed25519.PrivateKey, sessionName string, c *fleetv1alpha1.SessionConnection, remote net.Conn) (func(), string, error) { listener, err := net.Listen("tcp", o.listen) if err != nil { return nil, "", err @@ -348,7 +347,7 @@ func (o *proxyOptions) serveLocal(ctx context.Context, key ed25519.PrivateKey, s cleanup() return nil, "", err } - ready := map[string]any{"ready": true, "endpoint": endpoint, "credentialFile": o.credentialFile, "caBundle": o.caFile, "sessionUID": string(sessionUID)} + ready := map[string]any{"ready": true, "endpoint": endpoint, "credentialFile": o.credentialFile, "caBundle": o.caFile, "session": sessionName} if err := writeJSONFile(o.readyFile, ready, 0o644); err != nil { cleanup() return nil, "", err @@ -362,8 +361,8 @@ func (o *proxyOptions) serveLocal(ctx context.Context, key ed25519.PrivateKey, s r.Host = "fleet-gateway" r.Header.Del("Authorization") r.Header.Del("X-Auth-Token") - p, _ := protocol.Sign(key, string(sessionUID), c.GatewayAudience, time.Now()) - r.Header.Set(gateway.HeaderSession, string(sessionUID)) + p, _ := protocol.Sign(key, c.RouteID, c.GatewayAudience, time.Now()) + r.Header.Set(gateway.HeaderSession, c.RouteID) r.Header.Set(gateway.HeaderAudience, c.GatewayAudience) r.Header.Set(gateway.HeaderTimestamp, p.Timestamp) r.Header.Set(gateway.HeaderNonce, p.Nonce) diff --git a/internal/controller/admission.go b/internal/controller/admission.go index 784841d8..b9e4348c 100644 --- a/internal/controller/admission.go +++ b/internal/controller/admission.go @@ -12,7 +12,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" ) // SessionAdmission retains the authenticated API principal before the diff --git a/internal/controller/admission_test.go b/internal/controller/admission_test.go index d3964216..0ce7c6fc 100644 --- a/internal/controller/admission_test.go +++ b/internal/controller/admission_test.go @@ -11,11 +11,11 @@ import ( "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" ) func TestAdmissionRetainsAuthenticatedPrincipal(t *testing.T) { - s := fleetv1alpha1.MachineManagementSession{Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineClaimRef: fleetv1alpha1.LocalObjectReference{Name: "db-01"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}} + s := fleetv1alpha1.MachineManagementSession{Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineRef: fleetv1alpha1.LocalReference{Name: "db-01"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}} raw, _ := json.Marshal(s) resp := SessionAdmission{}.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{Operation: admissionv1.Create, Object: runtime.RawExtension{Raw: raw}, UserInfo: authnv1.UserInfo{Username: "alice@example.test"}}}) if !resp.Allowed || len(resp.Patches) == 0 { diff --git a/internal/controller/projection.go b/internal/controller/projection.go index 9f674960..c6af9017 100644 --- a/internal/controller/projection.go +++ b/internal/controller/projection.go @@ -18,7 +18,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/reconcile" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" ) // ProjectionReconciler writes only to the Karmada hub. Karmada carries the @@ -109,12 +110,29 @@ func (r *ProjectionReconciler) Reconcile(ctx context.Context, req ctrl.Request) } func (r *ProjectionReconciler) allocationStillActive(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding) bool { - var list fleetv1alpha1.MachineAllocationBindingList - if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace()), client.MatchingLabels{ClaimUIDLabel: string(b.Spec.ClaimUID)}); err != nil || len(list.Items) != 1 { + var allocation fleetv1.MachineAllocation + if err := r.Get(ctx, types.NamespacedName{Namespace: r.systemNamespace(), Name: b.Spec.AllocationName}, &allocation); err != nil { return false } - a := list.Items[0].Spec - return a.Active && a.ClaimUID == b.Spec.ClaimUID && a.MachineUID == b.Spec.MachineUID && a.BindingID == b.Spec.BindingID && a.BindingEpoch == b.Spec.BindingEpoch && a.LocationUID == b.Spec.LocationUID && a.LocationRevision == b.Spec.LocationRevision && a.MemberCluster == b.Spec.MemberCluster && a.AdapterRoute == b.Spec.AdapterRoute + if allocation.UID != b.Spec.AllocationUID || allocation.Status.Phase != "Active" || + allocation.Spec.MachineRef.Project != b.Spec.ConsumerProject || + allocation.Spec.MachineRef.Namespace != b.Spec.MachineNamespace || allocation.Spec.MachineRef.Name != b.Spec.MachineName || + allocation.Spec.MachineCapacityRef.Namespace != b.Spec.MachineCapacityNamespace || allocation.Spec.MachineCapacityRef.Name != b.Spec.MachineCapacityName || + allocation.Annotations[AllocationMachineUIDAnnotation] != string(b.Spec.MachineUID) || + allocation.Annotations[MemberClusterAnnotation] != b.Spec.MemberCluster || + allocation.Annotations[LocationNameAnnotation] != b.Spec.LocationName || + allocation.Annotations[ProviderProjectAnnotation] != b.Spec.ProviderProject { + return false + } + var machine fleetv1.Machine + if err := r.Get(ctx, types.NamespacedName{Namespace: b.Spec.MachineNamespace, Name: b.Spec.MachineName}, &machine); err != nil || machine.UID != b.Spec.MachineUID { + return false + } + var capacity fleetv1.MachineCapacity + if err := r.Get(ctx, types.NamespacedName{Namespace: b.Spec.MachineCapacityNamespace, Name: b.Spec.MachineCapacityName}, &capacity); err != nil { + return false + } + return capacity.UID == b.Spec.MachineCapacityUID && capacity.Spec.DeviceRef.Name == b.Spec.DeviceName } func (r *ProjectionReconciler) revokeProjection(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding, p *fleetv1alpha1.ProjectedMachineManagementSession) (ctrl.Result, error) { @@ -146,14 +164,22 @@ func (r *ProjectionReconciler) build(b *fleetv1alpha1.MachineManagementSessionBi s := b.Spec return &fleetv1alpha1.ProjectedMachineManagementSession{ TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "ProjectedMachineManagementSession"}, - ObjectMeta: metav1.ObjectMeta{Name: b.Name, Namespace: r.hubNamespace(), Labels: map[string]string{SessionUIDLabel: string(s.SessionUID), ClaimUIDLabel: string(s.ClaimUID), MemberClusterLabel: s.MemberCluster}}, - Spec: fleetv1alpha1.ProjectedMachineManagementSessionSpec{DesiredState: fleetv1alpha1.ProjectionActive, SessionUID: s.SessionUID, ClaimUID: s.ClaimUID, MachineUID: s.MachineUID, BindingID: s.BindingID, BindingEpoch: s.BindingEpoch, LocationUID: s.LocationUID, LocationRevision: s.LocationRevision, BareMetalMachineUID: s.BareMetalMachineUID, AccessProfileRevision: s.AccessProfileRevision, ClientPublicKey: s.ClientPublicKey, ConnectBefore: s.ConnectBefore, ExpiresAt: s.ExpiresAt, AuthorityFreshUntil: metav1.NewTime(r.now().Add(r.freshness())), SessionCorrelationID: s.SessionCorrelationID, OperationCorrelationID: s.OperationCorrelationID, AdapterRoute: s.AdapterRoute, BMCSystemID: s.BMCSystemID}, + ObjectMeta: metav1.ObjectMeta{Name: b.Name, Namespace: r.hubNamespace(), Labels: map[string]string{MemberClusterLabel: s.MemberCluster}}, + Spec: fleetv1alpha1.ProjectedMachineManagementSessionSpec{ + DesiredState: fleetv1alpha1.ProjectionActive, + MachineCapacityRef: fleetv1alpha1.LocalReference{Name: s.MachineCapacityName}, + Protocol: s.Protocol, AccessProfile: s.AccessProfile, ClientPublicKey: s.ClientPublicKey, + ConnectBefore: s.ConnectBefore, ExpiresAt: s.ExpiresAt, + AuthorityFreshUntil: metav1.NewTime(r.now().Add(r.freshness())), + }, } } func projectionMatches(b *fleetv1alpha1.MachineManagementSessionBinding, p *fleetv1alpha1.ProjectedMachineManagementSession) bool { s, x := b.Spec, p.Spec - return p.Labels[MemberClusterLabel] == s.MemberCluster && x.SessionUID == s.SessionUID && x.ClaimUID == s.ClaimUID && x.MachineUID == s.MachineUID && x.BindingID == s.BindingID && x.BindingEpoch == s.BindingEpoch && x.LocationUID == s.LocationUID && x.LocationRevision == s.LocationRevision && x.BareMetalMachineUID == s.BareMetalMachineUID && x.AccessProfileRevision == s.AccessProfileRevision && x.ClientPublicKey == s.ClientPublicKey && x.ConnectBefore.Equal(&s.ConnectBefore) && x.ExpiresAt.Equal(&s.ExpiresAt) && x.AdapterRoute == s.AdapterRoute && x.BMCSystemID == s.BMCSystemID + return p.Labels[MemberClusterLabel] == s.MemberCluster && + x.MachineCapacityRef.Name == s.MachineCapacityName && x.Protocol == s.Protocol && x.AccessProfile == s.AccessProfile && + x.ClientPublicKey == s.ClientPublicKey && x.ConnectBefore.Equal(&s.ConnectBefore) && x.ExpiresAt.Equal(&s.ExpiresAt) } func (r *ProjectionReconciler) ensurePolicy(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding) error { @@ -201,10 +227,10 @@ func (r *ProjectionReconciler) SetupWithManager(mgr ctrl.Manager) error { r.Client = mgr.GetClient() return ctrl.NewControllerManagedBy(mgr). For(&fleetv1alpha1.MachineManagementSessionBinding{}). - Watches(&fleetv1alpha1.MachineAllocationBinding{}, handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, obj client.Object) []reconcile.Request { - a := obj.(*fleetv1alpha1.MachineAllocationBinding) + Watches(&fleetv1.MachineAllocation{}, handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, obj client.Object) []reconcile.Request { + a := obj.(*fleetv1.MachineAllocation) var list fleetv1alpha1.MachineManagementSessionBindingList - if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace()), client.MatchingLabels{ClaimUIDLabel: string(a.Spec.ClaimUID)}); err != nil { + if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace()), client.MatchingLabels{AllocationNameLabel: a.Name}); err != nil { return nil } out := make([]reconcile.Request, 0, len(list.Items)) diff --git a/internal/controller/projection_test.go b/internal/controller/projection_test.go index 1ed1a74d..471b7ff5 100644 --- a/internal/controller/projection_test.go +++ b/internal/controller/projection_test.go @@ -7,62 +7,56 @@ import ( apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client/fake" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" ) func TestReleasedAllocationTerminallyRevokesProjection(t *testing.T) { - scheme := runtime.NewScheme() - if err := fleetv1alpha1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } + scheme := testScheme(t) now := time.Unix(1000, 0).UTC() - binding := &fleetv1alpha1.MachineManagementSessionBinding{ - ObjectMeta: metav1.ObjectMeta{Name: "session-uid", Namespace: SystemNamespace}, - Spec: fleetv1alpha1.MachineManagementSessionBindingSpec{ - SessionUID: "session-uid", ClaimUID: "claim-uid", MachineUID: "machine-uid", - BindingID: "binding", BindingEpoch: 1, LocationUID: "location", LocationRevision: "r1", - MemberCluster: "cell-a", AdapterRoute: "sushy-libvirt-v1", ExpiresAt: metav1.NewTime(now.Add(time.Hour)), - }, - } - allocation := &fleetv1alpha1.MachineAllocationBinding{ - ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: SystemNamespace, Labels: map[string]string{ClaimUIDLabel: "claim-uid"}}, - Spec: fleetv1alpha1.MachineAllocationBindingSpec{ClaimUID: "claim-uid", MachineUID: "machine-uid", BindingID: "binding", BindingEpoch: 1, LocationUID: "location", LocationRevision: "r1", MemberCluster: "cell-a", AdapterRoute: "sushy-libvirt-v1", Active: false}, - } - projection := &fleetv1alpha1.ProjectedMachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: binding.Name, Namespace: LocationNamespace, Labels: map[string]string{MemberClusterLabel: "cell-a"}}, Spec: fleetv1alpha1.ProjectedMachineManagementSessionSpec{DesiredState: fleetv1alpha1.ProjectionActive, SessionUID: "session-uid", ClaimUID: "claim-uid", MachineUID: "machine-uid", BindingID: "binding", BindingEpoch: 1, LocationUID: "location", LocationRevision: "r1", AdapterRoute: "sushy-libvirt-v1", ExpiresAt: metav1.NewTime(now.Add(time.Hour))}} - primary := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(binding).WithObjects(binding, allocation).Build() + machine := testMachine("machine-uid") + allocation := testAllocation(machine.UID) + allocation.Status.Phase = "Released" + capacity := testCapacity() + binding := &sessionv1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Name: "mms-internal", Namespace: SystemNamespace}, Spec: sessionv1.MachineManagementSessionBindingSpec{ + SessionUID: "session-uid", ConsumerProject: "consumer", ProviderProject: "provider", MachineNamespace: "default", MachineName: "db-01", MachineUID: machine.UID, + AllocationName: allocation.Name, AllocationUID: allocation.UID, MachineCapacityNamespace: capacity.Namespace, MachineCapacityName: capacity.Name, MachineCapacityUID: capacity.UID, + DeviceName: "device-a", LocationName: "location", MemberCluster: "cell-a", Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", ConnectBefore: metav1.NewTime(now.Add(time.Minute)), ExpiresAt: metav1.NewTime(now.Add(time.Hour)), + }} + projection := &sessionv1.ProjectedMachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: binding.Name, Namespace: LocationNamespace, Labels: map[string]string{MemberClusterLabel: "cell-a"}}, Spec: sessionv1.ProjectedMachineManagementSessionSpec{DesiredState: sessionv1.ProjectionActive, MachineCapacityRef: sessionv1.LocalReference{Name: capacity.Name}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", ConnectBefore: binding.Spec.ConnectBefore, ExpiresAt: binding.Spec.ExpiresAt}} + primary := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(binding).WithObjects(binding, machine, allocation, capacity).Build() federation := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(projection).WithObjects(projection).Build() r := &ProjectionReconciler{Client: primary, FederationClient: federation, Now: func() time.Time { return now }} - _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: SystemNamespace, Name: binding.Name}}) - if err != nil { + req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: SystemNamespace, Name: binding.Name}} + if _, err := r.Reconcile(context.Background(), req); err != nil { t.Fatal(err) } - var got fleetv1alpha1.MachineManagementSessionBinding - if err := primary.Get(context.Background(), types.NamespacedName{Namespace: SystemNamespace, Name: binding.Name}, &got); err != nil { + var got sessionv1.MachineManagementSessionBinding + if err := primary.Get(context.Background(), req.NamespacedName, &got); err != nil { t.Fatal(err) } if got.Annotations[RevokedAtAnnotation] == "" { t.Fatal("released allocation did not permanently revoke admitted binding") } - var revoked fleetv1alpha1.ProjectedMachineManagementSession - if err := federation.Get(context.Background(), types.NamespacedName{Namespace: LocationNamespace, Name: binding.Name}, &revoked); err != nil { + var revoked sessionv1.ProjectedMachineManagementSession + key := types.NamespacedName{Namespace: LocationNamespace, Name: binding.Name} + if err := federation.Get(context.Background(), key, &revoked); err != nil { t.Fatal(err) } - if revoked.Spec.DesiredState != fleetv1alpha1.ProjectionRevoked { + if revoked.Spec.DesiredState != sessionv1.ProjectionRevoked { t.Fatal("allocation release was not propagated as revocation") } apimeta.SetStatusCondition(&revoked.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, Reason: "GatewayStopped", Message: "stopped", ObservedGeneration: revoked.Generation}) if err := federation.Status().Update(context.Background(), &revoked); err != nil { t.Fatal(err) } - if _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: types.NamespacedName{Namespace: SystemNamespace, Name: binding.Name}}); err != nil { + if _, err := r.Reconcile(context.Background(), req); err != nil { t.Fatal(err) } - if err := federation.Get(context.Background(), types.NamespacedName{Namespace: LocationNamespace, Name: binding.Name}, &revoked); err == nil { + if err := federation.Get(context.Background(), key, &revoked); err == nil { t.Fatal("acknowledged federated projection survived cleanup") } } diff --git a/internal/controller/session.go b/internal/controller/session.go index 2c8db076..1676da86 100644 --- a/internal/controller/session.go +++ b/internal/controller/session.go @@ -22,20 +22,26 @@ import ( "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/reconcile" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" fleetmetrics "go.datum.net/fleet/internal/metrics" ) const ( - SystemNamespace = "fleet-system" - LocationNamespace = "machine-access-system" - PrincipalAnnotation = "fleet.datumapis.com/requesting-principal" - ClaimUIDLabel = "fleet.datumapis.com/claim-uid" - SessionUIDLabel = "fleet.datumapis.com/session-uid" - RevokedAtAnnotation = "fleet.datumapis.com/revoked-at" - MemberClusterLabel = "fleet.datumapis.com/member-cluster" - DefaultConnectWindow = time.Minute - DefaultAuthorityFreshness = 2 * time.Minute + SystemNamespace = "fleet-system" + LocationNamespace = "machine-access-system" + PrincipalAnnotation = "fleet.datumapis.com/requesting-principal" + MachineUIDLabel = "fleet.datumapis.com/machine-uid" + AllocationNameLabel = "fleet.datumapis.com/allocation-name" + SessionUIDLabel = "fleet.datumapis.com/session-uid" + RevokedAtAnnotation = "fleet.datumapis.com/revoked-at" + MemberClusterLabel = "fleet.datumapis.com/member-cluster" + MemberClusterAnnotation = "fleet.datumapis.com/member-cluster" + ProviderProjectAnnotation = "fleet.datumapis.com/provider-project" + LocationNameAnnotation = "fleet.datumapis.com/location-name" + AllocationMachineUIDAnnotation = "fleet.datumapis.com/machine-uid" + DefaultConnectWindow = time.Minute + DefaultAuthorityFreshness = 2 * time.Minute ) type SessionReconciler struct { @@ -64,19 +70,14 @@ func (r *SessionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct if session.UID == "" { return ctrl.Result{RequeueAfter: time.Second}, nil } - bindingName := string(session.UID) - var admitted fleetv1alpha1.MachineManagementSessionBinding - err := r.Get(ctx, types.NamespacedName{Namespace: r.systemNamespace(), Name: bindingName}, &admitted) - if apierrors.IsNotFound(err) { + admitted, err := r.bindingForSession(ctx, session.UID) + if err == nil && admitted == nil { return r.admit(ctx, &session) } if err != nil { return ctrl.Result{}, err } - if admitted.Spec.SessionUID != session.UID { - return ctrl.Result{}, fmt.Errorf("protected binding UID mismatch") - } - return r.reflect(ctx, &session, &admitted) + return r.reflect(ctx, &session, admitted) } func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.MachineManagementSession) (ctrl.Result, error) { @@ -84,26 +85,50 @@ func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.Ma if principal == "" { return r.reject(ctx, session, "PrincipalMissing", "Admission did not retain the authenticated principal.") } - var claim fleetv1alpha1.MachineClaim - key := types.NamespacedName{Namespace: session.Namespace, Name: session.Spec.MachineClaimRef.Name} - if err := r.Get(ctx, key, &claim); err != nil { + var machine fleetv1.Machine + key := types.NamespacedName{Namespace: session.Namespace, Name: session.Spec.MachineRef.Name} + if err := r.Get(ctx, key, &machine); err != nil { if apierrors.IsNotFound(err) { - return r.reject(ctx, session, "ClaimNotFound", "The MachineClaim does not exist.") + return r.reject(ctx, session, "MachineNotFound", "The Machine does not exist.") } return ctrl.Result{}, err } - var allocations fleetv1alpha1.MachineAllocationBindingList - if err := r.List(ctx, &allocations, client.InNamespace(r.systemNamespace()), client.MatchingLabels{ClaimUIDLabel: string(claim.UID)}); err != nil { + var allocations fleetv1.MachineAllocationList + if err := r.List(ctx, &allocations, client.InNamespace(r.systemNamespace())); err != nil { + return ctrl.Result{}, err + } + matching := make([]*fleetv1.MachineAllocation, 0, 1) + for i := range allocations.Items { + a := &allocations.Items[i] + if a.Status.Phase == "Active" && a.Spec.MachineRef.Namespace == machine.Namespace && a.Spec.MachineRef.Name == machine.Name { + matching = append(matching, a) + } + } + if len(matching) != 1 { + return r.reject(ctx, session, "MachineNotAllocated", "The Machine does not have exactly one active authoritative allocation.") + } + a := matching[0] + if a.Annotations[AllocationMachineUIDAnnotation] != string(machine.UID) { + return r.reject(ctx, session, "AllocationChanged", "The active allocation does not belong to this Machine incarnation.") + } + var capacity fleetv1.MachineCapacity + capacityKey := types.NamespacedName{Namespace: a.Spec.MachineCapacityRef.Namespace, Name: a.Spec.MachineCapacityRef.Name} + if err := r.Get(ctx, capacityKey, &capacity); err != nil { + if apierrors.IsNotFound(err) { + return r.reject(ctx, session, "CapacityNotFound", "The allocated MachineCapacity is unavailable.") + } return ctrl.Result{}, err } - if len(allocations.Items) != 1 || !allocations.Items[0].Spec.Active { - return r.reject(ctx, session, "ClaimNotActive", "The MachineClaim has no active authoritative allocation.") + member := a.Annotations[MemberClusterAnnotation] + location := a.Annotations[LocationNameAnnotation] + providerProject := a.Annotations[ProviderProjectAnnotation] + if member == "" || location == "" { + return r.reject(ctx, session, "LocationNotFederated", "The allocation location has no registered federation member.") } - a := allocations.Items[0] - if a.Spec.ClaimUID != claim.UID || a.Spec.ClaimName != claim.Name || a.Spec.ClaimNamespace != claim.Namespace { - return r.reject(ctx, session, "AllocationChanged", "The retained allocation does not match this claim incarnation.") + if providerProject == "" || capacity.Spec.DeviceRef.Name == "" { + return r.reject(ctx, session, "ProviderTargetUnresolved", "The allocation does not resolve to registered provider capacity.") } - if result, err := r.enforceLimits(ctx, a.Spec.ConsumerProjectUID, claim.UID); err != nil || result != nil { + if result, err := r.enforceLimits(ctx, a.Spec.MachineRef.Project, machine.UID); err != nil || result != nil { if err != nil { return ctrl.Result{}, err } @@ -116,10 +141,23 @@ func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.Ma } connect := metav1.NewTime(now.Add(DefaultConnectWindow)) expiry := metav1.NewTime(now.Add(ttl)) - if a.Spec.MemberCluster == "" { - return r.reject(ctx, session, "LocationNotFederated", "The authoritative location has no registered federation member.") + b := &fleetv1alpha1.MachineManagementSessionBinding{ + TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSessionBinding"}, + ObjectMeta: metav1.ObjectMeta{Name: "mms-" + randomCorrelationID(), Namespace: r.systemNamespace(), Labels: map[string]string{ + SessionUIDLabel: string(session.UID), MachineUIDLabel: string(machine.UID), AllocationNameLabel: a.Name, + }}, + Spec: fleetv1alpha1.MachineManagementSessionBindingSpec{ + SessionNamespace: session.Namespace, SessionName: session.Name, SessionUID: session.UID, + RequestingPrincipal: principal, ConsumerProject: a.Spec.MachineRef.Project, ProviderProject: providerProject, + MachineNamespace: machine.Namespace, MachineName: machine.Name, MachineUID: machine.UID, + AllocationName: a.Name, AllocationUID: a.UID, + MachineCapacityNamespace: capacity.Namespace, MachineCapacityName: capacity.Name, MachineCapacityUID: capacity.UID, + DeviceName: capacity.Spec.DeviceRef.Name, LocationName: location, MemberCluster: member, + Protocol: session.Spec.Protocol, AccessProfile: session.Spec.AccessProfile, + ClientPublicKey: session.Spec.ClientPublicKey, ConnectBefore: connect, ExpiresAt: expiry, + SessionCorrelationID: randomCorrelationID(), OperationCorrelationID: randomCorrelationID(), + }, } - b := &fleetv1alpha1.MachineManagementSessionBinding{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSessionBinding"}, ObjectMeta: metav1.ObjectMeta{Name: string(session.UID), Namespace: r.systemNamespace(), Labels: map[string]string{SessionUIDLabel: string(session.UID), ClaimUIDLabel: string(claim.UID)}}, Spec: fleetv1alpha1.MachineManagementSessionBindingSpec{SessionNamespace: session.Namespace, SessionName: session.Name, SessionUID: session.UID, RequestingPrincipal: principal, ConsumerProjectUID: a.Spec.ConsumerProjectUID, ProviderProjectUID: a.Spec.ProviderProjectUID, ClaimName: claim.Name, ClaimUID: claim.UID, MachineName: a.Spec.MachineName, MachineUID: a.Spec.MachineUID, BindingID: a.Spec.BindingID, BindingEpoch: a.Spec.BindingEpoch, LocationUID: a.Spec.LocationUID, LocationRevision: a.Spec.LocationRevision, MemberCluster: a.Spec.MemberCluster, BareMetalMachineUID: a.Spec.BareMetalMachineUID, AccessProfileRevision: a.Spec.AccessProfileRevision, ClientPublicKey: session.Spec.ClientPublicKey, ConnectBefore: connect, ExpiresAt: expiry, SessionCorrelationID: randomCorrelationID(), OperationCorrelationID: randomCorrelationID(), AdapterRoute: a.Spec.AdapterRoute, BMCSystemID: a.Spec.BMCSystemID}} if err := r.Create(ctx, b); err != nil { if apierrors.IsAlreadyExists(err) { return ctrl.Result{Requeue: true}, nil @@ -128,28 +166,27 @@ func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.Ma } fleetmetrics.SessionAdmissions.WithLabelValues("admitted").Inc() slog.InfoContext(ctx, "machine-management session admitted", - "sessionUID", session.UID, "claimUID", claim.UID, "machineUID", a.Spec.MachineUID, - "bindingID", a.Spec.BindingID, "bindingEpoch", a.Spec.BindingEpoch, + "session", session.Name, "machine", machine.Name, "allocation", a.Name, "principal", principal, "sessionCorrelationID", b.Spec.SessionCorrelationID) return ctrl.Result{RequeueAfter: time.Second}, nil } -func (r *SessionReconciler) enforceLimits(ctx context.Context, projectUID, claimUID types.UID) (*string, error) { +func (r *SessionReconciler) enforceLimits(ctx context.Context, project string, machineUID types.UID) (*string, error) { var list fleetv1alpha1.MachineManagementSessionBindingList if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace())); err != nil { return nil, err } - claimCount, projectCount := 0, 0 + machineCount, projectCount := 0, 0 now := r.now() for i := range list.Items { b := &list.Items[i] if !b.Spec.ExpiresAt.After(now) || b.Annotations[RevokedAtAnnotation] != "" { continue } - if b.Spec.ClaimUID == claimUID { - claimCount++ + if b.Spec.MachineUID == machineUID { + machineCount++ } - if b.Spec.ConsumerProjectUID == projectUID { + if b.Spec.ConsumerProject == project { projectCount++ } } @@ -161,8 +198,8 @@ func (r *SessionReconciler) enforceLimits(ctx context.Context, projectUID, claim if pl == 0 { pl = 5 } - if claimCount >= cl { - s := fmt.Sprintf("The claim already has %d active session(s); limit is %d.", claimCount, cl) + if machineCount >= cl { + s := fmt.Sprintf("The Machine already has %d active session(s); limit is %d.", machineCount, cl) return &s, nil } if projectCount >= pl { @@ -204,7 +241,7 @@ func (r *SessionReconciler) reflect(ctx context.Context, s *fleetv1alpha1.Machin func (r *SessionReconciler) reject(ctx context.Context, s *fleetv1alpha1.MachineManagementSession, reason, message string) (ctrl.Result, error) { fleetmetrics.SessionAdmissions.WithLabelValues(reason).Inc() - slog.WarnContext(ctx, "machine-management session rejected", "sessionUID", s.UID, "reason", reason) + slog.WarnContext(ctx, "machine-management session rejected", "session", s.Name, "reason", reason) setCondition(&s.Status.Conditions, s.Generation, metav1.ConditionFalse, reason, message, r.now()) return ctrl.Result{}, r.Status().Update(ctx, s) } @@ -213,19 +250,18 @@ func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.Machine if !controllerutil.ContainsFinalizer(s, fleetv1alpha1.SessionFinalizer) { return ctrl.Result{}, nil } - var b fleetv1alpha1.MachineManagementSessionBinding - key := types.NamespacedName{Namespace: r.systemNamespace(), Name: string(s.UID)} - if err := r.Get(ctx, key, &b); err == nil { + b, err := r.bindingForSession(ctx, s.UID) + if err == nil && b != nil { if b.Annotations[RevokedAtAnnotation] == "" { patch := client.MergeFrom(b.DeepCopy()) if b.Annotations == nil { b.Annotations = map[string]string{} } b.Annotations[RevokedAtAnnotation] = r.now().UTC().Format(time.RFC3339Nano) - if err := r.Patch(ctx, &b, patch); err != nil { + if err := r.Patch(ctx, b, patch); err != nil { return ctrl.Result{}, err } - slog.InfoContext(ctx, "machine-management session revocation requested", "sessionUID", s.UID, "bindingID", b.Spec.BindingID, "sessionCorrelationID", b.Spec.SessionCorrelationID) + slog.InfoContext(ctx, "machine-management session revocation requested", "session", s.Name, "allocation", b.Spec.AllocationName, "sessionCorrelationID", b.Spec.SessionCorrelationID) } if c := apimeta.FindStatusCondition(b.Status.Conditions, "CleanupConfirmed"); c != nil && c.Status == metav1.ConditionTrue { fleetmetrics.RevocationLatency.Observe(r.now().Sub(s.DeletionTimestamp.Time).Seconds()) @@ -236,7 +272,7 @@ func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.Machine if r.now().After(s.DeletionTimestamp.Add(30 * time.Second)) { fleetmetrics.RevocationLatency.Observe(r.now().Sub(s.DeletionTimestamp.Time).Seconds()) setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionUnknown, "LocationUnconfirmed", "The location did not confirm session teardown.", r.now()) - if err := r.Status().Update(ctx, &b); err != nil { + if err := r.Status().Update(ctx, b); err != nil { return ctrl.Result{}, err } patch := client.MergeFrom(s.DeepCopy()) @@ -244,7 +280,7 @@ func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.Machine return ctrl.Result{}, r.Patch(ctx, s, patch) } return ctrl.Result{RequeueAfter: time.Second}, nil - } else if !apierrors.IsNotFound(err) { + } else if err != nil { return ctrl.Result{}, err } patch := client.MergeFrom(s.DeepCopy()) @@ -252,6 +288,20 @@ func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.Machine return ctrl.Result{}, r.Patch(ctx, s, patch) } +func (r *SessionReconciler) bindingForSession(ctx context.Context, uid types.UID) (*fleetv1alpha1.MachineManagementSessionBinding, error) { + var list fleetv1alpha1.MachineManagementSessionBindingList + if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace()), client.MatchingLabels{SessionUIDLabel: string(uid)}); err != nil { + return nil, err + } + if len(list.Items) == 0 { + return nil, nil + } + if len(list.Items) != 1 || list.Items[0].Spec.SessionUID != uid { + return nil, fmt.Errorf("expected one protected binding for session UID") + } + return &list.Items[0], nil +} + func (r *SessionReconciler) SetupWithManager(mgr ctrl.Manager) error { r.Client = mgr.GetClient() return ctrl.NewControllerManagedBy(mgr). diff --git a/internal/controller/session_test.go b/internal/controller/session_test.go index cc606605..b3f2ddea 100644 --- a/internal/controller/session_test.go +++ b/internal/controller/session_test.go @@ -9,59 +9,65 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" ) func testScheme(t *testing.T) *runtime.Scheme { t.Helper() s := runtime.NewScheme() - if err := fleetv1alpha1.AddToScheme(s); err != nil { + if err := fleetv1.AddToScheme(s); err != nil { + t.Fatal(err) + } + if err := sessionv1.AddToScheme(s); err != nil { t.Fatal(err) } return s } -func TestAdmissionPinsProtectedAllocation(t *testing.T) { +func TestAdmissionPinsMachineAllocationAndCapacity(t *testing.T) { scheme := testScheme(t) now := time.Unix(1000, 0) - claim := &fleetv1alpha1.MachineClaim{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineClaim"}, ObjectMeta: metav1.ObjectMeta{Name: "db-01", Namespace: "default", UID: "claim-uid"}} - allocation := testAllocation(claim.UID) + machine := testMachine("machine-uid") + allocation := testAllocation(machine.UID) + capacity := testCapacity() session := testSession("session-uid") - c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(session, &fleetv1alpha1.MachineManagementSessionBinding{}).WithObjects(claim, allocation, session).Build() + c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(session, &sessionv1.MachineManagementSessionBinding{}).WithObjects(machine, allocation, capacity, session).Build() r := &SessionReconciler{Client: c, Now: func() time.Time { return now }} req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "default", Name: "access"}} if _, err := r.Reconcile(context.Background(), req); err != nil { t.Fatal(err) - } // finalizer + } if _, err := r.Reconcile(context.Background(), req); err != nil { t.Fatal(err) - } // binding - var b fleetv1alpha1.MachineManagementSessionBinding - if err := c.Get(context.Background(), types.NamespacedName{Namespace: SystemNamespace, Name: "session-uid"}, &b); err != nil { + } + var bindings sessionv1.MachineManagementSessionBindingList + if err := c.List(context.Background(), &bindings, client.InNamespace(SystemNamespace)); err != nil { t.Fatal(err) } - if b.Spec.ClaimUID != "claim-uid" || b.Spec.MachineUID != "machine-uid" || b.Spec.ProviderProjectUID != "provider-project" || b.Spec.RequestingPrincipal != "alice@example.test" { - t.Fatalf("binding not pinned: %+v", b.Spec) + if len(bindings.Items) != 1 { + t.Fatalf("bindings=%d", len(bindings.Items)) } - if b.Spec.AdapterRoute == "" || b.Spec.BMCSystemID == "" { - t.Fatal("private adapter identity missing") + b := bindings.Items[0] + if b.Spec.MachineUID != machine.UID || b.Spec.AllocationUID != allocation.UID || b.Spec.MachineCapacityUID != capacity.UID || b.Spec.DeviceName != "device-a" || b.Spec.ProviderProject != "provider" || b.Spec.RequestingPrincipal != "alice@example.test" { + t.Fatalf("binding not pinned: %+v", b.Spec) } } -func TestRecreatedClaimNameCannotInheritAllocation(t *testing.T) { +func TestRecreatedMachineNameCannotInheritAllocation(t *testing.T) { scheme := testScheme(t) - claim := &fleetv1alpha1.MachineClaim{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineClaim"}, ObjectMeta: metav1.ObjectMeta{Name: "db-01", Namespace: "default", UID: "new-claim-uid"}} - allocation := testAllocation("old-claim-uid") - allocation.Labels[ClaimUIDLabel] = "new-claim-uid" // even a forged lookup label cannot change retained UID + machine := testMachine("new-machine-uid") + allocation := testAllocation("old-machine-uid") session := testSession("session-uid") - c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(session).WithObjects(claim, allocation, session).Build() + c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(session).WithObjects(machine, allocation, testCapacity(), session).Build() r := &SessionReconciler{Client: c} req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "default", Name: "access"}} _, _ = r.Reconcile(context.Background(), req) _, _ = r.Reconcile(context.Background(), req) - var got fleetv1alpha1.MachineManagementSession + var got sessionv1.MachineManagementSession if err := c.Get(context.Background(), req.NamespacedName, &got); err != nil { t.Fatal(err) } @@ -70,10 +76,18 @@ func TestRecreatedClaimNameCannotInheritAllocation(t *testing.T) { } } -func testSession(uid types.UID) *fleetv1alpha1.MachineManagementSession { - return &fleetv1alpha1.MachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{Name: "access", Namespace: "default", UID: uid, Annotations: map[string]string{PrincipalAnnotation: "alice@example.test"}}, Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineClaimRef: fleetv1alpha1.LocalObjectReference{Name: "db-01"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", TTL: metav1.Duration{Duration: 15 * time.Minute}}} +func testSession(uid types.UID) *sessionv1.MachineManagementSession { + return &sessionv1.MachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: sessionv1.GroupVersion.String(), Kind: "MachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{Name: "access", Namespace: "default", UID: uid, Annotations: map[string]string{PrincipalAnnotation: "alice@example.test"}}, Spec: sessionv1.MachineManagementSessionSpec{MachineRef: sessionv1.LocalReference{Name: "db-01"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", TTL: metav1.Duration{Duration: 15 * time.Minute}}} +} + +func testMachine(uid types.UID) *fleetv1.Machine { + return &fleetv1.Machine{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1.GroupVersion.String(), Kind: "Machine"}, ObjectMeta: metav1.ObjectMeta{Name: "db-01", Namespace: "default", UID: uid}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "class"}, MachineProfileRef: fleetv1.LocalReference{Name: "profile"}, LocationRef: fleetv1.LocalReference{Name: "location"}}} +} + +func testCapacity() *fleetv1.MachineCapacity { + return &fleetv1.MachineCapacity{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1.GroupVersion.String(), Kind: "MachineCapacity"}, ObjectMeta: metav1.ObjectMeta{Name: "capacity-a", Namespace: "provider-ns", UID: "capacity-uid"}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "device-a"}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "clean"}, ReclaimPolicy: "Retain"}} } -func testAllocation(claimUID types.UID) *fleetv1alpha1.MachineAllocationBinding { - return &fleetv1alpha1.MachineAllocationBinding{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineAllocationBinding"}, ObjectMeta: metav1.ObjectMeta{Name: "allocation", Namespace: SystemNamespace, Labels: map[string]string{ClaimUIDLabel: string(claimUID)}}, Spec: fleetv1alpha1.MachineAllocationBindingSpec{ConsumerProjectUID: "consumer-project", ProviderProjectUID: "provider-project", ClaimNamespace: "default", ClaimName: "db-01", ClaimUID: claimUID, MachineName: "machine-a", MachineUID: "machine-uid", BindingID: "binding-a", BindingEpoch: 7, LocationUID: "location-uid", LocationRevision: "location-r1", MemberCluster: "cell-a", BareMetalMachineUID: "bmm-uid", AccessProfileRevision: "provisioning-r1", AdapterRoute: "sushy-libvirt", BMCSystemID: "vm-allocated", Active: true}} +func testAllocation(machineUID types.UID) *fleetv1.MachineAllocation { + return &fleetv1.MachineAllocation{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1.GroupVersion.String(), Kind: "MachineAllocation"}, ObjectMeta: metav1.ObjectMeta{Name: "allocation-a", Namespace: SystemNamespace, UID: "allocation-uid", Annotations: map[string]string{AllocationMachineUIDAnnotation: string(machineUID), MemberClusterAnnotation: "cell-a", LocationNameAnnotation: "location", ProviderProjectAnnotation: "provider"}}, Spec: fleetv1.MachineAllocationSpec{MachineRef: fleetv1.ProjectNamespacedReference{Project: "consumer", Namespace: "default", Name: "db-01"}, MachineCapacityRef: fleetv1.NamespacedReference{Namespace: "provider-ns", Name: "capacity-a"}}, Status: fleetv1.MachineAllocationStatus{Phase: "Active"}} } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index abd76824..eb30a9dc 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -14,21 +14,26 @@ import ( "encoding/hex" "encoding/pem" "errors" + "fmt" "math/big" "net" "net/http" "os" "path/filepath" + "reflect" + "strings" "sync" "time" + corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/journal" fleetmetrics "go.datum.net/fleet/internal/metrics" "go.datum.net/fleet/internal/protocol" @@ -37,11 +42,13 @@ import ( ) const ( - HeaderTimestamp = "X-Datum-Fleet-Timestamp" - HeaderNonce = "X-Datum-Fleet-Nonce" - HeaderSignature = "X-Datum-Fleet-Signature" - HeaderSession = "X-Datum-Fleet-Session" - HeaderAudience = "X-Datum-Fleet-Audience" + HeaderTimestamp = "X-Datum-Fleet-Timestamp" + HeaderNonce = "X-Datum-Fleet-Nonce" + HeaderSignature = "X-Datum-Fleet-Signature" + HeaderSession = "X-Datum-Fleet-Session" + HeaderAudience = "X-Datum-Fleet-Audience" + EnrollmentDeviceLabel = "fleet.datumapis.com/device-name" + DefaultEnrollmentNamespace = "machine-access-system" ) type Config struct { @@ -49,10 +56,8 @@ type Config struct { RelayPublicURL string RelayGatewayToken string Audience string - AdapterRoute string - BMCBaseURL string - BMCUsername string - BMCPassword string + SupportedAdapter string + EnrollmentNamespace string JournalDir string StateDir string DropResetResponseOnce bool @@ -69,6 +74,17 @@ type activeSession struct { cancel context.CancelFunc mu sync.RWMutex spec fleetv1alpha1.ProjectedMachineManagementSessionSpec + target resolvedTarget +} + +type resolvedTarget struct { + MachineCapacityName string + DeviceName string + Adapter string + BaseURL string + SystemID string + Username string + Password string } func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -99,18 +115,20 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu setCondition(&p, metav1.ConditionFalse, "ConnectWindowExpired", "No client connected before the admitted connection deadline.") return ctrl.Result{}, r.Status().Update(ctx, &p) } - if p.Spec.AdapterRoute != r.Config.AdapterRoute { - setCondition(&p, metav1.ConditionFalse, "AdapterRouteRejected", "The projected adapter route is not served by this gateway.") - return ctrl.Result{}, r.Status().Update(ctx, &p) - } r.mu.Lock() if r.active == nil { r.active = map[client.ObjectKey]*activeSession{} } a := r.active[req.NamespacedName] if a == nil { + target, err := r.resolveTarget(ctx, p.Spec) + if err != nil { + r.mu.Unlock() + setCondition(&p, metav1.ConditionFalse, "ManagementUnavailable", "The allocated capacity does not have a verified local management enrollment.") + return ctrl.Result{RequeueAfter: 5 * time.Second}, r.Status().Update(ctx, &p) + } runCtx, cancel := context.WithCancel(context.Background()) - a = &activeSession{cancel: cancel, spec: p.Spec} + a = &activeSession{cancel: cancel, spec: p.Spec, target: target} r.active[req.NamespacedName] = a go r.run(runCtx, req.NamespacedName, a) } else { @@ -167,16 +185,16 @@ func (r *Reconciler) run(ctx context.Context, key client.ObjectKey, a *activeSes } r.connectedStatus(key) a.mu.RLock() - spec := a.spec + target := a.target a.mu.RUnlock() - adapter := &redfish.SushyAdapter{BaseURL: r.Config.BMCBaseURL, SystemID: spec.BMCSystemID, Username: r.Config.BMCUsername, Password: r.Config.BMCPassword, DropResetResponseOnce: r.Config.DropResetResponseOnce} + adapter := &redfish.SushyAdapter{BaseURL: target.BaseURL, SystemID: target.SystemID, Username: target.Username, Password: target.Password, DropResetResponseOnce: r.Config.DropResetResponseOnce} h := &redfish.Handler{Adapter: adapter, Journal: store, CurrentAuthority: func() redfish.Authority { a.mu.RLock() defer a.mu.RUnlock() s := a.spec - return redfish.Authority{SessionUID: string(s.SessionUID), SessionCorrelationID: s.SessionCorrelationID, OperationCorrelationID: s.OperationCorrelationID, ClaimUID: string(s.ClaimUID), MachineUID: string(s.MachineUID), BindingID: s.BindingID, BindingEpoch: s.BindingEpoch, AdapterRoute: s.AdapterRoute, OperationEpoch: 1, ExpiresAt: s.ExpiresAt.Time, FreshUntil: s.AuthorityFreshUntil.Time} + return redfish.Authority{SessionName: key.Name, MachineCapacityName: target.MachineCapacityName, DeviceName: target.DeviceName, OperationEpoch: 1, ExpiresAt: s.ExpiresAt.Time, FreshUntil: s.AuthorityFreshUntil.Time} }} - protected := r.proofMiddleware(a, h) + protected := r.proofMiddleware(a, routeID, h) tlsConn := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13, NextProtos: []string{"datum-fleet-redfish/1"}}) // The relay admits one connector for the session, so an HTTP idle timeout // would permanently strand a valid session during a long PXE boot. Expiry, @@ -200,19 +218,19 @@ func (r *Reconciler) dialRelay(ctx context.Context, routeID string) (net.Conn, e return c, nil } -func (r *Reconciler) proofMiddleware(a *activeSession, next http.Handler) http.Handler { +func (r *Reconciler) proofMiddleware(a *activeSession, routeID string, next http.Handler) http.Handler { used := map[string]bool{} var mu sync.Mutex return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { a.mu.RLock() spec := a.spec a.mu.RUnlock() - if req.Header.Get(HeaderSession) != string(spec.SessionUID) || req.Header.Get(HeaderAudience) != r.Config.Audience { + if req.Header.Get(HeaderSession) != routeID || req.Header.Get(HeaderAudience) != r.Config.Audience { http.Error(w, "session proof target mismatch", http.StatusUnauthorized) return } proof := protocol.Proof{Timestamp: req.Header.Get(HeaderTimestamp), Nonce: req.Header.Get(HeaderNonce), Signature: req.Header.Get(HeaderSignature)} - err := protocol.Verify(spec.ClientPublicKey, string(spec.SessionUID), r.Config.Audience, proof, time.Now(), func(n string) bool { + err := protocol.Verify(spec.ClientPublicKey, routeID, r.Config.Audience, proof, time.Now(), func(n string) bool { mu.Lock() defer mu.Unlock() if used[n] { @@ -277,12 +295,47 @@ func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr).For(&fleetv1alpha1.ProjectedMachineManagementSession{}).Complete(r) } +func (r *Reconciler) resolveTarget(ctx context.Context, spec fleetv1alpha1.ProjectedMachineManagementSessionSpec) (resolvedTarget, error) { + namespace := r.Config.EnrollmentNamespace + if namespace == "" { + namespace = DefaultEnrollmentNamespace + } + var capacity fleetv1.MachineCapacity + if err := r.Get(ctx, client.ObjectKey{Namespace: namespace, Name: spec.MachineCapacityRef.Name}, &capacity); err != nil { + return resolvedTarget{}, err + } + if capacity.Spec.DeviceRef.Name == "" { + return resolvedTarget{}, fmt.Errorf("MachineCapacity has no deviceRef") + } + var secrets corev1.SecretList + if err := r.List(ctx, &secrets, client.InNamespace(namespace), client.MatchingLabels{EnrollmentDeviceLabel: capacity.Spec.DeviceRef.Name}); err != nil { + return resolvedTarget{}, err + } + if len(secrets.Items) != 1 { + return resolvedTarget{}, fmt.Errorf("expected one management enrollment") + } + data := secrets.Items[0].Data + target := resolvedTarget{ + MachineCapacityName: capacity.Name, + DeviceName: capacity.Spec.DeviceRef.Name, + Adapter: strings.TrimSpace(string(data["adapter"])), + BaseURL: strings.TrimSpace(string(data["endpoint"])), + SystemID: strings.TrimSpace(string(data["system-id"])), + Username: strings.TrimSpace(string(data["username"])), + Password: strings.TrimSpace(string(data["password"])), + } + if target.Adapter == "" || target.Adapter != r.Config.SupportedAdapter || target.BaseURL == "" || target.SystemID == "" || target.Username == "" || target.Password == "" { + return resolvedTarget{}, fmt.Errorf("management enrollment is incomplete or unsupported") + } + return target, nil +} + func sameBinding(a, b fleetv1alpha1.ProjectedMachineManagementSessionSpec) bool { a.AuthorityFreshUntil = metav1.Time{} b.AuthorityFreshUntil = metav1.Time{} a.DesiredState = "" b.DesiredState = "" - return a.SessionUID == b.SessionUID && a.ClaimUID == b.ClaimUID && a.MachineUID == b.MachineUID && a.BindingID == b.BindingID && a.BindingEpoch == b.BindingEpoch && a.LocationUID == b.LocationUID && a.LocationRevision == b.LocationRevision && a.BareMetalMachineUID == b.BareMetalMachineUID && a.AccessProfileRevision == b.AccessProfileRevision && a.ClientPublicKey == b.ClientPublicKey && a.ConnectBefore.Equal(&b.ConnectBefore) && a.ExpiresAt.Equal(&b.ExpiresAt) && a.AdapterRoute == b.AdapterRoute && a.BMCSystemID == b.BMCSystemID + return reflect.DeepEqual(a, b) } func setCondition(p *fleetv1alpha1.ProjectedMachineManagementSession, status metav1.ConditionStatus, reason, message string) { apimeta.SetStatusCondition(&p.Status.Conditions, metav1.Condition{Type: fleetv1alpha1.ConditionReady, Status: status, Reason: reason, Message: message, ObservedGeneration: p.Generation, LastTransitionTime: metav1.Now()}) diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index cda87209..fe832715 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -1,34 +1,53 @@ package gateway import ( + "context" "testing" "time" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" - fleetv1alpha1 "go.datum.net/fleet/api/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" ) func TestBindingInputsCannotChangeAfterGatewayAcceptance(t *testing.T) { a := fleetv1alpha1.ProjectedMachineManagementSessionSpec{ - SessionUID: "session", ClaimUID: "claim", MachineUID: "machine", - BindingID: "binding", BindingEpoch: 1, LocationUID: "location", LocationRevision: "r1", - BareMetalMachineUID: "bmm", AccessProfileRevision: "profile", ClientPublicKey: "key", + MachineCapacityRef: fleetv1alpha1.LocalReference{Name: "capacity"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", ConnectBefore: metav1.NewTime(time.Unix(100, 0)), ExpiresAt: metav1.NewTime(time.Unix(200, 0)), - AuthorityFreshUntil: metav1.NewTime(time.Unix(110, 0)), AdapterRoute: "adapter", BMCSystemID: "physical", + AuthorityFreshUntil: metav1.NewTime(time.Unix(110, 0)), } b := a b.AuthorityFreshUntil = metav1.NewTime(time.Unix(120, 0)) if !sameBinding(a, b) { t.Fatal("authority freshness was not refreshable") } - b.AdapterRoute = "changed" + b.MachineCapacityRef.Name = "changed" if sameBinding(a, b) { - t.Fatal("changed adapter route was accepted") + t.Fatal("changed capacity was accepted") } - b = a - b.BindingEpoch++ - if sameBinding(a, b) { - t.Fatal("changed binding epoch was accepted") +} + +func TestEnrollmentResolutionUsesCapacityDeviceNotCustomerTarget(t *testing.T) { + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := fleetv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "allocated", Namespace: DefaultEnrollmentNamespace}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "device-a"}}} + enrollment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "device-a", Namespace: DefaultEnrollmentNamespace, Labels: map[string]string{EnrollmentDeviceLabel: "device-a"}}, Data: map[string][]byte{"adapter": []byte("sushy-libvirt-v1"), "endpoint": []byte("https://private.invalid"), "system-id": []byte("physical-a"), "username": []byte("user"), "password": []byte("pass")}} + foreign := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "device-b", Namespace: DefaultEnrollmentNamespace, Labels: map[string]string{EnrollmentDeviceLabel: "device-b"}}, Data: map[string][]byte{"adapter": []byte("sushy-libvirt-v1"), "endpoint": []byte("https://foreign.invalid"), "system-id": []byte("physical-b"), "username": []byte("user"), "password": []byte("pass")}} + r := &Reconciler{Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(capacity, enrollment, foreign).Build(), Config: Config{SupportedAdapter: "sushy-libvirt-v1"}} + target, err := r.resolveTarget(context.Background(), fleetv1alpha1.ProjectedMachineManagementSessionSpec{MachineCapacityRef: fleetv1alpha1.LocalReference{Name: "allocated"}}) + if err != nil { + t.Fatal(err) + } + if target.DeviceName != "device-a" || target.SystemID != "physical-a" || target.BaseURL != "https://private.invalid" { + t.Fatalf("wrong enrollment resolved: %+v", target) } } diff --git a/internal/journal/journal.go b/internal/journal/journal.go index bcd7f1b3..8f503f96 100644 --- a/internal/journal/journal.go +++ b/internal/journal/journal.go @@ -26,32 +26,27 @@ const ( ) type Operation struct { - ID string `json:"id"` - SessionUID string `json:"sessionUID"` - SessionCorrelationID string `json:"sessionCorrelationID"` - OperationCorrelationID string `json:"operationCorrelationID"` - ClaimUID string `json:"claimUID"` - MachineUID string `json:"machineUID"` - BindingID string `json:"bindingID"` - BindingEpoch int64 `json:"bindingEpoch"` - Method string `json:"method"` - VirtualTarget string `json:"virtualTarget"` - AcceptedBody json.RawMessage `json:"acceptedBody"` - PhysicalTarget string `json:"physicalTarget"` - IdempotencyIdentity string `json:"idempotencyIdentity"` - OperationEpoch int64 `json:"operationEpoch"` - ConflictPrecondition string `json:"conflictPrecondition"` - AdapterRoute string `json:"adapterRoute"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` - Outcome Outcome `json:"outcome"` - Evidence string `json:"evidence,omitempty"` - HTTPStatus int `json:"httpStatus,omitempty"` + ID string `json:"id"` + SessionName string `json:"sessionName"` + MachineCapacityName string `json:"machineCapacityName"` + DeviceName string `json:"deviceName"` + Method string `json:"method"` + VirtualTarget string `json:"virtualTarget"` + AcceptedBody json.RawMessage `json:"acceptedBody"` + PhysicalTarget string `json:"physicalTarget"` + IdempotencyIdentity string `json:"idempotencyIdentity"` + OperationEpoch int64 `json:"operationEpoch"` + ConflictPrecondition string `json:"conflictPrecondition"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + Outcome Outcome `json:"outcome"` + Evidence string `json:"evidence,omitempty"` + HTTPStatus int `json:"httpStatus,omitempty"` } -func Identity(sessionUID, method, target string, body []byte) string { +func Identity(sessionName, method, target string, body []byte) string { h := sha256.New() - _, _ = fmt.Fprintf(h, "%s\n%s\n%s\n", sessionUID, method, target) + _, _ = fmt.Fprintf(h, "%s\n%s\n%s\n", sessionName, method, target) _, _ = h.Write(body) return hex.EncodeToString(h.Sum(nil)) } diff --git a/internal/journal/journal_test.go b/internal/journal/journal_test.go index 35f20a98..168d511d 100644 --- a/internal/journal/journal_test.go +++ b/internal/journal/journal_test.go @@ -12,7 +12,7 @@ func TestAdmissionIsDurableAndDeduplicated(t *testing.T) { if err != nil { t.Fatal(err) } - op := Operation{ID: "op-1", MachineUID: "machine-1", Method: "POST", VirtualTarget: "/reset", AcceptedBody: json.RawMessage(`{"ResetType":"On"}`)} + op := Operation{ID: "op-1", DeviceName: "device-1", Method: "POST", VirtualTarget: "/reset", AcceptedBody: json.RawMessage(`{"ResetType":"On"}`)} if _, fresh, err := s.Admit(op); err != nil || !fresh { t.Fatalf("admit fresh=%v err=%v", fresh, err) } diff --git a/internal/redfish/handler.go b/internal/redfish/handler.go index 6321e9c4..38b7353c 100644 --- a/internal/redfish/handler.go +++ b/internal/redfish/handler.go @@ -4,6 +4,7 @@ package redfish import ( "crypto/rand" + "crypto/sha256" "encoding/base64" "encoding/json" "errors" @@ -22,17 +23,12 @@ import ( const SystemID = "allocated" type Authority struct { - SessionUID string - SessionCorrelationID string - OperationCorrelationID string - ClaimUID string - MachineUID string - BindingID string - BindingEpoch int64 - AdapterRoute string - OperationEpoch int64 - ExpiresAt time.Time - FreshUntil time.Time + SessionName string + MachineCapacityName string + DeviceName string + OperationEpoch int64 + ExpiresAt time.Time + FreshUntil time.Time } type Handler struct { @@ -114,7 +110,15 @@ func (h *Handler) checkRequest(r *http.Request) error { } func (h *Handler) serviceRoot(w http.ResponseWriter) { - writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ServiceRoot.v1_15_0.ServiceRoot", "@odata.id": "/redfish/v1/", "Id": "RootService", "Name": "Fleet Virtual Redfish Service", "RedfishVersion": "1.18.0", "UUID": h.authority().SessionUID, "Systems": odata("/redfish/v1/Systems"), "SessionService": odata("/redfish/v1/SessionService"), "TaskService": odata("/redfish/v1/TaskService")}) + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ServiceRoot.v1_15_0.ServiceRoot", "@odata.id": "/redfish/v1/", "Id": "RootService", "Name": "Fleet Virtual Redfish Service", "RedfishVersion": "1.18.0", "UUID": virtualUUID(h.authority().SessionName), "Systems": odata("/redfish/v1/Systems"), "SessionService": odata("/redfish/v1/SessionService"), "TaskService": odata("/redfish/v1/TaskService")}) +} + +func virtualUUID(sessionName string) string { + sum := sha256.Sum256([]byte("go.datum.net/fleet/redfish-service-root/v1\n" + sessionName)) + b := sum[:16] + b[6] = (b[6] & 0x0f) | 0x50 + b[8] = (b[8] & 0x3f) | 0x80 + return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) } func (h *Handler) sessionService(w http.ResponseWriter) { writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#SessionService.v1_2_0.SessionService", "@odata.id": "/redfish/v1/SessionService", "Id": "SessionService", "Name": "Session Service", "ServiceEnabled": true, "SessionTimeout": 900, "Sessions": odata("/redfish/v1/SessionService/Sessions")}) @@ -219,10 +223,10 @@ func (h *Handler) mutate(w http.ResponseWriter, r *http.Request, raw []byte, eff writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.AuthorityStale", "Allocation authority is stale; the gateway has failed closed.") return } - id := journal.Identity(authority.SessionUID, r.Method, r.URL.Path, raw) - unlock := h.Journal.MachineLock(authority.MachineUID) + id := journal.Identity(authority.SessionName, r.Method, r.URL.Path, raw) + unlock := h.Journal.MachineLock(authority.DeviceName) defer unlock() - op, fresh, err := h.Journal.Admit(journal.Operation{ID: id, SessionUID: authority.SessionUID, SessionCorrelationID: authority.SessionCorrelationID, OperationCorrelationID: authority.OperationCorrelationID, ClaimUID: authority.ClaimUID, MachineUID: authority.MachineUID, BindingID: authority.BindingID, BindingEpoch: authority.BindingEpoch, Method: r.Method, VirtualTarget: r.URL.Path, AcceptedBody: append([]byte(nil), raw...), PhysicalTarget: h.Adapter.PhysicalTarget(), IdempotencyIdentity: id, OperationEpoch: authority.OperationEpoch, ConflictPrecondition: fmt.Sprintf("binding=%s epoch=%d fresh-before=%s", authority.BindingID, authority.BindingEpoch, authority.FreshUntil.UTC().Format(time.RFC3339)), AdapterRoute: authority.AdapterRoute}) + op, fresh, err := h.Journal.Admit(journal.Operation{ID: id, SessionName: authority.SessionName, MachineCapacityName: authority.MachineCapacityName, DeviceName: authority.DeviceName, Method: r.Method, VirtualTarget: r.URL.Path, AcceptedBody: append([]byte(nil), raw...), PhysicalTarget: h.Adapter.PhysicalTarget(), IdempotencyIdentity: id, OperationEpoch: authority.OperationEpoch, ConflictPrecondition: fmt.Sprintf("capacity=%s device=%s fresh-before=%s", authority.MachineCapacityName, authority.DeviceName, authority.FreshUntil.UTC().Format(time.RFC3339))}) if err != nil { writeError(w, http.StatusInternalServerError, "Fleet.1.0.JournalUnavailable", "The mutation could not be durably admitted.") return @@ -265,7 +269,7 @@ func (h *Handler) tasks(w http.ResponseWriter) { } members := make([]any, 0, len(operations)) for _, operation := range operations { - if operation.SessionUID == h.authority().SessionUID { + if operation.SessionName == h.authority().SessionName { members = append(members, odata("/redfish/v1/TaskService/Tasks/"+operation.ID)) } } @@ -273,7 +277,7 @@ func (h *Handler) tasks(w http.ResponseWriter) { } func (h *Handler) task(w http.ResponseWriter, id string) { op, err := h.Journal.Get(id) - if err != nil || op.SessionUID != h.authority().SessionUID { + if err != nil || op.SessionName != h.authority().SessionName { writeError(w, http.StatusNotFound, "Base.1.18.ResourceMissingAtURI", "Task not found.") return } diff --git a/internal/redfish/handler_test.go b/internal/redfish/handler_test.go index 5eb2c530..b388780d 100644 --- a/internal/redfish/handler_test.go +++ b/internal/redfish/handler_test.go @@ -40,7 +40,7 @@ func newHandler(t *testing.T, a Adapter) *Handler { t.Fatal(err) } now := time.Unix(1000, 0) - return &Handler{Adapter: a, Journal: s, Now: func() time.Time { return now }, Authority: Authority{SessionUID: "session", ClaimUID: "claim", MachineUID: "machine", BindingID: "binding", BindingEpoch: 7, AdapterRoute: "sushy-libvirt", OperationEpoch: 1, ExpiresAt: now.Add(time.Hour), FreshUntil: now.Add(time.Minute)}} + return &Handler{Adapter: a, Journal: s, Now: func() time.Time { return now }, Authority: Authority{SessionName: "session", MachineCapacityName: "capacity", DeviceName: "device", OperationEpoch: 1, ExpiresAt: now.Add(time.Hour), FreshUntil: now.Add(time.Minute)}} } func request(h http.Handler, method, path, body string) *httptest.ResponseRecorder { diff --git a/test/e2e/machine-management/seed/allocation.yaml b/test/e2e/machine-management/seed/allocation.yaml index ee340c1f..99c1df72 100644 --- a/test/e2e/machine-management/seed/allocation.yaml +++ b/test/e2e/machine-management/seed/allocation.yaml @@ -1,25 +1,23 @@ apiVersion: fleet.datumapis.com/v1alpha1 -kind: MachineAllocationBinding +kind: MachineCapacity +metadata: + name: allocated-capacity + namespace: fleet-provider +spec: + deviceRef: {name: device-allocated} + allocationPolicy: Enabled + cleaningPolicyRef: {name: synthetic-e2e} + reclaimPolicy: Retain +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: MachineAllocation metadata: name: db-01-allocation namespace: fleet-system - labels: - fleet.datumapis.com/claim-uid: CLAIM_UID + annotations: + fleet.datumapis.com/member-cluster: fleet-location-e2e + fleet.datumapis.com/location-name: location-e2e + fleet.datumapis.com/provider-project: datum-owned-hardware spec: - consumerProjectUID: 11111111-1111-4111-8111-111111111111 - providerProjectUID: 22222222-2222-4222-8222-222222222222 - claimNamespace: default - claimName: db-01 - claimUID: CLAIM_UID - machineName: synthetic-allocated - machineUID: 33333333-3333-4333-8333-333333333333 - bindingID: allocation-e2e-1 - bindingEpoch: 1 - locationUID: 44444444-4444-4444-8444-444444444444 - locationRevision: location-prototype-r1 - memberCluster: fleet-location-e2e - bareMetalMachineUID: 55555555-5555-4555-8555-555555555555 - accessProfileRevision: fleet-provisioning-v1.0.0 - adapterRoute: sushy-libvirt-v1 - bmcSystemID: allocated - active: true + machineRef: {project: project, namespace: default, name: db-01} + machineCapacityRef: {namespace: fleet-provider, name: allocated-capacity} diff --git a/test/e2e/machine-management/seed/location-management.yaml b/test/e2e/machine-management/seed/location-management.yaml new file mode 100644 index 00000000..9a4c35cb --- /dev/null +++ b/test/e2e/machine-management/seed/location-management.yaml @@ -0,0 +1,51 @@ +apiVersion: fleet.datumapis.com/v1alpha1 +kind: MachineCapacity +metadata: + name: allocated-capacity + namespace: machine-access-system +spec: + deviceRef: {name: device-allocated} + allocationPolicy: Enabled + cleaningPolicyRef: {name: synthetic-e2e} + reclaimPolicy: Retain +--- +apiVersion: v1 +kind: Secret +metadata: + name: enrollment-device-allocated + namespace: machine-access-system + labels: + fleet.datumapis.com/device-name: device-allocated +type: Opaque +stringData: + adapter: sushy-libvirt-v1 + endpoint: http://172.30.0.10:8000 + system-id: allocated + username: fleet-gateway + password: synthetic-e2e-only +--- +apiVersion: fleet.datumapis.com/v1alpha1 +kind: MachineCapacity +metadata: + name: db02-capacity + namespace: machine-access-system +spec: + deviceRef: {name: device-unallocated} + allocationPolicy: Enabled + cleaningPolicyRef: {name: synthetic-e2e} + reclaimPolicy: Retain +--- +apiVersion: v1 +kind: Secret +metadata: + name: enrollment-device-unallocated + namespace: machine-access-system + labels: + fleet.datumapis.com/device-name: device-unallocated +type: Opaque +stringData: + adapter: sushy-libvirt-v1 + endpoint: http://172.30.0.10:8000 + system-id: unallocated + username: fleet-gateway + password: synthetic-e2e-only diff --git a/test/e2e/machine-management/seed/claim.yaml b/test/e2e/machine-management/seed/machine.yaml similarity index 53% rename from test/e2e/machine-management/seed/claim.yaml rename to test/e2e/machine-management/seed/machine.yaml index fff045bb..8ae1dfe3 100644 --- a/test/e2e/machine-management/seed/claim.yaml +++ b/test/e2e/machine-management/seed/machine.yaml @@ -1,7 +1,10 @@ apiVersion: fleet.datumapis.com/v1alpha1 -kind: MachineClaim +kind: Machine metadata: name: db-01 namespace: default spec: machineClassRef: {name: synthetic-libvirt} + machineProfileRef: {name: synthetic-libvirt} + locationRef: {name: location-e2e} + powerState: "Off" diff --git a/test/e2e/machine-management/seed/test-identities.yaml b/test/e2e/machine-management/seed/test-identities.yaml index 6a46589e..ff0661c1 100644 --- a/test/e2e/machine-management/seed/test-identities.yaml +++ b/test/e2e/machine-management/seed/test-identities.yaml @@ -9,13 +9,13 @@ metadata: {name: fleet-viewer, namespace: default} apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: {name: fleet-authorized-claim-view, namespace: default} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machineclaim-viewer} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machine-viewer} subjects: [{kind: ServiceAccount, name: fleet-authorized, namespace: default}] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: {name: fleet-viewer-claim-view, namespace: default} -roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machineclaim-viewer} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machine-viewer} subjects: [{kind: ServiceAccount, name: fleet-viewer, namespace: default}] --- apiVersion: rbac.authorization.k8s.io/v1 From 865cb516431aa8077db986b191395e36278b4ccd Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 15:54:27 -0600 Subject: [PATCH 14/24] fix: update manager image build context --- .dockerignore | 2 -- build/manager.Dockerfile | 1 - 2 files changed, 3 deletions(-) diff --git a/.dockerignore b/.dockerignore index ead4d050..f026529a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,8 +1,6 @@ ** !go.mod !go.sum -!api/ -!api/** !cmd/ !cmd/** !internal/ diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index 092c5b2d..568e18a9 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -3,7 +3,6 @@ ARG TARGETOS TARGETARCH WORKDIR /src COPY go.mod go.sum ./ RUN go mod download -COPY api/ ./api/ COPY cmd/ ./cmd/ COPY internal/ ./internal/ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-manager ./cmd/fleet-manager \ From b70f7f3c9949ac7dcf32781bdd3ac9c5ba5d9941 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 16:08:16 -0600 Subject: [PATCH 15/24] test: allow first Karmada projection to settle --- .github/workflows/test-e2e.yml | 1 + hack/e2e/test.sh | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index f53e2436..eaf3047e 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -79,6 +79,7 @@ jobs: .e2e/validators .e2e/virtual-bmc/evidence .e2e/*.log + include-hidden-files: true if-no-files-found: ignore - name: Tear down if: always() diff --git a/hack/e2e/test.sh b/hack/e2e/test.sh index 140a03e7..0a3b8666 100755 --- a/hack/e2e/test.sh +++ b/hack/e2e/test.sh @@ -34,7 +34,10 @@ trap cleanup EXIT fail() { echo "FAIL: $*" >&2; exit 1; } wait_for() { local description=$1 command=$2 - for _ in $(seq 1 90); do eval "${command}" && return 0; sleep 1; done + # A freshly installed Karmada control plane can need more than 90 seconds to + # schedule the first Work and reflect member status on shared CI runners. + # Keep the bound explicit and configurable without weakening any assertion. + for _ in $(seq 1 "${FLEET_E2E_WAIT_SECONDS:-240}"); do eval "${command}" && return 0; sleep 1; done fail "timed out waiting for ${description}" } run_timeout() { From 75ae0b959e42cfb7887a7342ff17263f2da7591c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 16:26:10 -0600 Subject: [PATCH 16/24] ci: sanitize virtual BMC evidence artifacts --- .github/workflows/test-e2e.yml | 6 ++++++ hack/e2e/diagnostics.sh | 10 +++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index eaf3047e..5720856d 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -69,6 +69,11 @@ jobs: message=$(tr '\n' ' ' <"${RUNNER_TEMP}/fleet-e2e-error.txt" | sed 's/%/%25/g; s/\r/%0D/g; s/\n/%0A/g') echo "::error title=E2E failure::${message}" fi + - name: Prepare non-secret evidence for upload + if: always() + run: | + docker exec fleet-e2e-virtual-bmc sh -c \ + 'find /evidence -maxdepth 1 -type f ! -name "*.key" -exec chmod 0644 {} +' || true - name: Upload diagnostics and validator reports if: always() uses: actions/upload-artifact@v4 @@ -78,6 +83,7 @@ jobs: .e2e/diagnostics .e2e/validators .e2e/virtual-bmc/evidence + !.e2e/virtual-bmc/evidence/*.key .e2e/*.log include-hidden-files: true if-no-files-found: ignore diff --git a/hack/e2e/diagnostics.sh b/hack/e2e/diagnostics.sh index b7e49f97..f7c81556 100755 --- a/hack/e2e/diagnostics.sh +++ b/hack/e2e/diagnostics.sh @@ -24,5 +24,13 @@ fi docker logs fleet-e2e-virtual-bmc >"${OUT}/virtual-bmc.log" 2>&1 || true docker exec fleet-e2e-virtual-bmc virsh list --all >"${OUT}/libvirt-domains.txt" 2>&1 || true docker exec fleet-e2e-virtual-bmc virsh dumpxml allocated >"${OUT}/allocated-domain.xml" 2>&1 || true -if [[ -d "${E2E_DIR}/virtual-bmc/evidence" ]]; then cp -R "${E2E_DIR}/virtual-bmc/evidence" "${OUT}/"; fi +if [[ -d "${E2E_DIR}/virtual-bmc/evidence" ]]; then + # libvirt creates console logs as root. Make only non-secret evidence + # readable, and never copy the optional OpenVPN key into CI diagnostics. + docker exec fleet-e2e-virtual-bmc sh -c \ + 'find /evidence -maxdepth 1 -type f ! -name "*.key" -exec chmod 0644 {} +' >/dev/null 2>&1 || true + mkdir -p "${OUT}/evidence" + find "${E2E_DIR}/virtual-bmc/evidence" -maxdepth 1 -type f ! -name '*.key' \ + -exec cp {} "${OUT}/evidence/" \; +fi echo "diagnostics: ${OUT}" From b7aea9023ad586c3e8c21b0508bebca78f58e0b1 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 16:43:44 -0600 Subject: [PATCH 17/24] fix: make session binding admission idempotent --- hack/e2e/diagnostics.sh | 2 +- internal/controller/session.go | 12 +++++++++++- internal/controller/session_test.go | 17 +++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/hack/e2e/diagnostics.sh b/hack/e2e/diagnostics.sh index f7c81556..1b47aaa4 100755 --- a/hack/e2e/diagnostics.sh +++ b/hack/e2e/diagnostics.sh @@ -9,7 +9,7 @@ for cluster in management location; do if [[ -f "${kubeconfig}" ]]; then kubectl --kubeconfig "${kubeconfig}" get all,events -A -o wide >"${OUT}/${cluster}-resources.txt" 2>&1 || true kubectl --kubeconfig "${kubeconfig}" get machines,machinecapacities,machineallocations,machinemanagementsessions,machinemanagementsessionbindings,projectedmachinemanagementsessions -A -o yaml >"${OUT}/${cluster}-fleet.yaml" 2>&1 || true - kubectl --kubeconfig "${kubeconfig}" logs -A --all-containers --prefix --tail=-1 >"${OUT}/${cluster}-logs.txt" 2>&1 || true + kubectl --kubeconfig "${kubeconfig}" logs --all-namespaces --all-containers --prefix --tail=-1 >"${OUT}/${cluster}-logs.txt" 2>&1 || true if [[ "${cluster}" == location ]]; then kubectl --kubeconfig "${kubeconfig}" -n machine-access-system exec deployment/fleet-gateway -- \ sh -c 'for f in /var/lib/fleet/operations/*.json; do test -f "$f" && { echo "$f"; cat "$f"; }; done' \ diff --git a/internal/controller/session.go b/internal/controller/session.go index 1676da86..c2070863 100644 --- a/internal/controller/session.go +++ b/internal/controller/session.go @@ -5,6 +5,7 @@ package controller import ( "context" "crypto/rand" + "crypto/sha256" "encoding/hex" "fmt" "log/slog" @@ -143,7 +144,7 @@ func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.Ma expiry := metav1.NewTime(now.Add(ttl)) b := &fleetv1alpha1.MachineManagementSessionBinding{ TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSessionBinding"}, - ObjectMeta: metav1.ObjectMeta{Name: "mms-" + randomCorrelationID(), Namespace: r.systemNamespace(), Labels: map[string]string{ + ObjectMeta: metav1.ObjectMeta{Name: bindingName(session.UID), Namespace: r.systemNamespace(), Labels: map[string]string{ SessionUIDLabel: string(session.UID), MachineUIDLabel: string(machine.UID), AllocationNameLabel: a.Name, }}, Spec: fleetv1alpha1.MachineManagementSessionBindingSpec{ @@ -339,6 +340,15 @@ func randomCorrelationID() string { return hex.EncodeToString(b) } +// bindingName makes admission idempotent even while the controller-runtime +// cache is briefly stale after a successful create. The domain-separated hash +// is an opaque rendezvous name; the underlying Kubernetes UID remains only in +// the protected central binding and is never placed in the location payload. +func bindingName(uid types.UID) string { + sum := sha256.Sum256([]byte("fleet-machine-management-binding-v1\x00" + string(uid))) + return "mms-" + hex.EncodeToString(sum[:16]) +} + func equalityStatus(s *fleetv1alpha1.MachineManagementSession, b *fleetv1alpha1.MachineManagementSessionBinding) bool { return reflect.DeepEqual(s.Status.Connection, b.Status.Connection) && reflect.DeepEqual(s.Status.Conditions, b.Status.Conditions) && s.Status.ConnectBefore != nil && s.Status.ConnectBefore.Equal(&b.Spec.ConnectBefore) && s.Status.ExpiresAt != nil && s.Status.ExpiresAt.Equal(&b.Spec.ExpiresAt) } diff --git a/internal/controller/session_test.go b/internal/controller/session_test.go index b3f2ddea..b128dc9f 100644 --- a/internal/controller/session_test.go +++ b/internal/controller/session_test.go @@ -52,11 +52,28 @@ func TestAdmissionPinsMachineAllocationAndCapacity(t *testing.T) { t.Fatalf("bindings=%d", len(bindings.Items)) } b := bindings.Items[0] + if b.Name != bindingName(session.UID) { + t.Fatalf("binding name=%q, want deterministic opaque name %q", b.Name, bindingName(session.UID)) + } if b.Spec.MachineUID != machine.UID || b.Spec.AllocationUID != allocation.UID || b.Spec.MachineCapacityUID != capacity.UID || b.Spec.DeviceName != "device-a" || b.Spec.ProviderProject != "provider" || b.Spec.RequestingPrincipal != "alice@example.test" { t.Fatalf("binding not pinned: %+v", b.Spec) } } +func TestBindingNameIsStableAndOpaque(t *testing.T) { + uid := types.UID("b88ddb18-b190-455f-bc91-29331950ca41") + got := bindingName(uid) + if got != bindingName(uid) { + t.Fatal("binding name changed for the same session UID") + } + if got == bindingName(types.UID("another-session")) { + t.Fatal("different session UIDs produced the same binding name") + } + if got == "mms-"+string(uid) { + t.Fatal("binding name exposed the raw session UID") + } +} + func TestRecreatedMachineNameCannotInheritAllocation(t *testing.T) { scheme := testScheme(t) machine := testMachine("new-machine-uid") From c0cbf801d4adb3640d7f24748b76f376b3f7f9e4 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 17:01:03 -0600 Subject: [PATCH 18/24] fix: retain current service catalog dependency --- go.mod | 6 +++--- go.sum | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index d16fda69..0bb8317b 100644 --- a/go.mod +++ b/go.mod @@ -9,14 +9,16 @@ require ( go.datum.net/network-services-operator v0.28.5-0.20260925153938-d7fdc43f8524 go.miloapis.com/locations v0.0.0-20260825185141-507ac2cbd48c go.miloapis.com/milo v0.32.5 - go.miloapis.com/service-catalog v0.3.2-0.20260714005215-6a3cddd298b0 + go.miloapis.com/service-catalog v0.13.1 go.yaml.in/yaml/v3 v3.0.4 golang.org/x/sys v0.47.0 k8s.io/api v0.37.2 + k8s.io/apiextensions-apiserver v0.37.0 k8s.io/apimachinery v0.37.2 k8s.io/client-go v0.37.2 k8s.io/utils v0.0.0-20260626114624-be93311217bd sigs.k8s.io/controller-runtime v0.25.2 + sigs.k8s.io/yaml v1.6.0 ) require ( @@ -69,12 +71,10 @@ require ( google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - k8s.io/apiextensions-apiserver v0.37.0 // indirect k8s.io/klog/v2 v2.140.0 // indirect k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect sigs.k8s.io/gateway-api v1.5.1 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect - sigs.k8s.io/yaml v1.6.0 // indirect ) diff --git a/go.sum b/go.sum index da33c125..71398a4c 100644 --- a/go.sum +++ b/go.sum @@ -129,8 +129,8 @@ go.miloapis.com/locations v0.0.0-20260825185141-507ac2cbd48c h1:+BQirT3wYCgv7H2l go.miloapis.com/locations v0.0.0-20260825185141-507ac2cbd48c/go.mod h1:gzfAfHhSMwl/N68k/uSNYXOKK3IOBJCdXYaBgCE3gdE= go.miloapis.com/milo v0.32.5 h1:08tMRuw9jivqJb8XlOOp53usQLmLOncrZSXfmrNIm0Y= go.miloapis.com/milo v0.32.5/go.mod h1:GKK3afjCwshfZfvhjNe1wp/H45z4m7x5oG/8xbSgU1M= -go.miloapis.com/service-catalog v0.3.2-0.20260714005215-6a3cddd298b0 h1:jRjiHCZZt1NO1BGujbq925KgDd/YATPWO8jiWub6UbU= -go.miloapis.com/service-catalog v0.3.2-0.20260714005215-6a3cddd298b0/go.mod h1:chpaRFLTMODPZBEc7gOx3/e58loYBPSKHCojdKompXA= +go.miloapis.com/service-catalog v0.13.1 h1:KZzyFrcDg7aUqZNcUXrU5m83qHnNpwW2Zgby5xU9Gm8= +go.miloapis.com/service-catalog v0.13.1/go.mod h1:8kJJ+kw2GUzJk3ssgwtlsRuqrAHGSRxLE3K65sXaSfo= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= From d652a6ff1672da4e2f396b33c9ed341f39ff5a19 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 17:41:10 -0600 Subject: [PATCH 19/24] docs: detail Secure BMC production authorization plan --- docs/enhancements/secure-bmc-access.md | 4 + .../secure-bmc-authorization.md | 179 ++++++++++++++++++ 2 files changed, 183 insertions(+) create mode 100644 docs/implementation/secure-bmc-authorization.md diff --git a/docs/enhancements/secure-bmc-access.md b/docs/enhancements/secure-bmc-access.md index 9f02fb76..cb7c5871 100644 --- a/docs/enhancements/secure-bmc-access.md +++ b/docs/enhancements/secure-bmc-access.md @@ -326,6 +326,10 @@ unrestricted HTTP CONNECT service to the management network. ### Authentication and authorization +The [production authorization implementation plan](../implementation/secure-bmc-authorization.md) +expands the proposed IAM, caller-preservation, durable limits, and acceptance +contracts. These integrations are not yet production-verified. + Session admission uses Datum's existing human and service identity flows. IAM defines a management-session create permission separately from ordinary Machine read or update. Admission evaluates that permission against the diff --git a/docs/implementation/secure-bmc-authorization.md b/docs/implementation/secure-bmc-authorization.md new file mode 100644 index 00000000..73bbb4da --- /dev/null +++ b/docs/implementation/secure-bmc-authorization.md @@ -0,0 +1,179 @@ +# Secure BMC production authorization plan + +Status: proposed implementation contract, 2026-11-12. This plan expands the +production authorization work for Secure BMC Access. It does not enable production +admission or claim live Milo acceptance. + +Read with the [Secure BMC proposal](../enhancements/secure-bmc-access.md), +[prototype status](machine-management-prototype.md), [API architecture](../architecture.md), +and [pinned provisioning proposal](../proposals/fleet-management/bare-metal-provisioning.md). + +## Current implementation and gap + +`internal/controller/admission.go` copies the admission request username into a +service-owned annotation and makes the session spec immutable. Kubernetes RBAC +separates session creation from Machine reads. This is useful prototype evidence, +but a username is not a durable Milo authorization receipt, and the asynchronous +controller cannot reconstruct the original caller's authority from it. + +`internal/controller/session.go` counts cached bindings to enforce limits. That +check is not an atomic reservation across controller replicas. The existing Milo +contracts in `internal/milo/types.go` describe retained authority, admission fencing, +and protected quota custody for machine allocation; their production adapters are +not implemented. `internal/milo/quota.go` is specific to the machine quota resource +and must not be reused unchanged for sessions. + +The production admission path must retain the authenticated caller and exact +request, obtain a target-specific decision, reserve limits durably, and commit +against current allocation authority before any usable route is published. + +## Permission and audience contract + +Use the existing Bare Metal service, `metal.datumapis.com`, and its `metal` +entitlement. Do not create a second BMC catalog service. The following permission +names are proposed additions, subject to Milo integration validation: + +| Permission | Scope and purpose | +| --- | --- | +| `machinemanagementsessions.create` | Create a session request in the authenticated consumer project. | +| `machines.manageBMC` | Authorize the requested Provisioning capability against the exact target Machine in that project. | +| `machinemanagementsessions.get/list/watch` | Read safe session metadata and connection status in the project. | +| `machinemanagementsessions.delete` | Request teardown of a session in the project, including one created by another principal. | +| `machinemanagementsessions.updateStatus` | Service-only status publication. | + +All names above are prefixed with `metal.datumapis.com/` in IAM registration. +Creation requires both create and target capability permission. A generic create +grant alone cannot authorize arbitrary Machine references. If Milo cannot evaluate +the target-specific permission with the original caller, production stays disabled; +project-wide create must not silently substitute for that decision. + +Add an explicit opt-in BMC operator role containing the customer permissions above. +Do not inherit it into the existing viewer, consumer, or provider roles. Existing +Machine read, update, installation, and provider inventory grants confer no BMC +access. Retain project-wide session visibility for this initial role: the creator +is an audit identity, not an implicit owner-only ACL. A separate reader role may +be added later if needed. Customer writes to status, private admission receipts, +bindings, projections, quota custody, or finalizers remain forbidden. There is no +customer update/patch operation for changing an admitted session. + +Provider projects supply capabilities and enrollment authority; customers do not +need provider inventory permissions. Customer errors must not disclose whether a +foreign Machine or physical asset exists. Private allocation and Device details +stay out of public responses and IAM-facing customer objects. + +## Caller-preserving admission sequence + +1. Authenticate through Milo's trusted request path. Resolve the consumer project + identity and lifetime from that path, not a namespace name, annotation, or + request field. Preserve the principal's immutable identity and the authenticated + delegation context needed by the authorizer. Never persist bearer credentials. +2. Validate the immutable request and bind its digest to the target Machine UID, + consumer project lifetime, namespace UID, client public key, protocol, access + profile, and requested TTL. Reject ambiguous or unsupported profiles. Check + current Bare Metal entitlement and provider-published capability constraints. +3. Evaluate create and target capability permissions as that caller. Retain a + private receipt with decision ID, exact request digest, principal identity, + policy evidence/version and validity bound supported by the authorizer. A + controller service-account decision cannot replace a caller decision. +4. Persist a protected admission intent before quota or projection effects. Bind + it to the actual persisted session UID before creating any route. The request + admission boundary must provide a trustworthy handoff to the asynchronous + controller; an editable annotation is insufficient. Admission dry-run performs + validation only and creates no durable holds or external effects. +5. Resolve the exact current allocation through Fleet's authoritative lifecycle + custody. Retain Machine, allocation, capacity, Device and project identities + separately. Obtain the per-machine slot and project quota holds described below. +6. Commit admission under the shared lifecycle fence. Revalidate allocation + activity, project lifetime, entitlement, capability and receipt validity at the + commit boundary. A release or identity change wins over an uncommitted session. + Persist the admitted binding and its hold references before projection. +7. Publish only the existing narrow location projection. Caller credentials and + central policy receipts never enter Karmada or the gateway. Location execution + remains subject to current projected authority and the common effect fence. + +The trusted request handoff, target-decision API, and policy validity/revocation +signal are explicit Milo dependencies. Select their concrete adapters before +implementing admission; no invented endpoint or unsigned receipt is acceptable. +A webhook crash or API write failure may leave a prepared intent; recovery must +reconcile it against the persisted session UID and settle any known holds. A +missing response alone is not proof that a request or hold was never committed. + +## Durable limits and recovery + +Start with the prototype's policy defaults of one live session per Machine and +five per consumer project, configurable by service policy. Count pending admitted +sessions as well as connected ones. Session TTL is an independent maximum, not a +quota reservation mechanism. + +Use two durable controls: an allocation-scoped exclusive session slot through the +lifecycle custodian, and a Milo quota hold under a distinct proposed resource +`metal.datumapis.com/machinemanagementsessions`. Include consumer project lifetime, +Machine UID, allocation identity and session UID in the private custody record. +Retries for one session recover the same intent and holds. A second session must +not reuse them, even if its name or request body matches. + +The two stores need no assumed distributed transaction: prepare the intent, +reserve the machine slot, acquire project quota, then commit under the lifecycle +fence. Never publish a route before both holds and the commit are durable. A +partial failure remains pending or compensates through recorded settlement; it +cannot bypass one limit. A lost quota response is recovered by exact intent +identity, not by creating another quota claim. Protect hold lifetime from customer +deletions and quota claim edits. Cached list counts may be diagnostic only. + +Keep both holds until teardown is verified. Neither public session deletion, +terminal status, nor TTL expiry alone proves that a connector or admitted effect +has stopped. A proven never-projected admission may settle without contacting a +gateway; uncertain projection must take the teardown path. Persist teardown and +settlement receipts so restarts can resume without freeing a live slot. Quota +release uncertainty retains custody and reduces availability rather than allowing +oversubscription. Reconciliation must surface stuck holds for operators. + +## Revalidation and revocation + +A successful create decision is bounded authority, not permanent access. Refresh +requires current project lifetime, entitlement, allocation activity and a valid +caller-policy decision or renewal. Policy revocation, entitlement removal, +allocation release, explicit session deletion or expiry stops refresh and begins +teardown. A new positive decision cannot reactivate a terminal session. + +An unavailable authorizer or allocation reader prevents new admission and authority +extension. It is not evidence of a permanent denial: existing sessions remain +bounded by their last valid freshness deadline and enter recovery/unknown handling +where needed. Do not reset an expired deadline using cached success. Document and +measure the revocation bound as the remaining authority freshness interval plus +allowed clock uncertainty; do not promise instantaneous cancellation across a +partition. Already admitted effects require the lifecycle recovery contract and +must still block reuse until their outcome and teardown are known. + +## Implementation slices and evidence + +| Slice | Changes | Completion evidence | +| --- | --- | --- | +| IAM registration | Session ProtectedResource, Machine capability permission, explicit BMC role, narrow controller grants, separate quota resource under Bare Metal. | Render/packaging checks and role tests prove existing viewer/consumer roles gain no BMC capability. | +| Trusted admission | Milo caller adapter, protected request/decision custody, project-lifetime and target checks, immutable binding. | Original human and service-account decisions succeed; substituted controller identity, forged annotations and foreign targets fail. | +| Limits and fence | Protected project quota, allocation slot, idempotent recovery and lifecycle commit. | Concurrent admissions across two replicas never exceed either limit; crash injection at every partial commit recovers without a second hold or route. | +| Renewal and teardown | Policy renewal, bounded revocation, durable settlement and operator diagnostics. | IAM removal, project recreation, expiry, controller restart and API partition never extend stale authority or free an unverified slot. | +| Live Milo acceptance | Exercise the real project API and IAM/quota adapters with synthetic assets. | Sanitized evidence covers allow, deny, grant removal, boundary isolation and teardown; mock authorizer tests alone do not satisfy this gate. | + +Negative tests must include Machine read without session create; create without +Machine capability; wrong project with an identical Machine name; deleted and +recreated project or Machine; forged principal/receipt; changed key/profile/TTL; +replayed receipt for another session; stale entitlement; unavailable policy API; +concurrent release/admission; and customer deletion during uncertain quota or +projection writes. Dry-run must leave no custody or quota records. + +Audit records correlate principal, consumer project lifetime, request digest, +policy decision, session, allocation, quota intent, admission commit and teardown. +Keep physical identifiers in private records. Metrics expose admission denial +categories, authorization latency, held slots, unknown quota outcomes and teardown +age without principal or Machine identifiers as high-cardinality labels. + +## Dependencies and rollout + +The lifecycle integration work supplies authoritative allocation reads, the shared +commit/effect fence and verified teardown barrier. The Linux E2E work supplies +transport evidence; it does not prove production IAM. Implement registration and +contract tests first, then trusted admission and limits, and finally live Milo +acceptance. Keep production fail-closed until all adapters are available and the +acceptance gates pass. Enable an explicit pilot grant and quota only after that; +existing customers receive no new BMC permissions by default. From 8743d4017d5b14426bbf8c4e628892e933765a9b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 18:13:39 -0600 Subject: [PATCH 20/24] feat: integrate secure BMC sessions with lifecycle custody --- README.md | 12 +- cmd/fleet-controller/main.go | 3 +- ...om_projectedmachinemanagementsessions.yaml | 2 + .../machine-management-prototype.md | 34 +- docs/implementation/secure-bmc-lifecycle.md | 115 +++++ .../api/coordination/v1alpha1/teardown.go | 24 + .../coordination/v1alpha1/teardown_test.go | 31 ++ internal/api/coordination/v1alpha1/types.go | 9 +- internal/controller/lifecycle.go | 33 +- internal/controller/management_lifecycle.go | 323 +++++++++++++ .../controller/management_lifecycle_test.go | 454 ++++++++++++++++++ internal/controller/projection.go | 86 ++-- internal/controller/projection_test.go | 10 +- internal/controller/session.go | 126 +++-- internal/controller/session_test.go | 20 +- internal/gateway/gateway.go | 136 +++++- internal/gateway/gateway_test.go | 127 +++++ internal/redfish/handler.go | 21 +- internal/redfish/handler_test.go | 22 + 19 files changed, 1420 insertions(+), 168 deletions(-) create mode 100644 docs/implementation/secure-bmc-lifecycle.md create mode 100644 internal/api/coordination/v1alpha1/teardown.go create mode 100644 internal/api/coordination/v1alpha1/teardown_test.go create mode 100644 internal/controller/management_lifecycle.go create mode 100644 internal/controller/management_lifecycle_test.go diff --git a/README.md b/README.md index 9c91b166..87cea7fa 100644 --- a/README.md +++ b/README.md @@ -32,11 +32,13 @@ and immutable image selection remain in `infra`. See [`config/README.md`](config/README.md). There is still no real provider integration; the standalone smoke and synthetic staging modes remain test fixtures. -The repository also contains a deliberately narrow working prototype for -allocation-scoped customer Redfish access. It is not a complete Fleet allocator, -installer, or production BMC service. Its synthetic allocation records preserve -the proposed authority and identity boundaries while exercising the access path -end to end. +The repository also contains a deliberately narrow prototype for +allocation-scoped customer Redfish access. Its lifecycle integration consumes +service-owned Secret custody and serializes sessions against installation and +release, rather than trusting pre-bound allocation CRDs. Production access +authorization, trusted observation resolution, and executor fencing remain +unwired; the session controller defaults to unready and denies new sessions. +See the [implemented lifecycle contract](docs/implementation/secure-bmc-lifecycle.md). ## Scope diff --git a/cmd/fleet-controller/main.go b/cmd/fleet-controller/main.go index 90c46e9c..0c05e014 100644 --- a/cmd/fleet-controller/main.go +++ b/cmd/fleet-controller/main.go @@ -5,6 +5,7 @@ package main import ( "flag" "log/slog" + "net/http" "os" "time" @@ -53,7 +54,7 @@ func main() { must((&controller.SessionReconciler{PerClaimLimit: *perClaimLimit, PerProjectLimit: *perProjectLimit}).SetupWithManager(mgr)) must((&controller.ProjectionReconciler{FederationClient: federationClient, Freshness: *authorityFreshness}).SetupWithManager(mgr)) must(mgr.AddHealthzCheck("healthz", healthz.Ping)) - must(mgr.AddReadyzCheck("readyz", healthz.Ping)) + must(mgr.AddReadyzCheck("lifecycle-authority", func(*http.Request) error { return controller.ErrUnsupported })) slog.Info("starting Fleet session controllers") must(mgr.Start(ctrl.SetupSignalHandler())) } diff --git a/config/crd/bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml b/config/crd/bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml index e458c489..94ec057f 100644 --- a/config/crd/bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml +++ b/config/crd/bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml @@ -173,6 +173,8 @@ spec: endedAt: format: date-time type: string + teardownSpecDigest: + type: string type: object required: - spec diff --git a/docs/implementation/machine-management-prototype.md b/docs/implementation/machine-management-prototype.md index 434ed7e4..74587f17 100644 --- a/docs/implementation/machine-management-prototype.md +++ b/docs/implementation/machine-management-prototype.md @@ -17,13 +17,14 @@ The management-cluster controller authenticates through the Kubernetes delegated request identity retained by the mutating admission webhook. Kubernetes RBAC provides the prototype authorization decision: `machines` read and `machinemanagementsessions` create are separate grants. The controller resolves -the customer `Machine` through the immutable, terminal `MachineAllocation` to a +the customer `Machine` through service-owned claim and asset custody Secrets to a provider `MachineCapacity` and creates a protected `MachineManagementSessionBinding`. The latter pins the principal, consumer and provider project identities, the Machine, allocation, MachineCapacity and -immutable `deviceRef`, authoritative location and Karmada member, client key, +immutable `deviceRef`, an injected authoritative location and Karmada member, client key, deadlines, and correlation IDs. Local object UIDs are retained only in that -management-API record as recreation preconditions. None cross through Karmada +management-API record as recreation preconditions. `AllocationUID` now identifies +the private allocation binding, not a `MachineAllocation` CRD UID. None cross through Karmada or enter the public session. The controller writes a least-privileged session to the separate Karmada API and @@ -69,10 +70,10 @@ selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or 1. `datumctl fleet machine-management proxy MACHINE` generates a key and asks the management API for a session using only the customer Machine name. -2. Admission retains the authenticated principal. The controller resolves the - current Machine, exact active MachineAllocation, provider MachineCapacity and - immutable device relationship, enforces limits, and persists the protected - binding before projection. +2. Admission retains the authenticated principal. With an explicitly injected + access resolver, the controller resolves current Machine and provider identities + against protected lifecycle custody, enforces advisory limits, and acquires an + exclusive session hold in the asset Secret before publishing the binding. 3. The projector checks the authoritative allocation on every refresh, creates a Karmada hub copy and exact-member policy, and waits for status from that member. The gateway reads only its cell-local copy, establishes an outbound relay @@ -209,22 +210,19 @@ BMC logs, validator reports, acceleration selection, and PXE callbacks. Implemented-and-tested code must not be confused with a production-ready contract. Important gaps are: -- Machine, MachineAllocation, MachineCapacity, location registration, and local - enrollment data are synthetic and pre-bound. This access path does not consume the lifecycle library - or its protected Secret custody records. That library implements synthetic - allocation, installation and cleanup, but does not publish the synthetic - Active allocation annotations expected here. The BMC controller therefore - cannot be enabled against real allocations merely by installing its CRDs. - Production caller-preserving Milo admission, an authoritative allocation reader, - shared hardware-operation serialization, and a release barrier that waits for - session teardown remain integration work. +- The [lifecycle integration](secure-bmc-lifecycle.md) now reads protected Secret + custody, retains an exclusive hardware session hold, and blocks installation, + cleanup and reuse until verified teardown. It does not trust synthetic Active + allocation annotations. Its production access resolver remains absent, so + installing CRDs does not enable BMC access. Portable tests use explicit injected + authorization and observation fixtures; they are not production IAM evidence. - Delegated Kubernetes authentication/RBAC models the intended Compute/Milo pattern, but the production Datum API aggregation and session IAM registration are not wired. Sessions belong to the existing `metal` service; default Machine read access must not imply session-create permission. - Karmada projection and status aggregation are implemented and exercised, but - the prototype stores the member name directly in the protected synthetic - allocation. Production needs an authoritative location-to-member registration + member selection now requires the injected access resolver rather than allocation + annotations. Production needs an authoritative location-to-member registration controller, credential rotation, HA operations, failover policy, and environment packaging in `test-infra`/`infra`. - The relay is a small Fleet-specific opaque TCP rendezvous with inner TLS, not diff --git a/docs/implementation/secure-bmc-lifecycle.md b/docs/implementation/secure-bmc-lifecycle.md new file mode 100644 index 00000000..90b4cc05 --- /dev/null +++ b/docs/implementation/secure-bmc-lifecycle.md @@ -0,0 +1,115 @@ +# Secure BMC lifecycle custody + +Status: implemented library and portable tests; production wiring remains +unavailable. This supplements the [access-path prototype](machine-management-prototype.md) +and does not relax the [proposed product contract](../enhancements/secure-bmc-access.md) +or [pinned provisioning contract](../proposals/fleet-management/bare-metal-provisioning.md). + +## Authoritative inputs and writers + +`controller.LifecycleSessionAuthority` consumes the same `Coordinator` and private +Secret namespace used by standalone allocation, Milo lifecycle integration, and +synthetic staging. It resolves project-scoped claim custody to one bound, +committed asset. Public Machine status, `MachineAllocation` CRDs, and their +`machine-uid`, `member-cluster`, `location-name`, and `provider-project` annotations +are not allocation authority. No parallel allocation writer is introduced. + +The injected `ManagementAccessResolver` must authorize the retained principal for +explicit management access, verify current consumer/provider project lifetimes, +verify the live Machine and namespace lifetimes, and resolve trusted current +capacity/device and location/member observations. Its returned identities must +match retained custody. Refresh repeats resolution; failure terminally revokes +access rather than extending cached authority. Local standalone scope explicitly +uses the namespace lifetime; Milo scope uses canonical project authority and UID. +Missing integrations fail closed. + +Supply an authoritative private-record client with resource-version CAS, not a +public API cache interpreted as authority. Inject the same lifecycle authority +into `SessionReconciler.Lifecycle` and `ProjectionReconciler.Lifecycle`. The current +`fleet-controller` executable supplies neither a production resolver nor a +synthetic fallback; its readiness check reports unavailable. The manager and +staging handler remain allocation owners, and their shared Coordinator release +path includes this barrier. The projector checks custody on its existing bounded +refresh cadence, without allocation CRD watches or cluster-wide Secret access. + +## Exclusive effects and identities + +New private asset records use schema version 2, pinning Device name and location +alongside capacity UID. Customer Machine UID, capacity UID, physical asset key, +allocation BindingID/epoch, and installation operation identity remain separate. +In the protected binding, `AllocationName` is the asset Secret name and +`AllocationUID` is the allocation BindingID, not a CRD reference. Neither is sent +to the cell or public session. + +Admission CAS-writes the complete binding inputs into the asset before publishing +a binding or admitting projection. That same record owns the active installation +operation. One management session holds the asset effect slot, including Redfish +power/boot operations, until verified teardown. This is deliberately conservative +session-wide serialization, not an independent BMC lock. No general Machine power +controller is added; future power executors must use this same authority boundary. + +Installation requests mark the session revoking and return `ErrManagementActive` +without installation effects. Release CAS-transitions to `AssetReleasing` and +marks revocation before network/provider cleanup, quota settlement or reuse. New +sessions fail admission. CAS selects one winner among management admission, +installation activation and release; no timeout makes uncertain custody available. + +The gateway cancels the stream, drains accepted requests, rejects later requests, +and waits for its runner to exit. The durable journal must show settled successful +effects before cleanup acknowledgment. Pending, unknown, legacy failed effects, +missing session custody or a missing operation directory cannot prove cleanup. +Adapter errors without definitive evidence are Unknown. A different mutation +cannot bypass an unsettled device operation, and queued mutations recheck +authority after acquiring the device lock. + +## Recovery and teardown + +- A crash between asset CAS and binding creation recovers the exact binding, + deadlines, client key and correlation IDs, including during release. Recovery + does not create authority or renew expired deadlines. +- Projection intent is retained before federation Create. A revoked hold with no + admitted projection can settle using that positive private proof. After intent + is retained, an absent projection is unknown, not teardown proof. +- The gateway persists a session marker before route registration and a terminal + revocation marker before cleanup acknowledgment. Replayed Active projections + cannot restart durably revoked sessions. Control markers use the separate + `sessions` journal and are not exposed as Redfish tasks. +- The projector accepts cleanup only with a digest of the exact revoked projection + name/spec, not by comparing unrelated hub and cell generation counters, saving + confirmation on the binding before completing the hold and deleting federation + artifacts. Completion is replayable. Old confirmation cannot modify a newer + allocation/session hold. Public deletion retains its finalizer on timeout. +- Version 1 assets remain readable for lifecycle recovery/release but cannot admit + BMC sessions. No upgrade from mutable annotations is attempted. Older writers + reject version 2 rather than silently dropping holds. Drain old sessions and + upgrade all effect writers before enabling an injected source. Downgrade is not + a supported active-session migration. + +## Validation and production dependencies + +Portable tests cover identity binding without allocation CRDs, missing/denied +authorization, project/namespace/Machine/capacity recreation, device changes, +installation/session and release/session races, competing sessions, exact-input +recovery, projection intent, schema compatibility, stale/unknown teardown, +next-epoch reuse, obsolete completion replay, request draining, journal loss, +and unresolved mutation exclusion. + +```sh +go test ./internal/controller ./internal/gateway ./internal/redfish ./internal/standalone ./internal/manager ./internal/milo ./internal/staging +go test -race ./internal/controller ./internal/gateway ./internal/redfish +bash hack/validate-doc-links.sh +git diff --check +``` + +Production caller-preserving authorization, trusted enrollment/observation and +location registration, deployment wiring, and provider-enforced multi-executor +fencing remain absent. Private CAS and gateway tests establish a single qualified +executor contract only, not cross-replica fencing or hardware completion from an +arbitrary Redfish response. Stable protected journal storage is required. Unknown +operations still need qualified recovery evidence; this change does not auto-clear +tasks or redesign quota, nonce persistence, or general idempotency. + +Pre-bound-CRD E2E fixtures are not an integration source. The separate E2E owner +must explicitly wire a synthetic resolver backed by real lifecycle custody for +test use without enabling a production fallback. No Kind/Docker environment or +`hack/e2e` files were changed or run for this implementation. diff --git a/internal/api/coordination/v1alpha1/teardown.go b/internal/api/coordination/v1alpha1/teardown.go new file mode 100644 index 00000000..7aaf6098 --- /dev/null +++ b/internal/api/coordination/v1alpha1/teardown.go @@ -0,0 +1,24 @@ +package v1alpha1 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +func TeardownDigest(session *ProjectedMachineManagementSession) string { + if session.Spec.DesiredState != sessionv1.ProjectionRevoked { + return "" + } + data, err := json.Marshal(struct { + Name string `json:"name"` + Spec ProjectedMachineManagementSessionSpec `json:"spec"` + }{Name: session.Name, Spec: session.Spec}) + if err != nil { + return "" + } + digest := sha256.Sum256(data) + return hex.EncodeToString(digest[:]) +} diff --git a/internal/api/coordination/v1alpha1/teardown_test.go b/internal/api/coordination/v1alpha1/teardown_test.go new file mode 100644 index 00000000..855e7f11 --- /dev/null +++ b/internal/api/coordination/v1alpha1/teardown_test.go @@ -0,0 +1,31 @@ +package v1alpha1 + +import ( + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +func TestTeardownDigestBindsRevocationNotClusterMetadata(t *testing.T) { + session := &ProjectedMachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: "opaque-session", Namespace: "hub", UID: "hub-uid", Generation: 8}, Spec: ProjectedMachineManagementSessionSpec{DesiredState: sessionv1.ProjectionActive, MachineCapacityRef: sessionv1.LocalReference{Name: "capacity"}}} + if TeardownDigest(session) != "" { + t.Fatal("active projection has teardown proof") + } + session.Spec.DesiredState = sessionv1.ProjectionRevoked + digest := TeardownDigest(session) + session.Namespace, session.UID, session.Generation = "cell", "cell-uid", 3 + if digest == "" || TeardownDigest(session) != digest { + t.Fatal("API-local metadata changed proof identity") + } + session.Spec.MachineCapacityRef.Name = "other-capacity" + if TeardownDigest(session) == digest { + t.Fatal("proof survived a target change") + } + session.Spec.MachineCapacityRef.Name = "capacity" + session.Name = "another-session" + if TeardownDigest(session) == digest { + t.Fatal("proof survived session replacement") + } +} diff --git a/internal/api/coordination/v1alpha1/types.go b/internal/api/coordination/v1alpha1/types.go index 783a3457..fd400a78 100644 --- a/internal/api/coordination/v1alpha1/types.go +++ b/internal/api/coordination/v1alpha1/types.go @@ -38,10 +38,11 @@ type ProjectedMachineManagementSessionSpec struct { } type ProjectedMachineManagementSessionStatus struct { - Connection *sessionv1.SessionConnection `json:"connection,omitempty"` - ConnectedAt *metav1.Time `json:"connectedAt,omitempty"` - EndedAt *metav1.Time `json:"endedAt,omitempty"` - Conditions []metav1.Condition `json:"conditions,omitempty"` + TeardownSpecDigest string `json:"teardownSpecDigest,omitempty"` + Connection *sessionv1.SessionConnection `json:"connection,omitempty"` + ConnectedAt *metav1.Time `json:"connectedAt,omitempty"` + EndedAt *metav1.Time `json:"endedAt,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` } // +kubebuilder:object:root=true diff --git a/internal/controller/lifecycle.go b/internal/controller/lifecycle.go index d1f2a0db..00df5d47 100644 --- a/internal/controller/lifecycle.go +++ b/internal/controller/lifecycle.go @@ -29,8 +29,9 @@ import ( ) const ( - MachineFinalizer = "fleet.datumapis.com/machine-protection" - recordSchemaVersion = 1 + MachineFinalizer = "fleet.datumapis.com/machine-protection" + recordSchemaVersion = 1 + assetRecordSchemaVersion = 2 // Installation records gained retained public routing identities in v2. // v1 is accepted only by the explicit request-bound upgrader below. installationRecordSchemaVersion = 2 @@ -116,6 +117,8 @@ type AssetRecord struct { MachineNamespace string `json:"machineNamespace"` MachineName string `json:"machineName"` MachineUID types.UID `json:"machineUID"` + DeviceName string `json:"deviceName,omitempty"` + LocationName string `json:"locationName,omitempty"` ClaimNamespace string `json:"claimNamespace"` ClaimName string `json:"claimName"` ClaimUID types.UID `json:"claimUID"` @@ -133,6 +136,7 @@ type AssetRecord struct { FenceToken string `json:"fenceToken"` CurrentInstallationName string `json:"currentInstallationName"` ActiveOperationID string `json:"activeOperationID,omitempty"` + Management *ManagementSessionRecord `json:"management,omitempty"` AcceptedRequirements fleetv1.MachineProfileSpec `json:"acceptedRequirements"` Hardware fleetv1.Hardware `json:"hardware"` Network *NetworkRecord `json:"network,omitempty"` @@ -552,6 +556,9 @@ func (c *Coordinator) recordCandidateEligible(record *AssetRecord, request Alloc } func validateAssetForRequest(record *AssetRecord, request AllocationRequest) error { + if record.SchemaVersion == assetRecordSchemaVersion && record.LocationName != request.Claim.Spec.LocationRef.Name { + return fmt.Errorf("%w: retained allocation location differs from retry", ErrRecordInvalid) + } // Specs contain slices, so compare their canonical JSON rather than // allowing a recovered Preparing record to drift across retries. got, _ := json.Marshal(record.AcceptedRequirements) @@ -792,8 +799,9 @@ func (c *Coordinator) proposeAsset(ctx context.Context, request AllocationReques } func newAssetRecord(request AllocationRequest, machine *fleetv1.MachineCapacity, assetID string, epoch int64, bindingID, fenceToken string) *AssetRecord { - record := &AssetRecord{SchemaVersion: recordSchemaVersion, State: AssetPreparing, AssetID: assetID, + record := &AssetRecord{SchemaVersion: assetRecordSchemaVersion, State: AssetPreparing, AssetID: assetID, MachineNamespace: machine.Namespace, MachineName: machine.Name, MachineUID: machine.UID, + DeviceName: machine.Spec.DeviceRef.Name, LocationName: request.Claim.Spec.LocationRef.Name, ClaimNamespace: request.Claim.Namespace, ClaimName: request.Claim.Name, ClaimUID: request.Claim.UID, ClaimScope: allocationClaimScope(request), ClassUID: request.Class.UID, ProfileUID: request.Profile.UID, LocalClassUID: localClassUID(request), LocalProfileUID: localProfileUID(request), ConsumerProject: request.ConsumerProject, ProviderProject: request.ProviderProject, Authority: request.Authority, ExternalHold: request.ExternalHold, @@ -1001,6 +1009,12 @@ func (c *Coordinator) release(ctx context.Context, scope ClaimScope, claimUID ty if custody.State != CustodyBound || custody.AssetID != record.AssetID { return ReleaseResult{}, fmt.Errorf("%w: custody and asset authority disagree", ErrRecordInvalid) } + if managementHeld(record) { + if err := c.revokeManagement(ctx, record.AssetID, claimUID, true); err != nil { + return ReleaseResult{}, err + } + return ReleaseResult{State: AssetReleasing}, ErrManagementActive + } if record.ActiveOperationID != "" { if err := c.settleActiveOperation(ctx, record); err != nil { return ReleaseResult{State: record.State}, err @@ -1445,6 +1459,12 @@ func (c *Coordinator) activateOperation(ctx context.Context, assetID string, cla if record.ClaimUID != claimUID || record.State != AssetCommitted || record.CurrentInstallationName != predecessor { return ErrPredecessorConflict } + if managementHeld(record) { + if err := c.revokeManagement(ctx, assetID, claimUID, false); err != nil { + return err + } + return ErrManagementActive + } if record.ActiveOperationID != "" && record.ActiveOperationID != operationID { return ErrOperationActive } @@ -1539,7 +1559,7 @@ func (c *Coordinator) setAssetState(ctx context.Context, assetID string, claimUI if err != nil { return nil, err } - if record.ClaimUID != claimUID || record.State != from || record.ActiveOperationID != "" { + if record.ClaimUID != claimUID || record.State != from || record.ActiveOperationID != "" || managementHeld(record) { return nil, fmt.Errorf("%w: asset transition %s to %s rejected", ErrRecordInvalid, record.State, to) } record.State = to @@ -1988,7 +2008,7 @@ func decodeLegacyOperationSecret(secret *corev1.Secret) (*InstallationRecord, er } func validateAssetRecord(r *AssetRecord) error { - if r.SchemaVersion != recordSchemaVersion || r.AssetID == "" || r.MachineNamespace == "" || r.MachineName == "" || r.MachineUID == "" || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || !r.ClaimScope.Valid() || r.ClassUID == "" || r.ProfileUID == "" || r.LocalClassUID == "" || r.LocalProfileUID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" || r.CurrentInstallationName == "" { + if (r.SchemaVersion != recordSchemaVersion && r.SchemaVersion != assetRecordSchemaVersion) || r.SchemaVersion == recordSchemaVersion && r.Management != nil || r.AssetID == "" || r.MachineNamespace == "" || r.MachineName == "" || r.MachineUID == "" || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || !r.ClaimScope.Valid() || r.ClassUID == "" || r.ProfileUID == "" || r.LocalClassUID == "" || r.LocalProfileUID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" || r.CurrentInstallationName == "" { return ErrRecordInvalid } projectAuthority := r.ConsumerProject.Valid() || r.ProviderProject.Valid() || r.Authority.Valid() || r.ExternalHold.Valid() @@ -1998,6 +2018,9 @@ func validateAssetRecord(r *AssetRecord) error { if r.ConsumerProject.Valid() && r.ClaimScope != ProjectClaimScope(r.ConsumerProject) { return ErrRecordInvalid } + if r.Management != nil && validateManagementRecord(r) != nil { + return ErrRecordInvalid + } switch r.State { case AssetPreparing, AssetCommitted, AssetReleasing, AssetCleanupVerified, AssetReleased: default: diff --git a/internal/controller/management_lifecycle.go b/internal/controller/management_lifecycle.go new file mode 100644 index 00000000..6490a729 --- /dev/null +++ b/internal/controller/management_lifecycle.go @@ -0,0 +1,323 @@ +package controller + +import ( + "context" + "errors" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +var ErrManagementActive = errors.New("management session teardown is not verified") + +type ManagementSessionRecord struct { + Binding sessionv1.MachineManagementSessionBindingSpec `json:"binding"` + Revoking bool `json:"revoking"` + Completed bool `json:"completed"` + ProjectionAdmitted bool `json:"projectionAdmitted"` +} + +type ManagementAccess struct { + Scope ClaimScope + ConsumerProject ProjectIdentity + ProviderProject ProjectIdentity + NamespaceUID types.UID + MachineUID types.UID + CapacityNamespace string + CapacityName string + CapacityUID types.UID + DeviceName string + MemberCluster string + LocationName string +} + +type ManagementAccessResolver interface { + ResolveManagementAccess(context.Context, sessionv1.MachineManagementSessionBindingSpec) (ManagementAccess, error) +} + +type SessionLifecycle interface { + Recover(context.Context, *sessionv1.MachineManagementSession) (*sessionv1.MachineManagementSessionBindingSpec, error) + Prepare(context.Context, sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) + Acquire(context.Context, sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) + Active(context.Context, *sessionv1.MachineManagementSessionBinding) bool + Complete(context.Context, *sessionv1.MachineManagementSessionBinding) error + BeginProjection(context.Context, *sessionv1.MachineManagementSessionBinding) error + CancelUnprojected(context.Context, *sessionv1.MachineManagementSessionBinding) (bool, error) +} + +func (a *LifecycleSessionAuthority) BeginProjection(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) error { + if !a.Active(ctx, binding) || binding.Annotations[RevokedAtAnnotation] != "" { + return ErrManagementActive + } + return retry.RetryOnConflict(retry.DefaultRetry, func() error { + secret, asset, err := a.readBindingAsset(ctx, binding) + if err != nil { + return err + } + if !managementHeld(asset) || asset.State != AssetCommitted || asset.Management.Revoking || !equality.Semantic.DeepEqual(asset.Management.Binding, binding.Spec) { + return ErrManagementActive + } + if asset.Management.ProjectionAdmitted { + return nil + } + asset.Management.ProjectionAdmitted = true + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + return a.Coordinator.client.Update(ctx, secret) + }) +} + +func (a *LifecycleSessionAuthority) CancelUnprojected(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) (bool, error) { + if a == nil || a.Coordinator == nil || binding.Annotations[RevokedAtAnnotation] == "" { + return false, ErrManagementActive + } + completed := false + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + secret, asset, err := a.readBindingAsset(ctx, binding) + if err != nil { + return err + } + if asset.Management == nil || !equality.Semantic.DeepEqual(asset.Management.Binding, binding.Spec) { + return ErrRecordInvalid + } + if asset.Management.ProjectionAdmitted { + return nil + } + asset.Management.Revoking = true + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + if err := a.Coordinator.client.Update(ctx, secret); err != nil { + return err + } + completed = true + return nil + }) + return completed, err +} + +func (a *LifecycleSessionAuthority) Recover(ctx context.Context, session *sessionv1.MachineManagementSession) (*sessionv1.MachineManagementSessionBindingSpec, error) { + if a == nil || a.Coordinator == nil { + return nil, ErrUnsupported + } + var records corev1.SecretList + if err := a.Coordinator.client.List(ctx, &records, client.InNamespace(a.Coordinator.namespace), client.MatchingLabels{recordTypeLabel: "asset"}); err != nil { + return nil, err + } + var retained *sessionv1.MachineManagementSessionBindingSpec + for index := range records.Items { + asset, err := decodeAssetSecret(&records.Items[index]) + if err != nil { + return nil, err + } + if asset.Management == nil || asset.Management.Binding.SessionUID != session.UID { + continue + } + binding := asset.Management.Binding + if retained != nil || binding.SessionNamespace != session.Namespace || binding.SessionName != session.Name || binding.MachineName != session.Spec.MachineRef.Name || binding.RequestingPrincipal != session.Annotations[PrincipalAnnotation] || binding.ClientPublicKey != session.Spec.ClientPublicKey || binding.Protocol != session.Spec.Protocol || binding.AccessProfile != session.Spec.AccessProfile { + return nil, ErrRecordInvalid + } + retained = &binding + } + return retained, nil +} + +func (a *LifecycleSessionAuthority) Prepare(ctx context.Context, binding sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) { + asset, access, err := a.resolve(ctx, binding) + if err != nil { + return binding, err + } + binding.ConsumerProject, binding.ProviderProject = access.ConsumerProject.RouteName, access.ProviderProject.RouteName + binding.AllocationName, binding.AllocationUID = assetRecordName(asset.AssetID), types.UID(asset.BindingID) + binding.MachineCapacityNamespace, binding.MachineCapacityName, binding.MachineCapacityUID = asset.MachineNamespace, asset.MachineName, asset.MachineUID + binding.DeviceName, binding.LocationName, binding.MemberCluster = asset.DeviceName, asset.LocationName, access.MemberCluster + return binding, nil +} + +type LifecycleSessionAuthority struct { + Coordinator *Coordinator + Resolver ManagementAccessResolver +} + +func (a *LifecycleSessionAuthority) resolve(ctx context.Context, binding sessionv1.MachineManagementSessionBindingSpec) (*AssetRecord, ManagementAccess, error) { + if a == nil || a.Coordinator == nil || a.Resolver == nil || binding.RequestingPrincipal == "" || binding.MachineUID == "" { + return nil, ManagementAccess{}, ErrUnsupported + } + access, err := a.Resolver.ResolveManagementAccess(ctx, binding) + if err != nil { + return nil, access, err + } + if !access.Scope.Valid() || !access.ConsumerProject.Valid() || !access.ProviderProject.Valid() || access.MemberCluster == "" || access.LocationName == "" || access.Scope.ProjectUID != access.ConsumerProject.UID || access.Scope.AuthorityID != access.ConsumerProject.AuthorityID { + return nil, access, ErrRecordInvalid + } + custody, _, err := a.Coordinator.getCustodyScoped(ctx, access.Scope, binding.MachineUID) + if err != nil { + return nil, access, err + } + if custody.State != CustodyBound || custody.ClaimName != binding.MachineName || custody.ClaimNamespace != binding.MachineNamespace || custody.NamespaceUID != access.NamespaceUID || access.MachineUID != binding.MachineUID { + return nil, access, ErrRecordInvalid + } + asset, _, err := a.Coordinator.getAsset(ctx, custody.AssetID) + if err != nil { + return nil, access, err + } + if asset.SchemaVersion != assetRecordSchemaVersion { + return nil, access, ErrRecordInvalid + } + if custody.ConsumerProject != asset.ConsumerProject || custody.ProviderProject != asset.ProviderProject || custody.Authority != asset.Authority || custody.ExternalHold != asset.ExternalHold { + return nil, access, ErrRecordInvalid + } + if asset.ClaimScope != access.Scope || asset.ClaimUID != binding.MachineUID || asset.ClaimName != binding.MachineName || asset.ClaimNamespace != binding.MachineNamespace || asset.State != AssetCommitted || asset.DeviceName == "" || asset.DeviceName != access.DeviceName || asset.MachineNamespace != access.CapacityNamespace || asset.MachineName != access.CapacityName || asset.MachineUID != access.CapacityUID || asset.LocationName != access.LocationName || asset.ActiveOperationID != "" { + return nil, access, ErrRecordInvalid + } + if asset.ConsumerProject.Valid() && (asset.ConsumerProject != access.ConsumerProject || asset.ProviderProject != access.ProviderProject) { + return nil, access, ErrRecordInvalid + } + return asset, access, nil +} + +func (a *LifecycleSessionAuthority) Acquire(ctx context.Context, proposed sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) { + var retained sessionv1.MachineManagementSessionBindingSpec + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + asset, access, err := a.resolve(ctx, proposed) + if err != nil { + return err + } + current, secret, err := a.Coordinator.getAsset(ctx, asset.AssetID) + if err != nil { + return err + } + if !equality.Semantic.DeepEqual(current, asset) { + return ErrOperationActive + } + binding := proposed + binding.ConsumerProject, binding.ProviderProject = access.ConsumerProject.RouteName, access.ProviderProject.RouteName + binding.AllocationName, binding.AllocationUID = secret.Name, types.UID(asset.BindingID) + binding.MachineCapacityNamespace, binding.MachineCapacityName, binding.MachineCapacityUID = asset.MachineNamespace, asset.MachineName, asset.MachineUID + binding.DeviceName, binding.LocationName, binding.MemberCluster = asset.DeviceName, asset.LocationName, access.MemberCluster + if asset.Management != nil && asset.Management.Binding.SessionUID == binding.SessionUID { + previous := asset.Management.Binding + binding.ConnectBefore, binding.ExpiresAt = previous.ConnectBefore, previous.ExpiresAt + binding.SessionCorrelationID, binding.OperationCorrelationID = previous.SessionCorrelationID, previous.OperationCorrelationID + if !equality.Semantic.DeepEqual(previous, binding) || asset.Management.Completed { + return ErrRecordInvalid + } + retained = previous + return nil + } + if managementHeld(asset) { + return ErrManagementActive + } + asset.Management = &ManagementSessionRecord{Binding: binding} + if err := validateManagementRecord(asset); err != nil { + return err + } + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + if err := a.Coordinator.client.Update(ctx, secret); err != nil { + return err + } + retained = binding + return nil + }) + return retained, err +} + +func (a *LifecycleSessionAuthority) Active(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) bool { + asset, access, err := a.resolve(ctx, binding.Spec) + return err == nil && managementHeld(asset) && !asset.Management.Revoking && equality.Semantic.DeepEqual(asset.Management.Binding, binding.Spec) && access.MemberCluster == binding.Spec.MemberCluster && access.ConsumerProject.RouteName == binding.Spec.ConsumerProject && access.ProviderProject.RouteName == binding.Spec.ProviderProject +} + +func (a *LifecycleSessionAuthority) Complete(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) error { + if a == nil || a.Coordinator == nil || binding.Annotations[RevokedAtAnnotation] == "" { + return ErrManagementActive + } + condition := apimeta.FindStatusCondition(binding.Status.Conditions, "CleanupConfirmed") + if condition == nil || condition.Status != metav1.ConditionTrue || condition.ObservedGeneration != binding.Generation { + return ErrManagementActive + } + return retry.RetryOnConflict(retry.DefaultRetry, func() error { + return a.complete(ctx, binding) + }) +} + +func (a *LifecycleSessionAuthority) readBindingAsset(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) (*corev1.Secret, *AssetRecord, error) { + var secret corev1.Secret + if err := a.Coordinator.client.Get(ctx, client.ObjectKey{Namespace: a.Coordinator.namespace, Name: binding.Spec.AllocationName}, &secret); err != nil { + return nil, nil, err + } + asset, err := decodeAssetSecret(&secret) + if err != nil { + return nil, nil, err + } + if secret.Name != assetRecordName(asset.AssetID) { + return nil, nil, ErrRecordInvalid + } + return &secret, asset, nil +} + +func (a *LifecycleSessionAuthority) complete(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) error { + secret, asset, err := a.readBindingAsset(ctx, binding) + if err != nil { + return err + } + if string(binding.Spec.AllocationUID) != asset.BindingID || asset.Management != nil && asset.Management.Binding.SessionUID != binding.Spec.SessionUID { + return nil + } + if asset.Management == nil || !equality.Semantic.DeepEqual(asset.Management.Binding, binding.Spec) { + return ErrRecordInvalid + } + if asset.Management.Completed { + return nil + } + asset.Management.Revoking, asset.Management.Completed = true, true + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + return a.Coordinator.client.Update(ctx, secret) +} + +func managementHeld(asset *AssetRecord) bool { + return asset.Management != nil && !asset.Management.Completed +} + +func validateManagementRecord(asset *AssetRecord) error { + record := asset.Management + binding := record.Binding + if binding.SessionUID == "" || binding.SessionName == "" || binding.SessionNamespace != asset.ClaimNamespace || binding.RequestingPrincipal == "" || binding.ClientPublicKey == "" || binding.Protocol != "Redfish" || binding.AccessProfile != "Provisioning" || binding.ConsumerProject == "" || binding.ProviderProject == "" || binding.MemberCluster == "" || binding.LocationName == "" || binding.LocationName != asset.LocationName || binding.DeviceName == "" || binding.DeviceName != asset.DeviceName || binding.AllocationName != assetRecordName(asset.AssetID) || string(binding.AllocationUID) != asset.BindingID || binding.MachineUID != asset.ClaimUID || binding.MachineName != asset.ClaimName || binding.MachineNamespace != asset.ClaimNamespace || binding.MachineCapacityUID != asset.MachineUID || binding.MachineCapacityName != asset.MachineName || binding.MachineCapacityNamespace != asset.MachineNamespace || binding.ConnectBefore.IsZero() || binding.ExpiresAt.IsZero() || binding.ConnectBefore.After(binding.ExpiresAt.Time) || binding.SessionCorrelationID == "" || binding.OperationCorrelationID == "" { + return ErrRecordInvalid + } + if record.Completed && !record.Revoking || managementHeld(asset) && (asset.ActiveOperationID != "" || asset.State != AssetCommitted && asset.State != AssetReleasing) || asset.State == AssetReleasing && !record.Revoking { + return ErrRecordInvalid + } + return nil +} + +func (c *Coordinator) revokeManagement(ctx context.Context, assetID string, claimUID types.UID, releasing bool) error { + return retry.RetryOnConflict(retry.DefaultRetry, func() error { + asset, secret, err := c.getAsset(ctx, assetID) + if err != nil { + return err + } + if asset.ClaimUID != claimUID || !managementHeld(asset) || asset.ActiveOperationID != "" || asset.State != AssetCommitted && asset.State != AssetReleasing { + return ErrRecordInvalid + } + asset.Management.Revoking = true + if releasing { + asset.State = AssetReleasing + } + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + return c.client.Update(ctx, secret) + }) +} diff --git a/internal/controller/management_lifecycle_test.go b/internal/controller/management_lifecycle_test.go new file mode 100644 index 00000000..ec650282 --- /dev/null +++ b/internal/controller/management_lifecycle_test.go @@ -0,0 +1,454 @@ +package controller + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "k8s.io/apimachinery/pkg/api/equality" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" +) + +type managementResolver struct { + access ManagementAccess + err error +} + +func (r *managementResolver) ResolveManagementAccess(_ context.Context, _ sessionv1.MachineManagementSessionBindingSpec) (ManagementAccess, error) { + return r.access, r.err +} + +func managementFixture(t *testing.T) (*fixture, AllocationRequest, *AssetRecord, *LifecycleSessionAuthority, sessionv1.MachineManagementSessionBindingSpec) { + t.Helper() + ctx := context.Background() + f := newFixture(t) + request := f.request("customer") + request.Claim.Spec.LocationRef.Name = "location" + if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { + t.Fatal(err) + } + asset, err := f.coordinator.Allocate(ctx, request) + if err != nil { + t.Fatal(err) + } + authority := &LifecycleSessionAuthority{Coordinator: f.coordinator, Resolver: &managementResolver{access: ManagementAccess{Scope: LocalClaimScope(request.NamespaceUID), NamespaceUID: request.NamespaceUID, MachineUID: request.Claim.UID, CapacityNamespace: asset.MachineNamespace, CapacityName: asset.MachineName, CapacityUID: asset.MachineUID, DeviceName: asset.DeviceName, ConsumerProject: ProjectIdentity{AuthorityID: "local", RouteName: "consumer", UID: request.NamespaceUID}, ProviderProject: ProjectIdentity{AuthorityID: "local", RouteName: "provider", UID: "provider-uid"}, MemberCluster: "cell", LocationName: "location"}}} + binding := sessionv1.MachineManagementSessionBindingSpec{SessionNamespace: request.Claim.Namespace, SessionName: "access", SessionUID: "session", RequestingPrincipal: "principal", MachineNamespace: request.Claim.Namespace, MachineName: request.Claim.Name, MachineUID: request.Claim.UID, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", ConnectBefore: metav1.NewTime(f.now.Add(time.Minute)), ExpiresAt: metav1.NewTime(f.now.Add(time.Hour)), SessionCorrelationID: "session-correlation", OperationCorrelationID: "operation-correlation"} + return f, request, asset, authority, binding +} + +func confirmedBinding(spec sessionv1.MachineManagementSessionBindingSpec) *sessionv1.MachineManagementSessionBinding { + return &sessionv1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Name: bindingName(spec.SessionUID), Namespace: SystemNamespace, Generation: 2, Annotations: map[string]string{RevokedAtAnnotation: "revoked"}}, Spec: spec, Status: sessionv1.MachineManagementSessionBindingStatus{Conditions: []metav1.Condition{{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, ObservedGeneration: 2, Reason: "Verified"}}}} +} + +func TestManagementCustodyBlocksReleaseAndReuse(t *testing.T) { + ctx := context.Background() + f, request, asset, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + if retained.AllocationName != assetRecordName(asset.AssetID) || retained.AllocationUID != types.UID(asset.BindingID) || retained.MachineUID == retained.MachineCapacityUID || retained.DeviceName != asset.DeviceName { + t.Fatalf("identities collapsed: %+v", retained) + } + if !authority.Active(ctx, &sessionv1.MachineManagementSessionBinding{Spec: retained}) { + t.Fatal("retained session inactive") + } + result, err := f.coordinator.Release(ctx, request.Claim.UID) + if !errors.Is(err, ErrManagementActive) || result.SafeToRemoveFinalizer || len(f.executor.requests) != 0 { + t.Fatalf("release crossed live session: %+v %v", result, err) + } + if authority.Active(ctx, &sessionv1.MachineManagementSessionBinding{Spec: retained}) { + t.Fatal("release still refreshes session authority") + } + competitor := f.request("other") + if err := f.coordinator.EnsureClaimCustody(ctx, competitor.Claim, competitor.NamespaceUID, competitor.Admission); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Allocate(ctx, competitor); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("reuse before teardown: %v", err) + } + confirmation := confirmedBinding(retained) + confirmation.Status.Conditions[0].Status = metav1.ConditionUnknown + if err := authority.Complete(ctx, confirmation); !errors.Is(err, ErrManagementActive) { + t.Fatalf("unknown teardown cleared hold: %v", err) + } + confirmation.Status.Conditions[0].Status = metav1.ConditionTrue + confirmation.Status.Conditions[0].ObservedGeneration-- + if err := authority.Complete(ctx, confirmation); !errors.Is(err, ErrManagementActive) { + t.Fatalf("stale teardown cleared hold: %v", err) + } + confirmation.Status.Conditions[0].ObservedGeneration++ + authority = &LifecycleSessionAuthority{Coordinator: f.coordinator} + if err := authority.Complete(ctx, confirmation); err != nil { + t.Fatal(err) + } + if err := authority.Complete(ctx, confirmation); err != nil { + t.Fatalf("completion not replayable: %v", err) + } + result, err = f.coordinator.Release(ctx, request.Claim.UID) + if err != nil || !result.SafeToRemoveFinalizer || len(f.executor.requests) != 1 { + t.Fatalf("verified teardown did not unblock cleanup: %+v %v", result, err) + } + next, err := f.coordinator.Allocate(ctx, competitor) + if err != nil || next.Epoch <= asset.Epoch || next.BindingID == asset.BindingID || next.Management != nil { + t.Fatalf("reuse inherited authority: %+v %v", next, err) + } +} + +func TestManagementInstallationAndSessionAdmissionSerialize(t *testing.T) { + ctx := context.Background() + for iteration := 0; iteration < 20; iteration++ { + f, request, asset, authority, proposed := managementFixture(t) + var acquireErr, installErr error + var wait sync.WaitGroup + wait.Add(2) + go func() { defer wait.Done(); _, acquireErr = authority.Acquire(ctx, proposed) }() + go func() { + defer wait.Done() + installErr = f.coordinator.activateOperation(ctx, asset.AssetID, request.Claim.UID, "None", "installation") + }() + wait.Wait() + if acquireErr == nil && installErr == nil { + t.Fatal("session and installation both acquired hardware authority") + } + stored, _, err := f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil || managementHeld(stored) && stored.ActiveOperationID != "" { + t.Fatalf("conflicting durable authority: %+v %v", stored, err) + } + } +} + +func TestManagementInstallWaitsForTeardown(t *testing.T) { + ctx := context.Background() + f, request, _, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "installation-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "registry/image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} + installRequest := InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()} + if _, err := f.coordinator.Install(ctx, installRequest); !errors.Is(err, ErrManagementActive) || len(f.executor.requests) != 0 { + t.Fatalf("install bypassed session: %v", err) + } + if authority.Active(ctx, &sessionv1.MachineManagementSessionBinding{Spec: retained}) { + t.Fatal("install did not revoke management refresh") + } + if err := authority.Complete(ctx, confirmedBinding(retained)); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Install(ctx, installRequest); err != nil || len(f.executor.requests) != 1 { + t.Fatalf("install did not resume: %v", err) + } +} + +func TestManagementParallelSessionsAndReleaseCAS(t *testing.T) { + ctx := context.Background() + for iteration := 0; iteration < 20; iteration++ { + f, request, asset, authority, proposed := managementFixture(t) + other := proposed + other.SessionUID, other.SessionName = "other", "other" + var firstErr, secondErr error + var wait sync.WaitGroup + wait.Add(2) + go func() { defer wait.Done(); _, firstErr = authority.Acquire(ctx, proposed) }() + go func() { defer wait.Done(); _, secondErr = authority.Acquire(ctx, other) }() + wait.Wait() + if (firstErr == nil) == (secondErr == nil) { + t.Fatalf("expected exactly one session: %v %v", firstErr, secondErr) + } + stored, _, err := f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil { + t.Fatal(err) + } + if err := authority.Complete(ctx, confirmedBinding(stored.Management.Binding)); err != nil { + t.Fatal(err) + } + proposed.SessionUID = "racing-release" + var releaseErr error + wait.Add(2) + go func() { defer wait.Done(); _, firstErr = authority.Acquire(ctx, proposed) }() + go func() { defer wait.Done(); _, releaseErr = f.coordinator.Release(ctx, request.Claim.UID) }() + wait.Wait() + stored, _, err = f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil { + t.Fatal(err) + } + if firstErr == nil && releaseErr == nil || managementHeld(stored) && len(f.executor.requests) != 0 { + t.Fatal("release executed cleanup concurrently with management custody") + } + } +} + +func TestOldTeardownCannotClearNextSession(t *testing.T) { + ctx := context.Background() + f, _, asset, authority, proposed := managementFixture(t) + first, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + confirmation := confirmedBinding(first) + if err := authority.Complete(ctx, confirmation); err != nil { + t.Fatal(err) + } + proposed.SessionUID, proposed.SessionName = "next-session", "next-access" + next, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + if err := authority.Complete(ctx, confirmation); err != nil { + t.Fatal(err) + } + stored, _, err := f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil || !managementHeld(stored) || stored.Management.Binding.SessionUID != next.SessionUID { + t.Fatalf("old cleanup touched new authority: %+v %v", stored, err) + } + authority.Resolver.(*managementResolver).err = errors.New("project authorization revoked") + if authority.Active(ctx, &sessionv1.MachineManagementSessionBinding{Spec: next}) { + t.Fatal("refresh did not reauthorize") + } +} + +func TestSessionAdmissionConsumesLifecycleCustody(t *testing.T) { + ctx := context.Background() + f, request, asset, authority, proposed := managementFixture(t) + session := &sessionv1.MachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: proposed.SessionName, Namespace: proposed.SessionNamespace, UID: proposed.SessionUID, Annotations: map[string]string{PrincipalAnnotation: proposed.RequestingPrincipal}}, Spec: sessionv1.MachineManagementSessionSpec{MachineRef: sessionv1.LocalReference{Name: request.Claim.Name}, Protocol: proposed.Protocol, AccessProfile: proposed.AccessProfile, ClientPublicKey: proposed.ClientPublicKey}} + public := fake.NewClientBuilder().WithScheme(testScheme(t)).WithStatusSubresource(session, &sessionv1.MachineManagementSessionBinding{}).WithObjects(session, request.Claim).Build() + reconciler := &SessionReconciler{Client: public, Lifecycle: authority, Now: func() time.Time { return f.now }} + if _, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(session)}); err != nil { + t.Fatal(err) + } + var binding sessionv1.MachineManagementSessionBinding + if err := public.Get(ctx, client.ObjectKey{Namespace: SystemNamespace, Name: bindingName(session.UID)}, &binding); err != nil { + t.Fatal(err) + } + if binding.Spec.AllocationUID != types.UID(asset.BindingID) || binding.Spec.DeviceName != asset.DeviceName || binding.Spec.MachineCapacityUID != asset.MachineUID { + t.Fatalf("binding did not use authoritative custody: %+v", binding.Spec) + } + if err := public.Get(ctx, client.ObjectKeyFromObject(session), session); err != nil { + t.Fatal(err) + } + if err := public.Delete(ctx, session); err != nil { + t.Fatal(err) + } + reconciler.Now = func() time.Time { return time.Now().Add(time.Hour) } + if _, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(session)}); err != nil { + t.Fatal(err) + } + if err := public.Get(ctx, client.ObjectKeyFromObject(session), session); err != nil || !contains(session.Finalizers, sessionv1.SessionFinalizer) { + t.Fatalf("unknown teardown dropped finalizer: %v", err) + } +} + +func TestManagementAuthorizationAndPinnedTargets(t *testing.T) { + ctx := context.Background() + for _, mutation := range []string{"missing-authorizer", "denied", "project-lifetime", "namespace-lifetime", "machine-lifetime", "location", "device-unpinned", "capacity-recreated", "device-changed"} { + t.Run(mutation, func(t *testing.T) { + f, _, asset, authority, proposed := managementFixture(t) + resolver := authority.Resolver.(*managementResolver) + switch mutation { + case "missing-authorizer": + authority.Resolver = nil + case "denied": + resolver.err = errors.New("denied") + case "project-lifetime": + resolver.access.Scope.ProjectUID = "recreated" + case "machine-lifetime": + proposed.MachineUID = "recreated" + case "namespace-lifetime": + resolver.access.NamespaceUID = "recreated" + case "capacity-recreated": + resolver.access.CapacityUID = "recreated" + case "device-changed": + resolver.access.DeviceName = "other-device" + case "location": + resolver.access.LocationName = "other" + case "device-unpinned": + stored, secret, _ := f.coordinator.getAsset(ctx, asset.AssetID) + stored.DeviceName = "" + if err := encodeRecord(secret, stored, "asset"); err != nil { + t.Fatal(err) + } + if err := f.coordinator.client.Update(ctx, secret); err != nil { + t.Fatal(err) + } + } + if _, err := authority.Acquire(ctx, proposed); err == nil { + t.Fatal("untrusted input acquired authority") + } + }) + } +} + +func TestManagementRecoveryRetainsExactInputsDuringRelease(t *testing.T) { + ctx := context.Background() + f, request, _, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + proposed.ExpiresAt = metav1.NewTime(f.now.Add(2 * time.Hour)) + proposed.SessionCorrelationID = "new-random-value" + replayed, err := authority.Acquire(ctx, proposed) + if err != nil || !equality.Semantic.DeepEqual(replayed, retained) { + t.Fatalf("replay changed inputs: %+v %v", replayed, err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatal(err) + } + session := &sessionv1.MachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: retained.SessionName, Namespace: retained.SessionNamespace, UID: retained.SessionUID, Annotations: map[string]string{PrincipalAnnotation: retained.RequestingPrincipal}}, Spec: sessionv1.MachineManagementSessionSpec{MachineRef: sessionv1.LocalReference{Name: retained.MachineName}, Protocol: retained.Protocol, AccessProfile: retained.AccessProfile, ClientPublicKey: retained.ClientPublicKey}} + authority = &LifecycleSessionAuthority{Coordinator: f.coordinator} + recovered, err := authority.Recover(ctx, session) + if err != nil || !equality.Semantic.DeepEqual(recovered, &retained) { + t.Fatalf("orphaned hold cannot recover: %+v %v", recovered, err) + } + if err := sessionv1.AddToScheme(f.coordinator.client.Scheme()); err != nil { + t.Fatal(err) + } + if err := f.coordinator.client.Create(ctx, session); err != nil { + t.Fatal(err) + } + reconciler := &SessionReconciler{Client: f.coordinator.client, Lifecycle: authority} + if _, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(session)}); err != nil { + t.Fatal(err) + } + var binding sessionv1.MachineManagementSessionBinding + if err := f.coordinator.client.Get(ctx, client.ObjectKey{Namespace: SystemNamespace, Name: bindingName(session.UID)}, &binding); err != nil || !equality.Semantic.DeepEqual(binding.Spec, retained) { + t.Fatalf("binding recovery: %+v %v", binding, err) + } +} + +func TestProjectionIntentDistinguishesNeverStartedFromUnknown(t *testing.T) { + ctx := context.Background() + for _, projected := range []bool{false, true} { + f, request, _, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + binding := &sessionv1.MachineManagementSessionBinding{Spec: retained} + if projected { + if err := authority.BeginProjection(ctx, binding); err != nil { + t.Fatal(err) + } + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatal(err) + } + binding.Annotations = map[string]string{RevokedAtAnnotation: "revoked"} + closed, err := authority.CancelUnprojected(ctx, binding) + if err != nil || closed == projected { + t.Fatalf("projection intent %v, cancellation %v: %v", projected, closed, err) + } + if err := authority.BeginProjection(ctx, binding); err == nil { + t.Fatal("release permitted a new projection") + } + if !projected { + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatal("hold cleared before confirmation was retained") + } + if err := authority.Complete(ctx, confirmedBinding(retained)); err != nil { + t.Fatal(err) + } + } + result, err := f.coordinator.Release(ctx, request.Claim.UID) + if projected && (!errors.Is(err, ErrManagementActive) || result.SafeToRemoveFinalizer || len(f.executor.requests) != 0) { + t.Fatalf("uncertain projection allowed cleanup: %+v %v", result, err) + } + if !projected && (err != nil || !result.SafeToRemoveFinalizer) { + t.Fatalf("never-projected hold could not settle: %+v %v", result, err) + } + } +} + +func TestLegacyAssetRecordsCannotAdmitManagement(t *testing.T) { + ctx := context.Background() + f, request, asset, authority, proposed := managementFixture(t) + stored, secret, err := f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil { + t.Fatal(err) + } + stored.SchemaVersion = recordSchemaVersion + if err := encodeRecord(secret, stored, "asset"); err != nil { + t.Fatal(err) + } + if err := f.coordinator.client.Update(ctx, secret); err != nil { + t.Fatal(err) + } + if _, err := authority.Acquire(ctx, proposed); !errors.Is(err, ErrRecordInvalid) { + t.Fatalf("legacy record acquired a hold invisible to older writers: %v", err) + } + if result, err := f.coordinator.Release(ctx, request.Claim.UID); err != nil || !result.SafeToRemoveFinalizer { + t.Fatalf("legacy custody cannot drain: %+v %v", result, err) + } +} + +func TestLifecycleProjectionRequiresCurrentTeardownBeforeCleanup(t *testing.T) { + ctx := context.Background() + f, request, _, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + binding := &sessionv1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Name: bindingName(retained.SessionUID), Namespace: SystemNamespace, Generation: 1}, Spec: retained} + scheme := testScheme(t) + primary := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(binding).WithObjects(binding).Build() + federation := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&coordinationv1.ProjectedMachineManagementSession{}).Build() + reconciler := &ProjectionReconciler{Client: primary, FederationClient: federation, Lifecycle: authority, Now: func() time.Time { return f.now }} + req := ctrl.Request{NamespacedName: client.ObjectKeyFromObject(binding)} + if _, err := reconciler.Reconcile(ctx, req); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatal(err) + } + if _, err := reconciler.Reconcile(ctx, req); err != nil { + t.Fatal(err) + } + var projected coordinationv1.ProjectedMachineManagementSession + key := client.ObjectKey{Namespace: LocationNamespace, Name: binding.Name} + if err := federation.Get(ctx, key, &projected); err != nil { + t.Fatal(err) + } + if projected.Spec.DesiredState != sessionv1.ProjectionRevoked { + t.Fatal("release not propagated") + } + projected.Generation = 3 + if err := federation.Update(ctx, &projected); err != nil { + t.Fatal(err) + } + apimeta.SetStatusCondition(&projected.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, ObservedGeneration: 2, Reason: "Old"}) + if err := federation.Status().Update(ctx, &projected); err != nil { + t.Fatal(err) + } + if _, err := reconciler.Reconcile(ctx, req); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatalf("stale evidence cleared custody: %v", err) + } + projected.Status.TeardownSpecDigest = coordinationv1.TeardownDigest(&projected) + projected.Status.Conditions[0].ObservedGeneration = 77 + if err := federation.Status().Update(ctx, &projected); err != nil { + t.Fatal(err) + } + if _, err := reconciler.Reconcile(ctx, req); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); err != nil { + t.Fatal(err) + } + if err := federation.Get(ctx, key, &projected); err == nil { + t.Fatal("settled projection was not removed") + } +} diff --git a/internal/controller/projection.go b/internal/controller/projection.go index 410445ee..4316aa0d 100644 --- a/internal/controller/projection.go +++ b/internal/controller/projection.go @@ -15,12 +15,9 @@ import ( "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/reconcile" coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" - fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" ) // ProjectionReconciler writes only to the Karmada hub. Karmada carries the @@ -33,6 +30,7 @@ type ProjectionReconciler struct { HubNamespace string Now func() time.Time Freshness time.Duration + Lifecycle SessionLifecycle } func (r *ProjectionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -43,8 +41,11 @@ func (r *ProjectionReconciler) Reconcile(ctx context.Context, req ctrl.Request) if req.Namespace != r.systemNamespace() { return ctrl.Result{}, nil } + if cleanup := apimeta.FindStatusCondition(b.Status.Conditions, "CleanupConfirmed"); cleanup != nil && cleanup.Status == metav1.ConditionTrue { + return r.finishTeardown(ctx, &b) + } key := types.NamespacedName{Namespace: r.hubNamespace(), Name: b.Name} - active := r.allocationStillActive(ctx, &b) + active := r.now().Before(b.Spec.ExpiresAt.Time) && r.allocationStillActive(ctx, &b) if !active && b.Annotations[RevokedAtAnnotation] == "" { patch := client.MergeFrom(b.DeepCopy()) if b.Annotations == nil { @@ -60,8 +61,24 @@ func (r *ProjectionReconciler) Reconcile(ctx context.Context, req ctrl.Request) err := r.FederationClient.Get(ctx, key, &p) if apierrors.IsNotFound(err) { if b.Annotations[RevokedAtAnnotation] != "" || !active { + if r.Lifecycle != nil { + completed, err := r.Lifecycle.CancelUnprojected(ctx, &b) + if err != nil { + return ctrl.Result{}, err + } + if completed { + setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionTrue, "NeverProjected", "Private custody proves no projection was admitted.", r.now()) + if err := r.Status().Update(ctx, &b); err != nil { + return ctrl.Result{}, err + } + return r.finishTeardown(ctx, &b) + } + } return ctrl.Result{}, nil } + if err := r.Lifecycle.BeginProjection(ctx, &b); err != nil { + return ctrl.Result{}, err + } p = *r.build(&b) if err := r.FederationClient.Create(ctx, &p); err != nil { return ctrl.Result{}, err @@ -111,29 +128,7 @@ func (r *ProjectionReconciler) Reconcile(ctx context.Context, req ctrl.Request) } func (r *ProjectionReconciler) allocationStillActive(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding) bool { - var allocation fleetv1.MachineAllocation - if err := r.Get(ctx, types.NamespacedName{Namespace: r.systemNamespace(), Name: b.Spec.AllocationName}, &allocation); err != nil { - return false - } - if allocation.UID != b.Spec.AllocationUID || allocation.Status.Phase != "Active" || - allocation.Spec.MachineRef.Project != b.Spec.ConsumerProject || - allocation.Spec.MachineRef.Namespace != b.Spec.MachineNamespace || allocation.Spec.MachineRef.Name != b.Spec.MachineName || - allocation.Spec.MachineCapacityRef.Namespace != b.Spec.MachineCapacityNamespace || allocation.Spec.MachineCapacityRef.Name != b.Spec.MachineCapacityName || - allocation.Annotations[AllocationMachineUIDAnnotation] != string(b.Spec.MachineUID) || - allocation.Annotations[MemberClusterAnnotation] != b.Spec.MemberCluster || - allocation.Annotations[LocationNameAnnotation] != b.Spec.LocationName || - allocation.Annotations[ProviderProjectAnnotation] != b.Spec.ProviderProject { - return false - } - var machine fleetv1.Machine - if err := r.Get(ctx, types.NamespacedName{Namespace: b.Spec.MachineNamespace, Name: b.Spec.MachineName}, &machine); err != nil || machine.UID != b.Spec.MachineUID { - return false - } - var capacity fleetv1.MachineCapacity - if err := r.Get(ctx, types.NamespacedName{Namespace: b.Spec.MachineCapacityNamespace, Name: b.Spec.MachineCapacityName}, &capacity); err != nil { - return false - } - return capacity.UID == b.Spec.MachineCapacityUID && capacity.Spec.DeviceRef.Name == b.Spec.DeviceName + return r.Lifecycle != nil && r.Lifecycle.Active(ctx, b) } func (r *ProjectionReconciler) revokeProjection(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding, p *coordinationv1.ProjectedMachineManagementSession) (ctrl.Result, error) { @@ -146,18 +141,29 @@ func (r *ProjectionReconciler) revokeProjection(ctx context.Context, b *fleetv1a return ctrl.Result{RequeueAfter: time.Second}, nil } cleanup := apimeta.FindStatusCondition(p.Status.Conditions, "CleanupConfirmed") - if cleanup == nil || cleanup.Status != metav1.ConditionTrue { + if cleanup == nil || cleanup.Status != metav1.ConditionTrue || p.Status.TeardownSpecDigest != coordinationv1.TeardownDigest(p) { return ctrl.Result{RequeueAfter: time.Second}, nil } - if err := r.deletePolicy(ctx, b.Name); err != nil { + setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionTrue, "LocationTeardownConfirmed", "The selected location gateway confirmed session teardown through Karmada status aggregation.", r.now()) + setNamedCondition(&b.Status.Conditions, fleetv1alpha1.ConditionReady, b.Generation, metav1.ConditionFalse, "Revoked", "The session authority has ended.", r.now()) + if err := r.Status().Update(ctx, b); err != nil { return ctrl.Result{}, err } - if err := r.FederationClient.Delete(ctx, p); err != nil && !apierrors.IsNotFound(err) { + return r.finishTeardown(ctx, b) +} + +func (r *ProjectionReconciler) finishTeardown(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding) (ctrl.Result, error) { + if r.Lifecycle == nil { + return ctrl.Result{}, ErrUnsupported + } + if err := r.Lifecycle.Complete(ctx, b); err != nil { return ctrl.Result{}, err } - setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionTrue, "LocationTeardownConfirmed", "The selected location gateway confirmed session teardown through Karmada status aggregation.", r.now()) - setNamedCondition(&b.Status.Conditions, fleetv1alpha1.ConditionReady, b.Generation, metav1.ConditionFalse, "Revoked", "The session authority has ended.", r.now()) - return ctrl.Result{}, r.Status().Update(ctx, b) + if err := r.deletePolicy(ctx, b.Name); err != nil { + return ctrl.Result{}, err + } + projection := &coordinationv1.ProjectedMachineManagementSession{ObjectMeta: metav1.ObjectMeta{Namespace: r.hubNamespace(), Name: b.Name}} + return ctrl.Result{}, client.IgnoreNotFound(r.FederationClient.Delete(ctx, projection)) } func (r *ProjectionReconciler) build(b *fleetv1alpha1.MachineManagementSessionBinding) *coordinationv1.ProjectedMachineManagementSession { @@ -226,19 +232,7 @@ func (r *ProjectionReconciler) SetupWithManager(mgr ctrl.Manager) error { } r.Client = mgr.GetClient() return ctrl.NewControllerManagedBy(mgr). - For(&fleetv1alpha1.MachineManagementSessionBinding{}). - Watches(&fleetv1.MachineAllocation{}, handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, obj client.Object) []reconcile.Request { - a := obj.(*fleetv1.MachineAllocation) - var list fleetv1alpha1.MachineManagementSessionBindingList - if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace()), client.MatchingLabels{AllocationNameLabel: a.Name}); err != nil { - return nil - } - out := make([]reconcile.Request, 0, len(list.Items)) - for i := range list.Items { - out = append(out, reconcile.Request{NamespacedName: types.NamespacedName{Namespace: list.Items[i].Namespace, Name: list.Items[i].Name}}) - } - return out - })).Complete(r) + For(&fleetv1alpha1.MachineManagementSessionBinding{}).Complete(r) } func (r *ProjectionReconciler) systemNamespace() string { diff --git a/internal/controller/projection_test.go b/internal/controller/projection_test.go index feede248..1d4a115f 100644 --- a/internal/controller/projection_test.go +++ b/internal/controller/projection_test.go @@ -2,6 +2,7 @@ package controller import ( "context" + "errors" "testing" "time" @@ -54,14 +55,15 @@ func TestReleasedAllocationTerminallyRevokesProjection(t *testing.T) { t.Fatal("allocation release was not propagated as revocation") } apimeta.SetStatusCondition(&revoked.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, Reason: "GatewayStopped", Message: "stopped", ObservedGeneration: revoked.Generation}) + revoked.Status.TeardownSpecDigest = coordinationv1.TeardownDigest(&revoked) if err := federation.Status().Update(context.Background(), &revoked); err != nil { t.Fatal(err) } - if _, err := r.Reconcile(context.Background(), req); err != nil { - t.Fatal(err) + if _, err := r.Reconcile(context.Background(), req); !errors.Is(err, ErrUnsupported) { + t.Fatalf("missing lifecycle authority must block completion: %v", err) } - if err := federation.Get(context.Background(), key, &revoked); err == nil { - t.Fatal("acknowledged federated projection survived cleanup") + if err := federation.Get(context.Background(), key, &revoked); err != nil { + t.Fatal("projection evidence removed without lifecycle settlement") } } diff --git a/internal/controller/session.go b/internal/controller/session.go index c2070863..9649b242 100644 --- a/internal/controller/session.go +++ b/internal/controller/session.go @@ -29,20 +29,16 @@ import ( ) const ( - SystemNamespace = "fleet-system" - LocationNamespace = "machine-access-system" - PrincipalAnnotation = "fleet.datumapis.com/requesting-principal" - MachineUIDLabel = "fleet.datumapis.com/machine-uid" - AllocationNameLabel = "fleet.datumapis.com/allocation-name" - SessionUIDLabel = "fleet.datumapis.com/session-uid" - RevokedAtAnnotation = "fleet.datumapis.com/revoked-at" - MemberClusterLabel = "fleet.datumapis.com/member-cluster" - MemberClusterAnnotation = "fleet.datumapis.com/member-cluster" - ProviderProjectAnnotation = "fleet.datumapis.com/provider-project" - LocationNameAnnotation = "fleet.datumapis.com/location-name" - AllocationMachineUIDAnnotation = "fleet.datumapis.com/machine-uid" - DefaultConnectWindow = time.Minute - DefaultAuthorityFreshness = 2 * time.Minute + SystemNamespace = "fleet-system" + LocationNamespace = "machine-access-system" + PrincipalAnnotation = "fleet.datumapis.com/requesting-principal" + MachineUIDLabel = "fleet.datumapis.com/machine-uid" + AllocationNameLabel = "fleet.datumapis.com/allocation-name" + SessionUIDLabel = "fleet.datumapis.com/session-uid" + RevokedAtAnnotation = "fleet.datumapis.com/revoked-at" + MemberClusterLabel = "fleet.datumapis.com/member-cluster" + DefaultConnectWindow = time.Minute + DefaultAuthorityFreshness = 2 * time.Minute ) type SessionReconciler struct { @@ -51,6 +47,7 @@ type SessionReconciler struct { Now func() time.Time PerClaimLimit int PerProjectLimit int + Lifecycle SessionLifecycle } func (r *SessionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -58,6 +55,25 @@ func (r *SessionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct if err := r.Get(ctx, req.NamespacedName, &session); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } + if session.UID != "" && r.Lifecycle != nil { + binding, err := r.bindingForSession(ctx, session.UID) + if err != nil { + return ctrl.Result{}, err + } + if binding == nil { + retained, err := r.Lifecycle.Recover(ctx, &session) + if err != nil { + return ctrl.Result{}, err + } + if retained != nil { + binding = &fleetv1alpha1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Name: bindingName(session.UID), Namespace: r.systemNamespace(), Labels: map[string]string{SessionUIDLabel: string(session.UID), MachineUIDLabel: string(retained.MachineUID), AllocationNameLabel: retained.AllocationName}}, Spec: *retained} + if err := r.Create(ctx, binding); err != nil && !apierrors.IsAlreadyExists(err) { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } + } + } if !session.DeletionTimestamp.IsZero() { return r.revoke(ctx, &session) } @@ -94,46 +110,8 @@ func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.Ma } return ctrl.Result{}, err } - var allocations fleetv1.MachineAllocationList - if err := r.List(ctx, &allocations, client.InNamespace(r.systemNamespace())); err != nil { - return ctrl.Result{}, err - } - matching := make([]*fleetv1.MachineAllocation, 0, 1) - for i := range allocations.Items { - a := &allocations.Items[i] - if a.Status.Phase == "Active" && a.Spec.MachineRef.Namespace == machine.Namespace && a.Spec.MachineRef.Name == machine.Name { - matching = append(matching, a) - } - } - if len(matching) != 1 { - return r.reject(ctx, session, "MachineNotAllocated", "The Machine does not have exactly one active authoritative allocation.") - } - a := matching[0] - if a.Annotations[AllocationMachineUIDAnnotation] != string(machine.UID) { - return r.reject(ctx, session, "AllocationChanged", "The active allocation does not belong to this Machine incarnation.") - } - var capacity fleetv1.MachineCapacity - capacityKey := types.NamespacedName{Namespace: a.Spec.MachineCapacityRef.Namespace, Name: a.Spec.MachineCapacityRef.Name} - if err := r.Get(ctx, capacityKey, &capacity); err != nil { - if apierrors.IsNotFound(err) { - return r.reject(ctx, session, "CapacityNotFound", "The allocated MachineCapacity is unavailable.") - } - return ctrl.Result{}, err - } - member := a.Annotations[MemberClusterAnnotation] - location := a.Annotations[LocationNameAnnotation] - providerProject := a.Annotations[ProviderProjectAnnotation] - if member == "" || location == "" { - return r.reject(ctx, session, "LocationNotFederated", "The allocation location has no registered federation member.") - } - if providerProject == "" || capacity.Spec.DeviceRef.Name == "" { - return r.reject(ctx, session, "ProviderTargetUnresolved", "The allocation does not resolve to registered provider capacity.") - } - if result, err := r.enforceLimits(ctx, a.Spec.MachineRef.Project, machine.UID); err != nil || result != nil { - if err != nil { - return ctrl.Result{}, err - } - return r.reject(ctx, session, "SessionLimitExceeded", *result) + if r.Lifecycle == nil { + return r.reject(ctx, session, "AuthorityUnavailable", "Authoritative lifecycle access is unavailable.") } now := r.now() ttl := session.Spec.TTL.Duration @@ -145,20 +123,36 @@ func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.Ma b := &fleetv1alpha1.MachineManagementSessionBinding{ TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSessionBinding"}, ObjectMeta: metav1.ObjectMeta{Name: bindingName(session.UID), Namespace: r.systemNamespace(), Labels: map[string]string{ - SessionUIDLabel: string(session.UID), MachineUIDLabel: string(machine.UID), AllocationNameLabel: a.Name, + SessionUIDLabel: string(session.UID), MachineUIDLabel: string(machine.UID), }}, Spec: fleetv1alpha1.MachineManagementSessionBindingSpec{ SessionNamespace: session.Namespace, SessionName: session.Name, SessionUID: session.UID, - RequestingPrincipal: principal, ConsumerProject: a.Spec.MachineRef.Project, ProviderProject: providerProject, - MachineNamespace: machine.Namespace, MachineName: machine.Name, MachineUID: machine.UID, - AllocationName: a.Name, AllocationUID: a.UID, - MachineCapacityNamespace: capacity.Namespace, MachineCapacityName: capacity.Name, MachineCapacityUID: capacity.UID, - DeviceName: capacity.Spec.DeviceRef.Name, LocationName: location, MemberCluster: member, + RequestingPrincipal: principal, + MachineNamespace: machine.Namespace, MachineName: machine.Name, MachineUID: machine.UID, Protocol: session.Spec.Protocol, AccessProfile: session.Spec.AccessProfile, ClientPublicKey: session.Spec.ClientPublicKey, ConnectBefore: connect, ExpiresAt: expiry, SessionCorrelationID: randomCorrelationID(), OperationCorrelationID: randomCorrelationID(), }, } + if !machine.DeletionTimestamp.IsZero() { + return r.reject(ctx, session, "MachineDeleting", "The Machine is being released.") + } + prepared, err := r.Lifecycle.Prepare(ctx, b.Spec) + if err != nil { + return ctrl.Result{}, err + } + if result, err := r.enforceLimits(ctx, prepared.ConsumerProject, machine.UID); err != nil || result != nil { + if err != nil { + return ctrl.Result{}, err + } + return r.reject(ctx, session, "SessionLimitExceeded", *result) + } + retained, err := r.Lifecycle.Acquire(ctx, prepared) + if err != nil { + return ctrl.Result{RequeueAfter: time.Second}, err + } + b.Spec = retained + b.Labels[AllocationNameLabel] = retained.AllocationName if err := r.Create(ctx, b); err != nil { if apierrors.IsAlreadyExists(err) { return ctrl.Result{Requeue: true}, nil @@ -167,7 +161,7 @@ func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.Ma } fleetmetrics.SessionAdmissions.WithLabelValues("admitted").Inc() slog.InfoContext(ctx, "machine-management session admitted", - "session", session.Name, "machine", machine.Name, "allocation", a.Name, + "session", session.Name, "machine", machine.Name, "allocation", retained.AllocationName, "principal", principal, "sessionCorrelationID", b.Spec.SessionCorrelationID) return ctrl.Result{RequeueAfter: time.Second}, nil } @@ -251,6 +245,9 @@ func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.Machine if !controllerutil.ContainsFinalizer(s, fleetv1alpha1.SessionFinalizer) { return ctrl.Result{}, nil } + if r.Lifecycle == nil { + return ctrl.Result{}, ErrUnsupported + } b, err := r.bindingForSession(ctx, s.UID) if err == nil && b != nil { if b.Annotations[RevokedAtAnnotation] == "" { @@ -265,6 +262,9 @@ func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.Machine slog.InfoContext(ctx, "machine-management session revocation requested", "session", s.Name, "allocation", b.Spec.AllocationName, "sessionCorrelationID", b.Spec.SessionCorrelationID) } if c := apimeta.FindStatusCondition(b.Status.Conditions, "CleanupConfirmed"); c != nil && c.Status == metav1.ConditionTrue { + if err := r.Lifecycle.Complete(ctx, b); err != nil { + return ctrl.Result{}, err + } fleetmetrics.RevocationLatency.Observe(r.now().Sub(s.DeletionTimestamp.Time).Seconds()) patch := client.MergeFrom(s.DeepCopy()) controllerutil.RemoveFinalizer(s, fleetv1alpha1.SessionFinalizer) @@ -276,9 +276,7 @@ func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.Machine if err := r.Status().Update(ctx, b); err != nil { return ctrl.Result{}, err } - patch := client.MergeFrom(s.DeepCopy()) - controllerutil.RemoveFinalizer(s, fleetv1alpha1.SessionFinalizer) - return ctrl.Result{}, r.Patch(ctx, s, patch) + return ctrl.Result{RequeueAfter: time.Second}, nil } return ctrl.Result{RequeueAfter: time.Second}, nil } else if err != nil { diff --git a/internal/controller/session_test.go b/internal/controller/session_test.go index dc384836..fbc04c66 100644 --- a/internal/controller/session_test.go +++ b/internal/controller/session_test.go @@ -17,6 +17,13 @@ import ( fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" ) +const ( + MemberClusterAnnotation = "fleet.datumapis.com/member-cluster" + ProviderProjectAnnotation = "fleet.datumapis.com/provider-project" + LocationNameAnnotation = "fleet.datumapis.com/location-name" + AllocationMachineUIDAnnotation = "fleet.datumapis.com/machine-uid" +) + func testScheme(t *testing.T) *runtime.Scheme { t.Helper() s := runtime.NewScheme() @@ -32,7 +39,7 @@ func testScheme(t *testing.T) *runtime.Scheme { return s } -func TestAdmissionPinsMachineAllocationAndCapacity(t *testing.T) { +func TestPreboundAllocationCannotAuthorizeSession(t *testing.T) { scheme := testScheme(t) now := time.Unix(1000, 0) machine := testMachine("machine-uid") @@ -52,16 +59,9 @@ func TestAdmissionPinsMachineAllocationAndCapacity(t *testing.T) { if err := c.List(context.Background(), &bindings, client.InNamespace(SystemNamespace)); err != nil { t.Fatal(err) } - if len(bindings.Items) != 1 { + if len(bindings.Items) != 0 { t.Fatalf("bindings=%d", len(bindings.Items)) } - b := bindings.Items[0] - if b.Name != bindingName(session.UID) { - t.Fatalf("binding name=%q, want deterministic opaque name %q", b.Name, bindingName(session.UID)) - } - if b.Spec.MachineUID != machine.UID || b.Spec.AllocationUID != allocation.UID || b.Spec.MachineCapacityUID != capacity.UID || b.Spec.DeviceName != "device-a" || b.Spec.ProviderProject != "provider" || b.Spec.RequestingPrincipal != "alice@example.test" { - t.Fatalf("binding not pinned: %+v", b.Spec) - } } func TestBindingNameIsStableAndOpaque(t *testing.T) { @@ -92,7 +92,7 @@ func TestRecreatedMachineNameCannotInheritAllocation(t *testing.T) { if err := c.Get(context.Background(), req.NamespacedName, &got); err != nil { t.Fatal(err) } - if len(got.Status.Conditions) == 0 || got.Status.Conditions[0].Reason != "AllocationChanged" { + if len(got.Status.Conditions) == 0 || got.Status.Conditions[0].Reason != "AuthorityUnavailable" { t.Fatalf("conditions %+v", got.Status.Conditions) } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index ec6e74a6..9183193e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4,6 +4,7 @@ package gateway import ( "bufio" + "bytes" "context" "crypto/ed25519" "crypto/rand" @@ -12,6 +13,7 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/hex" + "encoding/json" "encoding/pem" "errors" "fmt" @@ -72,10 +74,13 @@ type Reconciler struct { } type activeSession struct { - cancel context.CancelFunc - mu sync.RWMutex - spec coordinationv1.ProjectedMachineManagementSessionSpec - target resolvedTarget + cancel context.CancelFunc + mu sync.RWMutex + effects sync.RWMutex + stopped bool + done chan struct{} + spec coordinationv1.ProjectedMachineManagementSessionSpec + target resolvedTarget } type resolvedTarget struct { @@ -100,10 +105,15 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu now := time.Now() if p.Spec.DesiredState == fleetv1alpha1.ProjectionRevoked { r.stop(req.NamespacedName) - if cleanup := apimeta.FindStatusCondition(p.Status.Conditions, "CleanupConfirmed"); cleanup != nil && cleanup.Status == metav1.ConditionTrue { + if cleanup := apimeta.FindStatusCondition(p.Status.Conditions, "CleanupConfirmed"); cleanup != nil && cleanup.Status == metav1.ConditionTrue && cleanup.ObservedGeneration == p.Generation && p.Status.TeardownSpecDigest == coordinationv1.TeardownDigest(&p) { return ctrl.Result{}, nil } + if err := r.verifyTeardown(req.NamespacedName, p.Spec.MachineCapacityRef.Name); err != nil { + apimeta.SetStatusCondition(&p.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionUnknown, Reason: "EffectsUnconfirmed", Message: "Session shutdown or durable effect settlement is unconfirmed.", ObservedGeneration: p.Generation, LastTransitionTime: metav1.Now()}) + return ctrl.Result{RequeueAfter: time.Second}, r.Status().Update(ctx, &p) + } setCondition(&p, metav1.ConditionFalse, "Revoked", "The central allocation authority revoked this session.") + p.Status.TeardownSpecDigest = coordinationv1.TeardownDigest(&p) apimeta.SetStatusCondition(&p.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, Reason: "GatewayStopped", Message: "The location gateway closed the relay stream and discarded session authority.", ObservedGeneration: p.Generation, LastTransitionTime: metav1.Now()}) return ctrl.Result{}, r.Status().Update(ctx, &p) } @@ -129,7 +139,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu return ctrl.Result{RequeueAfter: 5 * time.Second}, r.Status().Update(ctx, &p) } runCtx, cancel := context.WithCancel(context.Background()) - a = &activeSession{cancel: cancel, spec: p.Spec, target: target} + a = &activeSession{cancel: cancel, spec: p.Spec, target: target, done: make(chan struct{})} r.active[req.NamespacedName] = a go r.run(runCtx, req.NamespacedName, a) } else { @@ -153,6 +163,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu } func (r *Reconciler) run(ctx context.Context, key client.ObjectKey, a *activeSession) { + defer close(a.done) fleetmetrics.ActiveSessions.Inc() defer fleetmetrics.ActiveSessions.Dec() cert, der, fingerprint, err := loadOrCreateCertificate(r.Config.StateDir, key.Name) @@ -160,11 +171,33 @@ func (r *Reconciler) run(ctx context.Context, key client.ObjectKey, a *activeSes r.failStatus(key, "GatewayCertificateError", "The location gateway could not create its session certificate.") return } - store, err := journal.Open(filepath.Join(r.Config.JournalDir, "operations")) + sessionStore, err := journal.Open(filepath.Join(r.Config.JournalDir, "sessions")) + if err != nil { + return + } + if _, err := sessionStore.Get(journal.Identity(key.Name, "REVOKED", "", nil)); !errors.Is(err, os.ErrNotExist) { + r.failStatus(key, "SessionRevoked", "The durable journal does not permit this session to start.") + return + } + marker := journal.Identity(key.Name, "SESSION", "", nil) + var store *journal.Store + if _, markerErr := sessionStore.Get(marker); markerErr == nil { + store, err = r.existingOperations() + } else if errors.Is(markerErr, os.ErrNotExist) { + store, err = journal.Open(filepath.Join(r.Config.JournalDir, "operations")) + } else { + err = markerErr + } if err != nil { r.failStatus(key, "JournalUnavailable", "The durable operation journal is unavailable.") return } + a.mu.RLock() + sessionSpec, sessionTarget := a.spec, a.target + a.mu.RUnlock() + if err := retainSession(sessionStore, key.Name, sessionSpec, sessionTarget); err != nil { + return + } routeID := randomHex(24) conn, err := r.dialRelay(ctx, routeID) if err != nil { @@ -200,7 +233,8 @@ func (r *Reconciler) run(ctx context.Context, key client.ObjectKey, a *activeSes // The relay admits one connector for the session, so an HTTP idle timeout // would permanently strand a valid session during a long PXE boot. Expiry, // revocation, and projection teardown bound the stream lifetime instead. - server := &http.Server{Handler: protected, ReadHeaderTimeout: 10 * time.Second, MaxHeaderBytes: 16 << 10} + server := &http.Server{Handler: protected, ReadHeaderTimeout: 10 * time.Second, MaxHeaderBytes: 16 << 10, BaseContext: func(net.Listener) context.Context { return ctx }} + defer server.Close() _ = server.Serve(newOneConnListener(tlsConn)) _ = der // DER is retained only to make certificate pin derivation explicit. r.endedStatus(key, "Disconnected", "The client connection ended.") @@ -223,6 +257,12 @@ func (r *Reconciler) proofMiddleware(a *activeSession, routeID string, next http used := map[string]bool{} var mu sync.Mutex return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + a.effects.RLock() + defer a.effects.RUnlock() + if a.stopped { + http.Error(w, "session revoked", http.StatusForbidden) + return + } a.mu.RLock() spec := a.spec a.mu.RUnlock() @@ -288,8 +328,86 @@ func (r *Reconciler) stop(key client.ObjectKey) { defer r.mu.Unlock() if a := r.active[key]; a != nil { a.cancel() - delete(r.active, key) + a.effects.Lock() + a.stopped = true + a.effects.Unlock() + } +} + +func (r *Reconciler) verifyTeardown(key client.ObjectKey, capacity string) error { + r.mu.Lock() + defer r.mu.Unlock() + if active := r.active[key]; active != nil { + select { + case <-active.done: + default: + return fmt.Errorf("gateway stream has not stopped") + } + } + store, err := r.existingOperations() + if err != nil { + return err + } + markerID := journal.Identity(key.Name, "SESSION", "", nil) + sessionStore, err := journal.Open(filepath.Join(r.Config.JournalDir, "sessions")) + if err != nil { + return err } + marker, err := sessionStore.Get(markerID) + if err != nil || marker.SessionName != key.Name || marker.MachineCapacityName != capacity || marker.Outcome != journal.Succeeded { + return fmt.Errorf("session journal custody is unavailable") + } + operations, err := store.List() + if err != nil { + return err + } + for _, operation := range operations { + if operation.SessionName == key.Name && (operation.MachineCapacityName != capacity || operation.Outcome != journal.Succeeded) { + return fmt.Errorf("session effects are not verified") + } + } + tombstone := journal.Identity(key.Name, "REVOKED", "", nil) + if _, _, err := sessionStore.Admit(journal.Operation{ID: tombstone, SessionName: key.Name, MachineCapacityName: capacity, DeviceName: marker.DeviceName}); err != nil { + return err + } + if _, err := sessionStore.Finish(tombstone, journal.Succeeded, 0, "session terminally revoked after request and effect settlement"); err != nil { + return err + } + delete(r.active, key) + return nil +} + +func (r *Reconciler) existingOperations() (*journal.Store, error) { + directory := filepath.Join(r.Config.JournalDir, "operations") + if info, err := os.Stat(directory); err != nil { + return nil, err + } else if !info.IsDir() { + return nil, fmt.Errorf("operation journal directory is unavailable") + } + return journal.Open(directory) +} + +func retainSession(store *journal.Store, name string, spec coordinationv1.ProjectedMachineManagementSessionSpec, target resolvedTarget) error { + spec.AuthorityFreshUntil = metav1.Time{} + inputs, err := json.Marshal(spec) + if err != nil { + return err + } + marker := journal.Identity(name, "SESSION", "", nil) + physical := target.Adapter + ":" + target.SystemID + retained, _, err := store.Admit(journal.Operation{ID: marker, SessionName: name, MachineCapacityName: target.MachineCapacityName, DeviceName: target.DeviceName, PhysicalTarget: physical, AcceptedBody: inputs}) + if err != nil { + return err + } + var retainedInputs bytes.Buffer + if err := json.Compact(&retainedInputs, retained.AcceptedBody); err != nil { + return err + } + if retained.SessionName != name || retained.MachineCapacityName != target.MachineCapacityName || retained.DeviceName != target.DeviceName || retained.PhysicalTarget != physical || !bytes.Equal(retainedInputs.Bytes(), inputs) { + return fmt.Errorf("retained session inputs differ") + } + _, err = store.Finish(marker, journal.Succeeded, 0, "session journal retained before route registration") + return err } func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { r.Client = mgr.GetClient() diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 12f14b19..68f8c4fe 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -2,12 +2,21 @@ package gateway import ( "context" + "crypto/ed25519" + "crypto/rand" + "net/http" + "net/http/httptest" + "os" + "path/filepath" "testing" "time" + "go.datum.net/fleet/internal/journal" + "go.datum.net/fleet/internal/protocol" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" @@ -15,6 +24,124 @@ import ( fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" ) +func TestTeardownRequiresDurableSettledEffects(t *testing.T) { + for _, outcome := range []journal.Outcome{journal.Pending, journal.Unknown, journal.Failed, journal.Succeeded} { + t.Run(string(outcome), func(t *testing.T) { + reconciler := &Reconciler{Config: Config{JournalDir: t.TempDir()}} + key := client.ObjectKey{Namespace: "cell", Name: "session"} + if err := reconciler.verifyTeardown(key, "capacity"); err == nil { + t.Fatal("missing journal treated as cleanup proof") + } + store, err := journal.Open(filepath.Join(reconciler.Config.JournalDir, "operations")) + if err != nil { + t.Fatal(err) + } + control, err := journal.Open(filepath.Join(reconciler.Config.JournalDir, "sessions")) + if err != nil { + t.Fatal(err) + } + marker := journal.Identity(key.Name, "SESSION", "", nil) + if _, _, err := control.Admit(journal.Operation{ID: marker, SessionName: key.Name, MachineCapacityName: "capacity", DeviceName: "device"}); err != nil { + t.Fatal(err) + } + if _, err := control.Finish(marker, journal.Succeeded, 0, "synthetic proof"); err != nil { + t.Fatal(err) + } + if _, _, err := store.Admit(journal.Operation{ID: "effect", SessionName: key.Name, MachineCapacityName: "capacity", DeviceName: "device"}); err != nil { + t.Fatal(err) + } + if _, err := store.Finish("effect", outcome, 0, "synthetic result"); err != nil { + t.Fatal(err) + } + restarted := &Reconciler{Config: reconciler.Config} + if err := restarted.verifyTeardown(key, "capacity"); (err == nil) != (outcome == journal.Succeeded) { + t.Fatalf("outcome %s: %v", outcome, err) + } + if outcome == journal.Succeeded { + if _, err := control.Get(journal.Identity(key.Name, "REVOKED", "", nil)); err != nil { + t.Fatalf("missing durable revocation: %v", err) + } + if err := os.RemoveAll(filepath.Join(reconciler.Config.JournalDir, "operations")); err != nil { + t.Fatal(err) + } + if err := restarted.verifyTeardown(key, "capacity"); err == nil { + t.Fatal("lost operation directory treated as empty evidence") + } + } + }) + } +} + +func TestStopDrainsRequestsAndDeniesLaterEffects(t *testing.T) { + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + active := &activeSession{cancel: cancel, done: make(chan struct{}), spec: coordinationv1.ProjectedMachineManagementSessionSpec{ClientPublicKey: protocol.PublicKey(privateKey)}} + key := client.ObjectKey{Name: "session", Namespace: "cell"} + reconciler := &Reconciler{Config: Config{Audience: "audience"}, active: map[client.ObjectKey]*activeSession{key: active}} + entered, release, served, stopped := make(chan struct{}), make(chan struct{}), make(chan struct{}), make(chan struct{}) + handler := reconciler.proofMiddleware(active, "route", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { close(entered); <-release })) + proof, err := protocol.Sign(privateKey, "route", "audience", time.Now()) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, "/", nil) + request.Header.Set(HeaderSession, "route") + request.Header.Set(HeaderAudience, "audience") + request.Header.Set(HeaderTimestamp, proof.Timestamp) + request.Header.Set(HeaderNonce, proof.Nonce) + request.Header.Set(HeaderSignature, proof.Signature) + go func() { handler.ServeHTTP(httptest.NewRecorder(), request); close(served) }() + <-entered + go func() { reconciler.stop(key); close(stopped) }() + <-ctx.Done() + select { + case <-stopped: + t.Fatal("teardown returned with a running effect") + default: + } + close(release) + <-served + <-stopped + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusForbidden { + t.Fatalf("post-revocation request: %d", response.Code) + } + if err := reconciler.verifyTeardown(key, "capacity"); err == nil { + t.Fatal("unstopped stream accepted as teardown") + } + close(active.done) +} + +func TestRetainedSessionRejectsChangedInputsAfterRestart(t *testing.T) { + store, err := journal.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + spec := coordinationv1.ProjectedMachineManagementSessionSpec{DesiredState: fleetv1alpha1.ProjectionActive, ClientPublicKey: "key"} + target := resolvedTarget{MachineCapacityName: "capacity", DeviceName: "device", Adapter: "synthetic", SystemID: "physical"} + if err := retainSession(store, "session", spec, target); err != nil { + t.Fatal(err) + } + spec.AuthorityFreshUntil = metav1.Now() + if err := retainSession(store, "session", spec, target); err != nil { + t.Fatalf("freshness could not advance: %v", err) + } + spec.ClientPublicKey = "changed" + if err := retainSession(store, "session", spec, target); err == nil { + t.Fatal("changed client key recovered old authority") + } + spec.ClientPublicKey = "key" + target.DeviceName = "other-device" + if err := retainSession(store, "session", spec, target); err == nil { + t.Fatal("changed device recovered old authority") + } +} + func TestBindingInputsCannotChangeAfterGatewayAcceptance(t *testing.T) { a := coordinationv1.ProjectedMachineManagementSessionSpec{ MachineCapacityRef: fleetv1alpha1.LocalReference{Name: "capacity"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", diff --git a/internal/redfish/handler.go b/internal/redfish/handler.go index 38b7353c..9c04cd4a 100644 --- a/internal/redfish/handler.go +++ b/internal/redfish/handler.go @@ -226,6 +226,22 @@ func (h *Handler) mutate(w http.ResponseWriter, r *http.Request, raw []byte, eff id := journal.Identity(authority.SessionName, r.Method, r.URL.Path, raw) unlock := h.Journal.MachineLock(authority.DeviceName) defer unlock() + current := h.authority() + if current.SessionName != authority.SessionName || current.DeviceName != authority.DeviceName || current.MachineCapacityName != authority.MachineCapacityName || current.OperationEpoch != authority.OperationEpoch || !h.now().Before(current.ExpiresAt) || !h.now().Before(current.FreshUntil) { + writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.AuthorityStale", "Hardware authority changed while waiting for serialization.") + return + } + operations, err := h.Journal.List() + if err != nil { + writeError(w, http.StatusInternalServerError, "Fleet.1.0.JournalUnavailable", "Prior hardware effects could not be verified.") + return + } + for _, operation := range operations { + if operation.DeviceName == authority.DeviceName && operation.ID != id && operation.Outcome != journal.Succeeded { + writeError(w, http.StatusConflict, "Fleet.1.0.OperationUnconfirmed", "A previous hardware effect has not been verified.") + return + } + } op, fresh, err := h.Journal.Admit(journal.Operation{ID: id, SessionName: authority.SessionName, MachineCapacityName: authority.MachineCapacityName, DeviceName: authority.DeviceName, Method: r.Method, VirtualTarget: r.URL.Path, AcceptedBody: append([]byte(nil), raw...), PhysicalTarget: h.Adapter.PhysicalTarget(), IdempotencyIdentity: id, OperationEpoch: authority.OperationEpoch, ConflictPrecondition: fmt.Sprintf("capacity=%s device=%s fresh-before=%s", authority.MachineCapacityName, authority.DeviceName, authority.FreshUntil.UTC().Format(time.RFC3339))}) if err != nil { writeError(w, http.StatusInternalServerError, "Fleet.1.0.JournalUnavailable", "The mutation could not be durably admitted.") @@ -243,8 +259,9 @@ func (h *Handler) mutate(w http.ResponseWriter, r *http.Request, raw []byte, eff h.writeExistingTask(w, op) return } - op, _ = h.Journal.Finish(id, journal.Failed, http.StatusBadGateway, "adapter returned a bounded non-secret failure") - fleetmetrics.Operations.WithLabelValues("failed").Inc() + op, _ = h.Journal.Finish(id, journal.Unknown, http.StatusBadGateway, "adapter failure does not establish whether the effect occurred") + fleetmetrics.Operations.WithLabelValues("unknown").Inc() + fleetmetrics.UnknownOperations.Inc() writeError(w, http.StatusBadGateway, "Fleet.1.0.BMCOperationFailed", "The allocated system did not complete the requested operation.") return } diff --git a/internal/redfish/handler_test.go b/internal/redfish/handler_test.go index b388780d..5eda9da2 100644 --- a/internal/redfish/handler_test.go +++ b/internal/redfish/handler_test.go @@ -107,6 +107,28 @@ func TestLostResponseIsUnknownAndNeverDuplicatesReset(t *testing.T) { if !strings.Contains(w2.Body.String(), "Unknown") { t.Fatalf("retry did not preserve unknown: %s", w2.Body.String()) } + conflicting := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"ForceOff"}`) + if conflicting.Code != http.StatusConflict || a.resets != 1 { + t.Fatal("a new power effect bypassed an unresolved prior effect") + } +} + +func TestQueuedMutationRechecksAuthority(t *testing.T) { + adapter := &fakeAdapter{} + handler := newHandler(t, adapter) + reads := 0 + handler.CurrentAuthority = func() Authority { + reads++ + authority := handler.Authority + if reads > 1 { + authority.FreshUntil = handler.Now().Add(-time.Second) + } + return authority + } + response := request(handler, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"On"}`) + if response.Code != http.StatusServiceUnavailable || adapter.resets != 0 { + t.Fatalf("stale queued mutation executed: %d, %d", response.Code, adapter.resets) + } } func TestTaskCollectionListsOnlyCurrentSession(t *testing.T) { From e93fffe25ccb86955e49fd0d11101dea63aed71a Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 18:28:30 -0600 Subject: [PATCH 21/24] fix(e2e): require real Redfish schema coverage and preserve failure evidence --- .github/workflows/test-e2e.yml | 15 ++- config/redfish/FleetProvisioning.v1_0_0.json | 5 +- .../machine-management-prototype.md | 98 +++++++++++++++++-- hack/e2e/common.sh | 41 ++++++++ hack/e2e/diagnostics.sh | 36 ++++--- hack/e2e/prepare-schemas.sh | 20 ++++ hack/e2e/test-common.sh | 41 ++++++++ hack/e2e/test.sh | 55 ++++++----- hack/e2e/up.sh | 1 + hack/e2e/validators.sh | 18 +++- internal/redfish/handler.go | 4 +- internal/redfish/handler_test.go | 52 ++++++++++ 12 files changed, 325 insertions(+), 61 deletions(-) create mode 100644 hack/e2e/common.sh create mode 100755 hack/e2e/prepare-schemas.sh create mode 100755 hack/e2e/test-common.sh diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index 5720856d..96e3f6c2 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -46,7 +46,9 @@ jobs: "${tools_bin}/helm" version "${tools_bin}/task" --version - name: Portable tests - run: task test + run: | + task test + bash hack/e2e/test-common.sh - name: Start virtual-BMC environment run: task e2e:up - name: End-to-end scenarios @@ -54,9 +56,11 @@ jobs: set -o pipefail task e2e:test 2>&1 | tee .e2e/e2e-test.log - name: Collect diagnostics + if: always() + run: task e2e:diagnostics || true + - name: Summarize failure if: failure() run: | - task e2e:diagnostics || true if [[ -f .e2e/e2e-test.log ]]; then tail -n 100 .e2e/e2e-test.log { @@ -69,11 +73,6 @@ jobs: message=$(tr '\n' ' ' <"${RUNNER_TEMP}/fleet-e2e-error.txt" | sed 's/%/%25/g; s/\r/%0D/g; s/\n/%0A/g') echo "::error title=E2E failure::${message}" fi - - name: Prepare non-secret evidence for upload - if: always() - run: | - docker exec fleet-e2e-virtual-bmc sh -c \ - 'find /evidence -maxdepth 1 -type f ! -name "*.key" -exec chmod 0644 {} +' || true - name: Upload diagnostics and validator reports if: always() uses: actions/upload-artifact@v4 @@ -82,8 +81,6 @@ jobs: path: | .e2e/diagnostics .e2e/validators - .e2e/virtual-bmc/evidence - !.e2e/virtual-bmc/evidence/*.key .e2e/*.log include-hidden-files: true if-no-files-found: ignore diff --git a/config/redfish/FleetProvisioning.v1_0_0.json b/config/redfish/FleetProvisioning.v1_0_0.json index 1d117ae3..6b61a1e5 100644 --- a/config/redfish/FleetProvisioning.v1_0_0.json +++ b/config/redfish/FleetProvisioning.v1_0_0.json @@ -17,7 +17,10 @@ "RedfishVersion": {"ReadRequirement": "Mandatory"}, "Systems": {"ReadRequirement": "Mandatory"}, "SessionService": {"ReadRequirement": "Mandatory"}, - "TaskService": {"ReadRequirement": "Mandatory"} + "Tasks": {"ReadRequirement": "Mandatory"}, + "Links": {"ReadRequirement": "Mandatory", "PropertyRequirements": { + "Sessions": {"ReadRequirement": "Mandatory"} + }} } }, "ComputerSystem": { diff --git a/docs/implementation/machine-management-prototype.md b/docs/implementation/machine-management-prototype.md index 74587f17..5d6ca8a3 100644 --- a/docs/implementation/machine-management-prototype.md +++ b/docs/implementation/machine-management-prototype.md @@ -185,6 +185,17 @@ Validator versions are `redfish` 3.4.2, `redfish-interop-validator` 3.0.3. Reports and PXE correlation evidence are under `.e2e/validators` and `.e2e/virtual-bmc/evidence`. +Setup downloads the DMTF Redfish-Publications 2026.2 CSDL snapshot at +`4f81814e399213c9055863ddaff42791c6b3706a`, verifies its archive SHA-256, and +extracts it into `.e2e/redfish-schemas`. The pin and checksum are in +[`prepare-schemas.sh`](../../hack/e2e/prepare-schemas.sh). Validation uses that +explicit cache with `--skipschema`; it does not download schemas while a +short-lived management session is active or change TLS trust for the loopback +service. Reports retain schema provenance and summary counts. A zero exit code +alone is insufficient: each validator must perform positive checks with zero +warnings and failures. Optional-property skips remain visible and are not +counted as successful checks. + ## Troubleshooting Run `task e2e:diagnostics` before teardown. It captures both clusters' resources, @@ -192,6 +203,23 @@ events and logs, Karmada clusters/Works/bindings and hub session state, protected/public session state, libvirt domain state/XML, virtual BMC logs, validator reports, acceleration selection, and PXE callbacks. +The harness writes timestamped successful scenario checkpoints to +`.e2e/checkpoints.log` and retains earlier proxy logs across session restarts. +On failure it attempts a bounded diagnostic snapshot before terminating proxies +or undoing injected outages; CI also collects diagnostics on successful runs. +Resource reads are separate so a CRD absent from one cluster does not hide that +cluster's other evidence. Workload logs target explicit deployments, and BMC +evidence is exported through Docker rather than assuming a remote bind mount is +visible on the client. Only named non-secret evidence files are exported. + +`FLEET_E2E_WAIT_SECONDS` bounds polling by elapsed seconds, not by the number of +potentially slow requests (an in-flight probe can still add its own timeout). +Proxy readiness fails when the process exits instead of waiting for the entire +polling budget. API errors do not count as confirmed session deletion. These +harness checks do not change the admitted one-minute connection window, session +expiry, or the gateway freshness fence. Portable helper regressions run with +`bash hack/e2e/test-common.sh` and in the Linux E2E workflow. + - A gateway stuck on `RelayUnavailable` usually indicates relay DNS/token or NetworkPolicy failure in the location cluster. - A missing cell projection: inspect the hub `PropagationPolicy`, the Work in @@ -297,11 +325,67 @@ files at the container writer and copies them through Docker, so verification does not depend on host/VM bind-mount visibility. It also waits for valid authority after the expensive emulated boot before attempting another mutation. -The full `task e2e:test` run did **not** pass in this environment: repeated sessions +The initial synchronized `task e2e:test` run did **not** pass: repeated sessions intermittently exhausted the one-minute connection window, and a post-PXE disk-boot -request failed before journal admission. The latter may reflect delayed freshness -renewal under emulation; the added wait has not been verified by a complete run. -Do not count the later validator, central-outage, release/recreation, expiry, or -lost-response scenarios as verified for this synchronization. The qualified Linux -CI run and the remaining production integration gates are still required. The -local test environment was torn down after collecting these results. +request failed before journal admission. Its cause was not established by that +run. At that point the added authority wait and later validator, central-outage, +release/recreation, expiry, and lost-response scenarios remained unverified. That +environment was torn down. The follow-up below records subsequent evidence +separately rather than attributing the earlier failures to emulation. + +### E2E reliability follow-up (2026-11-12) + +A fresh run from the synchronized prototype completed every lifecycle scenario, +including disk restoration, both outages, release/recreation, expiry, and the +lost-response duplicate-reset check. However, inspection invalidated its service +validator result: version 3.1.8 returned zero with **zero schema checks and ten +warnings** after the loopback-only CA bundle prevented the external DMTF schema +download. The narrow service also has no schema metadata endpoint, so no schema +source remained. That run is lifecycle evidence, not successful schema validation. + +The pinned offline schema cache and coverage guard now fail closed on that case. +Real schema validation then exposed two ServiceRoot errors: the task-service link +was named `TaskService` instead of the standard `Tasks`, and mandatory `Links` +was missing. The root now publishes `Tasks` and `Links.Sessions`; the declared +interoperability profile and a focused regression test agree with those fields. +The next run performed 91 schema checks but failed the zero-warning guard on +three deprecated task-message `Severity` fields. Messages now use the standard +`MessageSeverity`, with regression coverage preserving success, failure, pending, +and unknown task outcomes. This intermediate result is not a validator pass. +No provider route, admitted connection deadline, expiry, freshness fence, or +operation-authority behavior changes as part of these corrections. + +The final corrected pre-lifecycle run on November 12 (November 13 UTC) did **not** +complete. Setup, RBAC denial, generic DMTF client, Karmada projection, local login +revocation, route isolation, session limits, and a fresh PXE callback with libvirt +poweroff passed. At 00:21:08 UTC the boot proof completed; the subsequent bounded +authority wait failed. At 00:23:26 the member projection still had +`authorityFreshUntil=00:15:41Z`, while the hub had `00:17:43Z` and admitted expiry +was `00:28:47Z`. Karmada's API server had restarted twice and its controller manager +six times; previous manager logs show refused connections to the Karmada API, and +API-server logs show failed etcd connectivity. These observations establish stale +authority and control-plane interruption, not the underlying cause of those +restarts. No Hdd mutation or validators were reached in this run. The gateway did +not relax its freshness fence. Diagnostics now retain pod termination status and +previous workload logs as well as current logs for this failure class. + +Evidence is retained locally under +`/tmp/fleet-bmc-reliability-evidence/run-{1,2,3}`; the final setup/test logs are +`/tmp/fleet-bmc-reliability-{up,test}-3.log`. Only allowlisted diagnostics, +validator reports, and non-secret logs are archived, not kubeconfigs or proxy +credentials. Run 1 proves the baseline lifecycle scenarios but not schema +validation; run 2 proves schema traversal and identifies the deprecated fields; +run 3 does not establish that the final schema correction passes live validation. +Portable full Go tests, targeted race tests, shell helper regressions on macOS +and Linux, schema checksum rejection, shell syntax/ShellCheck, documentation +links, and whitespace checks pass. The original intermittent connection-window +failure remains unresolved; its cause was not reproduced or established here. + +These results are for the synchronized `bccf896` pre-lifecycle baseline, **not** +the later Coordinator custody integration. Combined validation must use the +explicit synthetic fixture, real Secret-backed lifecycle custody and release, +and the updated coordination CRD. Its lost-response/unknown-operation scenario +must be last or isolated: unknown effects legitimately prevent teardown and +allocation reuse, and cannot be cleared merely to continue the test. No native +Linux/CI full run, physical BMC, or OpenVPN qualification was obtained in this +environment. A complete warning-free validator and lifecycle run remains required. diff --git a/hack/e2e/common.sh b/hack/e2e/common.sh new file mode 100644 index 00000000..5d7e76a9 --- /dev/null +++ b/hack/e2e/common.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +fail() { echo "FAIL: $*" >&2; exit 1; } + +wait_for() { + local description=$1 command=$2 process_id=${3:-} + local deadline=$((SECONDS + ${FLEET_E2E_WAIT_SECONDS:-240})) + while (( SECONDS < deadline )); do + if [[ -n "${process_id}" ]] && ! kill -0 "${process_id}" 2>/dev/null; then + fail "${description}: process ${process_id} exited before readiness; inspect proxy logs" + fi + eval "${command}" && return 0 + sleep 1 + done + fail "timed out waiting for ${description}" +} + +run_timeout() { + local seconds=$1 + shift + if command -v timeout >/dev/null; then timeout "${seconds}" "$@"; return; fi + if command -v gtimeout >/dev/null; then gtimeout "${seconds}" "$@"; return; fi + perl -e '$seconds = shift; alarm $seconds; exec @ARGV' "${seconds}" "$@" +} + +checkpoint() { + printf '%s PASS: %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$*" | tee -a "${E2E_DIR}/checkpoints.log" +} + +sessions_absent() { + local kubeconfig=$1 namespace=$2 resource=$3 objects + objects=$(kubectl --request-timeout=10s --kubeconfig "${kubeconfig}" -n "${namespace}" get "${resource}" -o json) || return 1 + jq -e '(.items | type == "array") and (.items | length == 0)' <<<"${objects}" >/dev/null +} + +validator_coverage() { + awk -F '[:,]' ' + /^ - Pass:/ { resources++; passed += $2; warnings += $4; failed += $6 } + END { exit !(resources > 0 && passed > 0 && warnings == 0 && failed == 0) } + ' "$1" +} diff --git a/hack/e2e/diagnostics.sh b/hack/e2e/diagnostics.sh index 1b47aaa4..e4f7f224 100755 --- a/hack/e2e/diagnostics.sh +++ b/hack/e2e/diagnostics.sh @@ -4,33 +4,45 @@ ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) E2E_DIR="${ROOT_DIR}/.e2e" OUT="${E2E_DIR}/diagnostics/$(date -u +%Y%m%dT%H%M%SZ)" mkdir -p "${OUT}" +source "${ROOT_DIR}/hack/e2e/common.sh" for cluster in management location; do kubeconfig="${E2E_DIR}/${cluster}.kubeconfig" if [[ -f "${kubeconfig}" ]]; then - kubectl --kubeconfig "${kubeconfig}" get all,events -A -o wide >"${OUT}/${cluster}-resources.txt" 2>&1 || true - kubectl --kubeconfig "${kubeconfig}" get machines,machinecapacities,machineallocations,machinemanagementsessions,machinemanagementsessionbindings,projectedmachinemanagementsessions -A -o yaml >"${OUT}/${cluster}-fleet.yaml" 2>&1 || true - kubectl --kubeconfig "${kubeconfig}" logs --all-namespaces --all-containers --prefix --tail=-1 >"${OUT}/${cluster}-logs.txt" 2>&1 || true + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" get all,events -A -o wide >"${OUT}/${cluster}-resources.txt" 2>&1 || true + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" get pods -A -o json >"${OUT}/${cluster}-pods.json" 2>&1 || true + for resource in machines machinecapacities machineallocations machinemanagementsessions machinemanagementsessionbindings projectedmachinemanagementsessions; do + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" get "${resource}" -A -o yaml >"${OUT}/${cluster}-${resource}.yaml" 2>&1 || true + done + if [[ "${cluster}" == management ]]; then + workloads='fleet-system/fleet-controller karmada-system/karmada-controller-manager karmada-system/karmada-apiserver karmada-system/karmada-kube-controller-manager' + else + workloads='machine-access-system/fleet-gateway machine-access-system/fleet-relay' + fi + for workload in ${workloads}; do + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" -n "${workload%/*}" logs "deployment/${workload#*/}" \ + --all-containers --prefix --timestamps --tail=2000 >"${OUT}/${cluster}-${workload#*/}.log" 2>&1 || true + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" -n "${workload%/*}" logs "deployment/${workload#*/}" \ + --all-containers --previous --prefix --timestamps --tail=500 >"${OUT}/${cluster}-${workload#*/}-previous.log" 2>&1 || true + done if [[ "${cluster}" == location ]]; then - kubectl --kubeconfig "${kubeconfig}" -n machine-access-system exec deployment/fleet-gateway -- \ + run_timeout 15 kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" -n machine-access-system exec deployment/fleet-gateway -- \ sh -c 'for f in /var/lib/fleet/operations/*.json; do test -f "$f" && { echo "$f"; cat "$f"; }; done' \ >"${OUT}/operation-journal.jsonl" 2>&1 || true fi fi done if [[ -f "${E2E_DIR}/karmada.kubeconfig" ]]; then - kubectl --kubeconfig "${E2E_DIR}/karmada.kubeconfig" get clusters,works.work.karmada.io,resourcebindings.work.karmada.io -A -o yaml >"${OUT}/karmada-resources.yaml" 2>&1 || true - kubectl --kubeconfig "${E2E_DIR}/karmada.kubeconfig" get projectedmachinemanagementsessions,propagationpolicies -A -o yaml >"${OUT}/karmada-fleet.yaml" 2>&1 || true + kubectl --request-timeout=5s --kubeconfig "${E2E_DIR}/karmada.kubeconfig" get clusters,works.work.karmada.io,resourcebindings.work.karmada.io -A -o yaml >"${OUT}/karmada-resources.yaml" 2>&1 || true + kubectl --request-timeout=5s --kubeconfig "${E2E_DIR}/karmada.kubeconfig" get projectedmachinemanagementsessions,propagationpolicies -A -o yaml >"${OUT}/karmada-fleet.yaml" 2>&1 || true fi docker logs fleet-e2e-virtual-bmc >"${OUT}/virtual-bmc.log" 2>&1 || true docker exec fleet-e2e-virtual-bmc virsh list --all >"${OUT}/libvirt-domains.txt" 2>&1 || true docker exec fleet-e2e-virtual-bmc virsh dumpxml allocated >"${OUT}/allocated-domain.xml" 2>&1 || true if [[ -d "${E2E_DIR}/virtual-bmc/evidence" ]]; then - # libvirt creates console logs as root. Make only non-secret evidence - # readable, and never copy the optional OpenVPN key into CI diagnostics. - docker exec fleet-e2e-virtual-bmc sh -c \ - 'find /evidence -maxdepth 1 -type f ! -name "*.key" -exec chmod 0644 {} +' >/dev/null 2>&1 || true mkdir -p "${OUT}/evidence" - find "${E2E_DIR}/virtual-bmc/evidence" -maxdepth 1 -type f ! -name '*.key' \ - -exec cp {} "${OUT}/evidence/" \; + for evidence in acceleration.txt allocated-console.log pxe-callbacks.jsonl libvirtd.log virtlogd.log; do + docker cp "fleet-e2e-virtual-bmc:/evidence/${evidence}" "${OUT}/evidence/${evidence}" 2>/dev/null || true + done + cp "${E2E_DIR}/virtual-bmc/evidence/pxe-operation-correlation.json" "${OUT}/evidence/" 2>/dev/null || true fi echo "diagnostics: ${OUT}" diff --git a/hack/e2e/prepare-schemas.sh b/hack/e2e/prepare-schemas.sh new file mode 100755 index 00000000..261a9ba1 --- /dev/null +++ b/hack/e2e/prepare-schemas.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +SCHEMA_DIR="${ROOT_DIR}/.e2e/redfish-schemas" +REVISION=4f81814e399213c9055863ddaff42791c6b3706a +SHA256=48d1c587676f2b03d5589825653d8924d0fee67d963c5de5ba411e9a3b4b4068 +ARCHIVE="${ROOT_DIR}/.e2e/redfish-publications-${REVISION}.tar.gz" +mkdir -p "${SCHEMA_DIR}" +if [[ ! -f "${ARCHIVE}" ]]; then + curl --fail --silent --show-error --location --retry 3 --max-time 180 \ + "https://codeload.github.com/DMTF/Redfish-Publications/tar.gz/${REVISION}" -o "${ARCHIVE}.download" + mv "${ARCHIVE}.download" "${ARCHIVE}" +fi +actual=$(openssl dgst -sha256 "${ARCHIVE}" | awk '{print $NF}') +[[ "${actual}" == "${SHA256}" ]] || { echo "DMTF schema archive checksum mismatch: ${ARCHIVE}" >&2; exit 1; } +rm -rf "${SCHEMA_DIR}" +mkdir -p "${SCHEMA_DIR}" +tar -xzf "${ARCHIVE}" --strip-components=2 -C "${SCHEMA_DIR}" "Redfish-Publications-${REVISION}/csdl" +printf 'DMTF Redfish-Publications 2026.2\nrevision=%s\narchive_sha256=%s\n' "${REVISION}" "${SHA256}" >"${SCHEMA_DIR}/provenance.txt" +echo "Pinned DMTF CSDL schemas: ${SCHEMA_DIR}" diff --git a/hack/e2e/test-common.sh b/hack/e2e/test-common.sh new file mode 100755 index 00000000..8fe7ddea --- /dev/null +++ b/hack/e2e/test-common.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +source "${ROOT_DIR}/hack/e2e/common.sh" + +wait_for "immediate success" true +if (FLEET_E2E_WAIT_SECONDS=1 wait_for "bounded failure" false) 2>/dev/null; then + fail "failed predicate passed" +fi +if (wait_for "dead proxy with stale ready file" true 2147483647) 2>/dev/null; then + fail "dead proxy accepted stale readiness" +fi +kubectl() { return 1; } +if sessions_absent ignored default sessions; then + fail "API failure counted as confirmed deletion" +fi +kubectl() { printf '%s\n' '{"items":[{"metadata":{"name":"retained"}}]}'; } +if sessions_absent ignored default sessions; then + fail "existing session counted as deleted" +fi +kubectl() { printf '%s\n' '{"items":[]}'; } +sessions_absent ignored default sessions +kubectl() { printf '%s\n' '{}'; } +if sessions_absent ignored default sessions; then + fail "missing list evidence counted as confirmed deletion" +fi +run_timeout 2 bash -c 'exit 0' +if run_timeout 1 bash -c 'sleep 5'; then + fail "timeout failed to stop command" +fi +report=$(mktemp) +trap 'rm -f "${report}"' EXIT +for summary in '' ' - Pass: 0, Warn: 0, Fail: 0, Skip: 0' ' - Pass: 0, Warn: 1, Fail: 0, Skip: 0' ' - Pass: 1, Warn: 1, Fail: 0, Skip: 0' ' - Pass: 1, Warn: 0, Fail: 1, Skip: 0'; do + printf '%s\n' "${summary}" >"${report}" + if validator_coverage "${report}"; then + fail "incomplete validator coverage accepted: ${summary}" + fi +done +printf '%s\n' ' - Pass: 12, Warn: 0, Fail: 0, Skip: 35' >"${report}" +validator_coverage "${report}" +echo 'E2E harness helpers: PASS' diff --git a/hack/e2e/test.sh b/hack/e2e/test.sh index 33a484aa..ea58970d 100755 --- a/hack/e2e/test.sh +++ b/hack/e2e/test.sh @@ -9,6 +9,8 @@ LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" KARMADA_KUBECONFIG="${E2E_DIR}/karmada.kubeconfig" PATH="${E2E_DIR}/bin:${PATH}" export PATH +source "${ROOT_DIR}/hack/e2e/common.sh" +rm -f "${E2E_DIR}/checkpoints.log" "${E2E_DIR}/viewer-ready.json" "${E2E_DIR}/ready-2.json" for file in "${MGMT_KUBECONFIG}" "${LOCATION_KUBECONFIG}" "${KARMADA_KUBECONFIG}" "${E2E_DIR}/management-ca.crt"; do [[ -f "${file}" ]] || { echo "missing ${file}; run task e2e:up" >&2; exit 1; } @@ -27,30 +29,17 @@ proxy_pid= second_proxy_pid= management_paused=false location_paused=false +bmc_blocked=false cleanup() { + local result=$? + if [[ ${result} -ne 0 ]]; then run_timeout 90 "${ROOT_DIR}/hack/e2e/diagnostics.sh" || true; fi if [[ -n "${proxy_pid}" ]]; then kill -TERM "${proxy_pid}" 2>/dev/null || true; wait "${proxy_pid}" 2>/dev/null || true; fi if [[ -n "${second_proxy_pid}" ]]; then kill -TERM "${second_proxy_pid}" 2>/dev/null || true; wait "${second_proxy_pid}" 2>/dev/null || true; fi if [[ "${management_paused}" == true ]]; then docker unpause fleet-management-e2e-control-plane >/dev/null 2>&1 || true; fi if [[ "${location_paused}" == true ]]; then docker unpause fleet-location-e2e-control-plane >/dev/null 2>&1 || true; fi + if [[ "${bmc_blocked}" == true ]]; then docker exec fleet-e2e-virtual-bmc iptables -D INPUT -p tcp --dport 8000 -s 172.30.0.20 -j REJECT >/dev/null 2>&1 || true; fi } trap cleanup EXIT - -fail() { echo "FAIL: $*" >&2; exit 1; } -wait_for() { - local description=$1 command=$2 - # A freshly installed Karmada control plane can need more than 90 seconds to - # schedule the first Work and reflect member status on shared CI runners. - # Keep the bound explicit and configurable without weakening any assertion. - for _ in $(seq 1 "${FLEET_E2E_WAIT_SECONDS:-240}"); do eval "${command}" && return 0; sleep 1; done - fail "timed out waiting for ${description}" -} -run_timeout() { - local seconds=$1 - shift - if command -v timeout >/dev/null; then timeout "${seconds}" "$@"; return; fi - if command -v gtimeout >/dev/null; then gtimeout "${seconds}" "$@"; return; fi - perl -e '$seconds = shift; alarm $seconds; exec @ARGV' "${seconds}" "$@" -} file_mode() { if stat -c %a "$1" >/dev/null 2>&1; then stat -c %a "$1"; else stat -f %Lp "$1"; fi } @@ -70,6 +59,9 @@ set -e start_proxy() { local ttl=${1:-15m} + local attempt + attempt=$(date -u '+%Y%m%dT%H%M%SZ') + [[ ! -f "${E2E_DIR}/proxy.log" ]] || cp "${E2E_DIR}/proxy.log" "${E2E_DIR}/proxy-${attempt}.log" rm -f "${E2E_DIR}/ready.json" "${E2E_DIR}/credentials.json" "${E2E_DIR}/ca.pem" DATUM_TOKEN=must-not-be-used HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-01 -- \ --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" \ @@ -77,7 +69,7 @@ start_proxy() { --ready-file "${E2E_DIR}/ready.json" --credential-file "${E2E_DIR}/credentials.json" \ --ca-file "${E2E_DIR}/ca.pem" >"${E2E_DIR}/proxy.log" 2>&1 & proxy_pid=$! - wait_for "datumctl fleet proxy readiness" "jq -e '.ready == true' '${E2E_DIR}/ready.json' >/dev/null 2>&1" + wait_for "datumctl fleet proxy readiness" "jq -e '.ready == true' '${E2E_DIR}/ready.json' >/dev/null 2>&1" "${proxy_pid}" endpoint=$(jq -r .endpoint "${E2E_DIR}/credentials.json") username=$(jq -r .username "${E2E_DIR}/credentials.json") password=$(jq -r .password "${E2E_DIR}/credentials.json") @@ -88,7 +80,7 @@ stop_proxy() { kill -TERM "${proxy_pid}" 2>/dev/null || true wait "${proxy_pid}" 2>/dev/null || true proxy_pid= - wait_for "session deletion" "! kubectl --kubeconfig '${MGMT_KUBECONFIG}' -n default get machinemanagementsessions.metal.datumapis.com -o name 2>/dev/null | grep -q ." + wait_for "session deletion" "sessions_absent '${MGMT_KUBECONFIG}' default machinemanagementsessions.metal.datumapis.com" } # Nested x86 QEMU on non-x86 developer hosts can take tens of seconds to apply @@ -98,6 +90,7 @@ stop_proxy() { rf() { curl --silent --show-error --max-time 90 --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" "$@"; } rf_status() { curl --silent --max-time 90 --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" "$@"; } +checkpoint "Machine reader denied session creation" start_proxy [[ $(file_mode "${E2E_DIR}/credentials.json") == 600 ]] || fail "credential file is not 0600" [[ $(file_mode "${E2E_DIR}/ca.pem") == 600 ]] || fail "CA file is not 0600" @@ -136,6 +129,7 @@ else -v "${E2E_DIR}:/state:ro" -v "${TEST_DIR}:/work:ro" fleet-redfish-tools:e2e \ "python /work/generic-client.py" fi +checkpoint "generic DMTF client and Karmada projection" # Session-local login credentials are revocable and are not BMC credentials. login_headers="${E2E_DIR}/login.headers" @@ -224,7 +218,7 @@ HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-02 --credential-file "${E2E_DIR}/credentials-2.json" --ca-file "${E2E_DIR}/ca-2.pem" \ >"${E2E_DIR}/proxy-2.log" 2>&1 & second_proxy_pid=$! -wait_for "second project session" "jq -e '.ready == true' '${E2E_DIR}/ready-2.json' >/dev/null 2>&1" +wait_for "second project session" "jq -e '.ready == true' '${E2E_DIR}/ready-2.json' >/dev/null 2>&1" "${second_proxy_pid}" set +e run_timeout 20 env HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-03 -- \ --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" >"${E2E_DIR}/project-limit.log" 2>&1 @@ -235,6 +229,8 @@ grep -q SessionLimitExceeded "${E2E_DIR}/project-limit.log" || fail "project lim kill -TERM "${second_proxy_pid}"; wait "${second_proxy_pid}" || true; second_proxy_pid= kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system patch machineallocation db-02-allocation --subresource=status --type=merge -p '{"status":{"phase":"Released"}}' +checkpoint "local login revocation, route isolation, and session limits" + # Real sushy -> libvirt PXE effect, correlated by the allocated VM MAC callback. pxe_body='{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Pxe"}}' pxe_task=$(rf -X PATCH -H 'Content-Type: application/json' -d "${pxe_body}" "${root}/redfish/v1/Systems/allocated") @@ -256,10 +252,8 @@ wait_for "PXE fixture poweroff in libvirt" "[[ \$(docker exec fleet-e2e-virtual- jq -n --arg operationID "$(jq -r .Id <<<"${power_task}")" --arg mac 52:54:00:aa:00:01 \ --argjson callback "$(grep '/pxe/52-54-00-aa-00-01' "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" | tail -1)" \ '{operationID:$operationID,vmMAC:$mac,callback:$callback}' >"${E2E_DIR}/virtual-bmc/evidence/pxe-operation-correlation.json" +checkpoint "fresh allocated PXE callback and libvirt poweroff" -# Software-emulated guest boot can starve the control planes long enough to -# exceed the deliberately short test freshness window. Require renewed authority -# before admitting the next effect; do not loosen the gateway's fail-closed gate. wait_for "authority after PXE boot" "[[ \$(rf_status '${root}/redfish/v1/Systems/allocated') == 200 ]]" hdd_body='{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Hdd"}}' @@ -271,9 +265,11 @@ grep -A6 "" <<<"${domain_xml}" | grep -q "" <<<"${domain_xml}" | grep -q '/dev/null wait_for "new allocation domain power-on" "[[ \$(docker exec fleet-e2e-virtual-bmc virsh domstate unallocated | tr -d '\\r') == running ]]" +checkpoint "release fence and same-name Machine recreation" # Fault-inject a lost BMC response. Retrying the identical admitted operation # must recover its Unknown task without sending a second physical reset. stop_proxy wait_for "prior location projection teardown" \ - "! kubectl --kubeconfig '${LOCATION_KUBECONFIG}' -n machine-access-system get projectedmachinemanagementsessions.coordination.fleet.datumapis.com -o name 2>/dev/null | grep -q ." + "sessions_absent '${LOCATION_KUBECONFIG}' machine-access-system projectedmachinemanagementsessions.coordination.fleet.datumapis.com" kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch deployment fleet-gateway --type=json \ -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--fault-drop-reset-response-once"}]' kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s @@ -345,6 +343,7 @@ lost_second=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" " [[ $(jq -r .Id <<<"${lost_first}") == $(jq -r .Id <<<"${lost_second}") ]] || fail "retry created a second operation" reset_after=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) [[ $((reset_after - reset_before)) -eq 1 ]] || fail "lost-response retry sent $((reset_after - reset_before)) physical resets" +checkpoint "lost response remains Unknown and retry sends no second reset" # The gateway schedules the admitted expiry and closes the stream rather than # treating a still-live client or relay connection as authority. @@ -352,17 +351,20 @@ stop_proxy start_proxy 1m sleep 65 [[ $(rf_status "${root}/redfish/v1/Systems/allocated") != 200 ]] || fail "expired session retained Redfish access" +checkpoint "admitted expiry closes access" stop_proxy start_proxy # Stop only the private sushy route. The customer receives a bounded error that # does not disclose the private endpoint or credential. -gateway_pod=$(kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system get pod -l app.kubernetes.io/name=fleet-gateway -o jsonpath='{.items[0].metadata.name}') docker exec fleet-e2e-virtual-bmc iptables -I INPUT 1 -p tcp --dport 8000 -s 172.30.0.20 -j REJECT +bmc_blocked=true bmc_error=$(rf "${root}/redfish/v1/Systems/allocated") [[ $(jq -r .error.code <<<"${bmc_error}") == Fleet.1.0.BMCUnavailable ]] || fail "BMC failure was not actionable" ! grep -Eq '172\.30\.0\.10|fleet-gateway|synthetic-e2e-only' <<<"${bmc_error}" || fail "BMC failure disclosed private data" -docker exec fleet-e2e-virtual-bmc iptables -D INPUT 1 +docker exec fleet-e2e-virtual-bmc iptables -D INPUT -p tcp --dport 8000 -s 172.30.0.20 -j REJECT +bmc_blocked=false +checkpoint "bounded private BMC outage without credential disclosure" # If the location cannot acknowledge explicit deletion, the public object may # finish deleting only with a protected Unknown teardown outcome. @@ -376,4 +378,5 @@ cleanup_status=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get m docker unpause fleet-location-e2e-control-plane >/dev/null location_paused=false [[ ! -e "${E2E_DIR}/credentials.json" && ! -e "${E2E_DIR}/ca.pem" ]] || fail "proxy secret files survived shutdown" +checkpoint "unconfirmed location teardown remains Unknown; local secrets removed" echo "machine-management end-to-end scenarios: PASS" diff --git a/hack/e2e/up.sh b/hack/e2e/up.sh index ab689899..2ec38243 100755 --- a/hack/e2e/up.sh +++ b/hack/e2e/up.sh @@ -18,6 +18,7 @@ if [[ $(uname -s) != Linux ]]; then export FLEET_FORCE_QEMU=${FLEET_FORCE_QEMU:-1} fi mkdir -p "${E2E_DIR}/bin" "${FLEET_E2E_STATE}/evidence" "${FLEET_E2E_STATE}/images" +bash "${ROOT_DIR}/hack/e2e/prepare-schemas.sh" find "${FLEET_E2E_STATE}/evidence" -maxdepth 1 -type f -delete docker compose -p fleet-bmc-e2e -f "${TEST_DIR}/compose.yaml" up -d --build diff --git a/hack/e2e/validators.sh b/hack/e2e/validators.sh index 66b7495d..784773d3 100755 --- a/hack/e2e/validators.sh +++ b/hack/e2e/validators.sh @@ -5,8 +5,14 @@ ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) E2E_DIR="${ROOT_DIR}/.e2e" CREDENTIAL_FILE=${FLEET_CREDENTIAL_FILE:-${E2E_DIR}/credentials.json} REPORT_DIR="${E2E_DIR}/validators" +SCHEMA_DIR="${E2E_DIR}/redfish-schemas" +source "${ROOT_DIR}/hack/e2e/common.sh" [[ -f "${CREDENTIAL_FILE}" ]] || { echo "missing proxy credential file: ${CREDENTIAL_FILE}" >&2; exit 1; } +for schema in ServiceRoot SessionService Session SessionCollection ComputerSystem ComputerSystemCollection TaskService Task TaskCollection Resource; do + [[ -s "${SCHEMA_DIR}/${schema}_v1.xml" || -s "${SCHEMA_DIR}/${schema}.xml" ]] || fail "missing pinned ${schema} schema; run task e2e:up" +done mkdir -p "${REPORT_DIR}/service" "${REPORT_DIR}/interop" +cp "${SCHEMA_DIR}/provenance.txt" "${REPORT_DIR}/schema-provenance.txt" endpoint=$(jq -r .endpoint "${CREDENTIAL_FILE}") username=$(jq -r .username "${CREDENTIAL_FILE}") @@ -17,23 +23,27 @@ if [[ $(uname -s) == Darwin ]]; then validator_bin=${FLEET_VALIDATOR_BIN:-/private/tmp/fleet-validator-venv/bin} REQUESTS_CA_BUNDLE="${ca_bundle}" "${validator_bin}/rf_service_validator" \ --rhost "${endpoint%/redfish/v1/}" --user "${username}" --password "${password}" \ - --authtype Session --nooemcheck --logdir "${REPORT_DIR}/service" + --authtype Session --nooemcheck --logdir "${REPORT_DIR}/service" \ + --skipschema --schema_directory "${SCHEMA_DIR}" 2>&1 | tee "${REPORT_DIR}/service-summary.log" + validator_coverage "${REPORT_DIR}/service-summary.log" || fail "service validator did not complete warning-free schema validation" REQUESTS_CA_BUNDLE="${ca_bundle}" "${validator_bin}/rf_interop_validator" \ --rhost "${endpoint%/redfish/v1/}" --user "${username}" --password "${password}" \ --authtype Session --nooemcheck --logdir "${REPORT_DIR}/interop" \ - "${ROOT_DIR}/config/redfish/FleetProvisioning.v1_0_0.json" + "${ROOT_DIR}/config/redfish/FleetProvisioning.v1_0_0.json" 2>&1 | tee "${REPORT_DIR}/interop-summary.log" else docker run --rm --network host --user "$(id -u):$(id -g)" --workdir /state/validators/service \ -e REQUESTS_CA_BUNDLE=/state/ca.pem \ -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ fleet-redfish-tools:e2e \ - "rf_service_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/service" + "rf_service_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/service --skipschema --schema_directory /state/redfish-schemas" 2>&1 | tee "${REPORT_DIR}/service-summary.log" + validator_coverage "${REPORT_DIR}/service-summary.log" || fail "service validator did not complete warning-free schema validation" docker run --rm --network host --user "$(id -u):$(id -g)" --workdir /state/validators/interop \ -e REQUESTS_CA_BUNDLE=/state/ca.pem \ -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ fleet-redfish-tools:e2e \ - "rf_interop_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/interop /work/config/redfish/FleetProvisioning.v1_0_0.json" + "rf_interop_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/interop /work/config/redfish/FleetProvisioning.v1_0_0.json" 2>&1 | tee "${REPORT_DIR}/interop-summary.log" fi +validator_coverage "${REPORT_DIR}/interop-summary.log" || fail "interop validator did not complete warning-free profile validation" echo "DMTF validator reports: ${REPORT_DIR}" diff --git a/internal/redfish/handler.go b/internal/redfish/handler.go index 9c04cd4a..a100d0d0 100644 --- a/internal/redfish/handler.go +++ b/internal/redfish/handler.go @@ -110,7 +110,7 @@ func (h *Handler) checkRequest(r *http.Request) error { } func (h *Handler) serviceRoot(w http.ResponseWriter) { - writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ServiceRoot.v1_15_0.ServiceRoot", "@odata.id": "/redfish/v1/", "Id": "RootService", "Name": "Fleet Virtual Redfish Service", "RedfishVersion": "1.18.0", "UUID": virtualUUID(h.authority().SessionName), "Systems": odata("/redfish/v1/Systems"), "SessionService": odata("/redfish/v1/SessionService"), "TaskService": odata("/redfish/v1/TaskService")}) + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ServiceRoot.v1_15_0.ServiceRoot", "@odata.id": "/redfish/v1/", "Id": "RootService", "Name": "Fleet Virtual Redfish Service", "RedfishVersion": "1.18.0", "UUID": virtualUUID(h.authority().SessionName), "Systems": odata("/redfish/v1/Systems"), "SessionService": odata("/redfish/v1/SessionService"), "Tasks": odata("/redfish/v1/TaskService"), "Links": map[string]any{"Sessions": odata("/redfish/v1/SessionService/Sessions")}}) } func virtualUUID(sessionName string) string { @@ -314,7 +314,7 @@ func taskBody(op journal.Operation) map[string]any { state = "Exception" status = "Warning" } - return map[string]any{"@odata.type": "#Task.v1_7_4.Task", "@odata.id": "/redfish/v1/TaskService/Tasks/" + op.ID, "Id": op.ID, "Name": "Fleet machine operation", "TaskState": state, "TaskStatus": status, "Messages": []any{map[string]any{"MessageId": "Fleet.1.0." + string(op.Outcome), "Message": op.Evidence, "Severity": status, "Resolution": "Inspect or recover the existing operation; do not resubmit an unknown effect."}}} + return map[string]any{"@odata.type": "#Task.v1_7_4.Task", "@odata.id": "/redfish/v1/TaskService/Tasks/" + op.ID, "Id": op.ID, "Name": "Fleet machine operation", "TaskState": state, "TaskStatus": status, "Messages": []any{map[string]any{"MessageId": "Fleet.1.0." + string(op.Outcome), "Message": op.Evidence, "MessageSeverity": status, "Resolution": "Inspect or recover the existing operation; do not resubmit an unknown effect."}}} } func odata(path string) map[string]string { return map[string]string{"@odata.id": path} } func setODataHeaders(w http.ResponseWriter) { diff --git a/internal/redfish/handler_test.go b/internal/redfish/handler_test.go index 5eda9da2..888137b8 100644 --- a/internal/redfish/handler_test.go +++ b/internal/redfish/handler_test.go @@ -92,6 +92,31 @@ func TestUnsupportedMutationsRejected(t *testing.T) { } } +func TestServiceRootUsesStandardTaskAndSessionLinks(t *testing.T) { + handler := newHandler(t, &fakeAdapter{}) + response := request(handler, http.MethodGet, "/redfish/v1/", "") + if response.Code != http.StatusOK { + t.Fatalf("service root: %d %s", response.Code, response.Body.String()) + } + var root struct { + Tasks map[string]string + Links map[string]map[string]string + TaskService json.RawMessage + } + if err := json.Unmarshal(response.Body.Bytes(), &root); err != nil { + t.Fatal(err) + } + if root.TaskService != nil { + t.Fatal("ServiceRoot exposed the nonstandard TaskService property") + } + if root.Tasks["@odata.id"] != "/redfish/v1/TaskService" { + t.Fatalf("incorrect task link: %v", root.Tasks) + } + if root.Links["Sessions"]["@odata.id"] != "/redfish/v1/SessionService/Sessions" { + t.Fatalf("incorrect session link: %v", root.Links) + } +} + func TestLostResponseIsUnknownAndNeverDuplicatesReset(t *testing.T) { a := &fakeAdapter{lost: true} h := newHandler(t, a) @@ -167,3 +192,30 @@ func TestAdapterResponseLostSentinel(t *testing.T) { t.Fatal("sentinel") } } + +func TestTaskMessageSeverityPreservesOperationOutcome(t *testing.T) { + for _, test := range []struct { + outcome journal.Outcome + state string + status string + }{ + {journal.Pending, "Running", "OK"}, + {journal.Succeeded, "Completed", "OK"}, + {journal.Failed, "Exception", "Critical"}, + {journal.Unknown, "Exception", "Warning"}, + } { + t.Run(string(test.outcome), func(t *testing.T) { + body := taskBody(journal.Operation{ID: "operation", Outcome: test.outcome, Evidence: "retained evidence"}) + if body["TaskState"] != test.state || body["TaskStatus"] != test.status { + t.Fatalf("operation outcome changed: %v", body) + } + message := body["Messages"].([]any)[0].(map[string]any) + if message["MessageSeverity"] != test.status || message["MessageId"] != "Fleet.1.0."+string(test.outcome) { + t.Fatalf("incorrect operation message: %v", message) + } + if _, present := message["Severity"]; present { + t.Fatal("deprecated message Severity remains exposed") + } + }) + } +} From a428b6763a39385551e4e6b8bc0fd2915a974ddf Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 18:29:41 -0600 Subject: [PATCH 22/24] Wire synthetic BMC sessions through lifecycle custody --- README.md | 3 + cmd/fleet-controller/main.go | 29 ++- cmd/fleet-controller/main_test.go | 38 ++++ cmd/fleet-session-fixture/main.go | 112 +++++++++++ config/manager/controller.yaml | 2 + config/rbac/controller.yaml | 29 ++- docs/implementation/secure-bmc-lifecycle.md | 15 +- docs/implementation/synthetic-bmc-fixture.md | 167 ++++++++++++++++ internal/controller/management_lifecycle.go | 3 + internal/staging/sessionfixture/authority.go | 117 +++++++++++ internal/staging/sessionfixture/executor.go | 26 +++ internal/staging/sessionfixture/fixture.go | 99 ++++++++++ .../staging/sessionfixture/fixture_test.go | 181 ++++++++++++++++++ 13 files changed, 811 insertions(+), 10 deletions(-) create mode 100644 cmd/fleet-controller/main_test.go create mode 100644 cmd/fleet-session-fixture/main.go create mode 100644 docs/implementation/synthetic-bmc-fixture.md create mode 100644 internal/staging/sessionfixture/authority.go create mode 100644 internal/staging/sessionfixture/executor.go create mode 100644 internal/staging/sessionfixture/fixture.go create mode 100644 internal/staging/sessionfixture/fixture_test.go diff --git a/README.md b/README.md index 87cea7fa..e9c004e3 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,9 @@ service-owned Secret custody and serializes sessions against installation and release, rather than trusting pre-bound allocation CRDs. Production access authorization, trusted observation resolution, and executor fencing remain unwired; the session controller defaults to unready and denies new sessions. +An explicit [synthetic fixture mode](docs/implementation/synthetic-bmc-fixture.md) +wires the runnable prototype to real Coordinator custody without enabling a +production fallback. See the [implemented lifecycle contract](docs/implementation/secure-bmc-lifecycle.md). ## Scope diff --git a/cmd/fleet-controller/main.go b/cmd/fleet-controller/main.go index 0c05e014..2e8392a9 100644 --- a/cmd/fleet-controller/main.go +++ b/cmd/fleet-controller/main.go @@ -23,6 +23,7 @@ import ( fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/staging/sessionfixture" ) func main() { @@ -33,6 +34,8 @@ func main() { authorityFreshness := flag.Duration("authority-freshness", 2*time.Minute, "maximum cached allocation-authority lifetime at a location") perClaimLimit := flag.Int("per-claim-session-limit", 1, "maximum concurrent sessions for one claim") perProjectLimit := flag.Int("per-project-session-limit", 5, "maximum concurrent sessions for one consumer project") + lifecycleMode := flag.String("lifecycle-mode", "production", "production (unready) or synthetic (test-only private fixture grants)") + privateNamespace := flag.String("private-namespace", controller.SystemNamespace, "private Coordinator Secret namespace") flag.Parse() if *federationKubeconfig == "" { slog.Error("--federation-kubeconfig is required") @@ -50,15 +53,35 @@ func main() { wh := webhook.NewServer(webhook.Options{CertDir: *webhookCertDir}) mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{Scheme: scheme, Metrics: metricsserver.Options{BindAddress: *metrics}, HealthProbeBindAddress: *probe, WebhookServer: wh}) must(err) + privateClient, err := client.New(mgr.GetConfig(), client.Options{Scheme: scheme}) + must(err) + lifecycle, readiness, err := lifecycleWiring(*lifecycleMode, privateClient, *privateNamespace) + must(err) mgr.GetWebhookServer().Register("/mutate-metal-datumapis-com-v1alpha1-machinemanagementsession", &admission.Webhook{Handler: controller.SessionAdmission{}}) - must((&controller.SessionReconciler{PerClaimLimit: *perClaimLimit, PerProjectLimit: *perProjectLimit}).SetupWithManager(mgr)) - must((&controller.ProjectionReconciler{FederationClient: federationClient, Freshness: *authorityFreshness}).SetupWithManager(mgr)) + must((&controller.SessionReconciler{Lifecycle: lifecycle, PerClaimLimit: *perClaimLimit, PerProjectLimit: *perProjectLimit}).SetupWithManager(mgr)) + must((&controller.ProjectionReconciler{Lifecycle: lifecycle, FederationClient: federationClient, Freshness: *authorityFreshness}).SetupWithManager(mgr)) must(mgr.AddHealthzCheck("healthz", healthz.Ping)) - must(mgr.AddReadyzCheck("lifecycle-authority", func(*http.Request) error { return controller.ErrUnsupported })) + must(mgr.AddReadyzCheck("lifecycle-authority", readiness)) slog.Info("starting Fleet session controllers") must(mgr.Start(ctrl.SetupSignalHandler())) } +func lifecycleWiring(mode string, kube client.Client, namespace string) (controller.SessionLifecycle, healthz.Checker, error) { + switch mode { + case "production": + return nil, func(*http.Request) error { return controller.ErrUnsupported }, nil + case "synthetic": + authority, err := sessionfixture.NewAuthority(kube, namespace) + if err != nil { + return nil, nil, err + } + slog.Warn("SYNTHETIC TEST ONLY: fixture grants replace production authorization and provider observations", "privateNamespace", namespace) + return authority, healthz.Ping, nil + default: + return nil, nil, controller.ErrUnsupported + } +} + func must(err error) { if err != nil { slog.Error("fatal", "error", err) diff --git a/cmd/fleet-controller/main_test.go b/cmd/fleet-controller/main_test.go new file mode 100644 index 00000000..2a3b8054 --- /dev/null +++ b/cmd/fleet-controller/main_test.go @@ -0,0 +1,38 @@ +package main + +import ( + "errors" + "testing" + + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + "go.datum.net/fleet/internal/controller" +) + +func TestLifecycleModeIsExplicitAndFailClosed(t *testing.T) { + scheme := runtime.NewScheme() + if err := clientgoscheme.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + kube := fake.NewClientBuilder().WithScheme(scheme).Build() + authority, ready, err := lifecycleWiring("production", kube, "private") + if err != nil || authority != nil || !errors.Is(ready(nil), controller.ErrUnsupported) { + t.Fatalf("production did not fail closed: %v %v", authority, err) + } + if _, _, err := lifecycleWiring("typo", kube, "private"); err == nil { + t.Fatal("unrecognized mode was accepted") + } + authority, ready, err = lifecycleWiring("synthetic", kube, "private") + if err != nil || ready(nil) != nil { + t.Fatalf("synthetic wiring: %v", err) + } + concrete, ok := authority.(*controller.LifecycleSessionAuthority) + if !ok || concrete.Coordinator == nil || concrete.Resolver == nil { + t.Fatalf("missing real custody or resolver: %T", authority) + } + if _, _, err := lifecycleWiring("synthetic", kube, ""); err == nil { + t.Fatal("accepted missing private namespace") + } +} diff --git a/cmd/fleet-session-fixture/main.go b/cmd/fleet-session-fixture/main.go new file mode 100644 index 00000000..f80f96e5 --- /dev/null +++ b/cmd/fleet-session-fixture/main.go @@ -0,0 +1,112 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "syscall" + "time" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/simulator" + "go.datum.net/fleet/internal/staging/sessionfixture" +) + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run() error { + synthetic := flag.Bool("synthetic", false, "required acknowledgment: test-only admission, observations and cleanup; never use with real assets") + kubeconfig := flag.String("kubeconfig", "", "management kubeconfig") + phase := flag.String("phase", "allocate", "allocate or release") + namespace := flag.String("namespace", "default", "Machine namespace") + machine := flag.String("machine", "db-01", "Machine name") + uid := flag.String("machine-uid", "", "exact retained Machine UID, required for release") + capacityNamespace := flag.String("capacity-namespace", "fleet-provider", "MachineCapacity namespace") + capacity := flag.String("capacity", "", "MachineCapacity name, required for allocation") + principal := flag.String("principal", "", "exact authenticated username authorized by this synthetic fixture") + member := flag.String("member-cluster", "", "synthetic member route") + privateNamespace := flag.String("private-namespace", "fleet-system", "Coordinator and immutable synthetic grant Secret namespace") + state := flag.String("state", "", "persistent synthetic executor file; retain across all release retries and reuse") + flag.Parse() + if !*synthetic || *kubeconfig == "" || *state == "" || (*phase != "allocate" && *phase != "release") { + return errors.New("--synthetic, --kubeconfig, --state and --phase=allocate|release are required") + } + if *phase == "allocate" && (*capacity == "" || *principal == "" || *member == "") { + return errors.New("allocation requires --capacity, --principal and --member-cluster") + } + if *phase == "release" && *uid == "" { + return errors.New("release requires --machine-uid (never inferred from a possibly recreated name)") + } + if err := os.MkdirAll(filepath.Dir(*state), 0700); err != nil { + return err + } + lock, err := os.OpenFile(*state+".lock", os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return err + } + defer lock.Close() + if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + return fmt.Errorf("synthetic executor is already in use: %w", err) + } + defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) + store, err := simulator.Open(*state) + if err != nil { + return err + } + scheme := runtime.NewScheme() + if err := clientgoscheme.AddToScheme(scheme); err != nil { + return err + } + if err := fleetv1.AddToScheme(scheme); err != nil { + return err + } + config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) + if err != nil { + return err + } + kube, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + return err + } + coordinator, err := controller.NewCoordinator(kube, *privateNamespace, sessionfixture.StoreExecutor{Store: store}, controller.LocalDigestImageResolver{}, nil, time.Minute) + if err != nil { + return err + } + fixture := sessionfixture.Fixture{Client: kube, Coordinator: coordinator, PrivateNamespace: *privateNamespace} + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + key := client.ObjectKey{Namespace: *namespace, Name: *machine} + var result any + if *phase == "allocate" { + asset, allocateErr := fixture.Allocate(ctx, key, client.ObjectKey{Namespace: *capacityNamespace, Name: *capacity}, *principal, *member) + err = allocateErr + if asset != nil { + result = struct { + MachineUID types.UID `json:"machineUID"` + Epoch int64 `json:"epoch"` + }{asset.ClaimUID, asset.Epoch} + } + } else { + result, err = fixture.Release(ctx, key, types.UID(*uid)) + } + if encodeErr := json.NewEncoder(os.Stdout).Encode(result); encodeErr != nil { + return encodeErr + } + return err +} diff --git a/config/manager/controller.yaml b/config/manager/controller.yaml index d81850ab..9ddd431b 100644 --- a/config/manager/controller.yaml +++ b/config/manager/controller.yaml @@ -22,6 +22,8 @@ spec: image: fleet-controller:e2e imagePullPolicy: IfNotPresent args: + - --lifecycle-mode=synthetic + - --private-namespace=fleet-system - --federation-kubeconfig=/var/run/fleet-federation/kubeconfig - --webhook-cert-dir=/var/run/fleet-webhook # Test-only short window; the binary's product-oriented default is 2m. diff --git a/config/rbac/controller.yaml b/config/rbac/controller.yaml index e22f5b3d..f8783b27 100644 --- a/config/rbac/controller.yaml +++ b/config/rbac/controller.yaml @@ -10,7 +10,7 @@ metadata: name: fleet-session-controller rules: - apiGroups: [metal.datumapis.com] - resources: [machinemanagementsessions, machines, machinecapacities, machineallocations] + resources: [machinemanagementsessions, machines, machinecapacities] verbs: [get, list, watch] # The controller writes only metadata finalizers on the public object. CEL # validation keeps the customer-authored spec immutable. @@ -20,6 +20,9 @@ rules: - apiGroups: [metal.datumapis.com] resources: [machinemanagementsessions/status] verbs: [get, update, patch] + - apiGroups: [""] + resources: [namespaces] + verbs: [get] - apiGroups: [metal.datumapis.com] resources: [machinemanagementsessions/finalizers] verbs: [update, patch] @@ -31,6 +34,30 @@ rules: verbs: [get, update, patch] --- apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-session-custody + namespace: fleet-system +rules: + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, update] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-session-custody + namespace: fleet-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-session-custody +subjects: + - kind: ServiceAccount + name: fleet-controller + namespace: fleet-system +--- +apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: fleet-session-controller diff --git a/docs/implementation/secure-bmc-lifecycle.md b/docs/implementation/secure-bmc-lifecycle.md index 90b4cc05..544e5c05 100644 --- a/docs/implementation/secure-bmc-lifecycle.md +++ b/docs/implementation/secure-bmc-lifecycle.md @@ -26,8 +26,10 @@ Missing integrations fail closed. Supply an authoritative private-record client with resource-version CAS, not a public API cache interpreted as authority. Inject the same lifecycle authority into `SessionReconciler.Lifecycle` and `ProjectionReconciler.Lifecycle`. The current -`fleet-controller` executable supplies neither a production resolver nor a -synthetic fallback; its readiness check reports unavailable. The manager and +`fleet-controller` executable defaults to production-unavailable readiness. An +explicit [synthetic fixture mode](synthetic-bmc-fixture.md) injects private grants +and real Coordinator custody for test-only runnable integration; it is not a +production fallback. The manager and staging handler remain allocation owners, and their shared Coordinator release path includes this barrier. The projector checks custody on its existing bounded refresh cadence, without allocation CRD watches or cluster-wide Secret access. @@ -109,7 +111,8 @@ arbitrary Redfish response. Stable protected journal storage is required. Unknow operations still need qualified recovery evidence; this change does not auto-clear tasks or redesign quota, nonce persistence, or general idempotency. -Pre-bound-CRD E2E fixtures are not an integration source. The separate E2E owner -must explicitly wire a synthetic resolver backed by real lifecycle custody for -test use without enabling a production fallback. No Kind/Docker environment or -`hack/e2e` files were changed or run for this implementation. +Pre-bound-CRD E2E fixtures are not an integration source. The +[synthetic fixture executable](synthetic-bmc-fixture.md#exact-harness-recipe) +provides real allocation/release transitions and explicit resolver wiring. The +separate E2E owner integrates those commands into the harness. No Kind/Docker +environment or `hack/e2e` files were changed or run for this integration repair. diff --git a/docs/implementation/synthetic-bmc-fixture.md b/docs/implementation/synthetic-bmc-fixture.md new file mode 100644 index 00000000..f755d54e --- /dev/null +++ b/docs/implementation/synthetic-bmc-fixture.md @@ -0,0 +1,167 @@ +# Synthetic BMC lifecycle fixture + +Status: implemented test-only session-controller wiring and fixture executable. +Portable tests exercise actual private Coordinator custody. This is not a +production authorization adapter, provider observation source, or cleaning proof +for physical hardware. See [lifecycle custody](secure-bmc-lifecycle.md). + +## Wiring and trust boundary + +`fleet-controller` defaults to `--lifecycle-mode=production`: readiness fails and +no lifecycle authority is injected. An unknown mode fails startup. Explicit +`--lifecycle-mode=synthetic --private-namespace=fleet-system` injects the same +`LifecycleSessionAuthority` into both session and projection reconcilers. Its +Coordinator and resolver use an uncached Kubernetes client. The synthetic mode's +readiness indicates configured wiring, not that any particular fixture is ready. +Missing or invalid fixtures still deny session admission. + +The standalone prototype manifest `config/manager/controller.yaml` opts into +synthetic mode. It is not a production overlay. Its RBAC reads namespaces and +reads/lists/updates Secrets only in `fleet-system`; it no longer reads allocation +CRDs. Changing the private namespace requires a corresponding scoped Role and +RoleBinding. The session controller cannot create fixture grants. The fixture +command is an operator tool, run with dedicated test-cluster credentials. + +The fixture command reads existing Machine, MachineCapacity and namespace +lifetimes. It installs the normal Machine protection finalizer, retains an +immutable, private `synthetic-session-*` Secret grant, and calls +`EnsureClaimCustody` and `Allocate`. The grant alone never authorizes a session: +the real committed asset and bound claim custody must agree. The grant pins one +authenticated username, Machine UID/generation, namespace UIDs, capacity +UID/generation, device, location and member route. Every refresh rereads live +objects. Missing/recreated/deleting objects, changed device or generation, or a +different principal fail closed. Re-running allocation with different immutable +grant inputs is rejected. + +Admission, class/profile requirements and current eligible hardware observations +are explicitly synthetic, as in the standalone/staging fixtures. The command +accepts only powered-off, networkless Machines without initial installation. It +constructs synthetic class/profile inputs matching the Machine's reference names; +those objects need not be published. It does not write availability status or use +MachineAllocation annotations. Real Coordinator CAS decides exclusivity even when +the synthetic evidence says capacity is available. + +## Exact harness recipe + +Build alongside the existing plugin and controller images, without needing a new +container or service: + +```sh +go build -o "$E2E_DIR/bin/fleet-session-fixture" ./cmd/fleet-session-fixture +``` + +The E2E owner should apply `config/rbac/controller.yaml` and the prototype manager +manifest, create `fleet-provider`, and apply the Machine and capacity objects. +For example, the management API needs these synthetic objects: + +```yaml +apiVersion: metal.datumapis.com/v1alpha1 +kind: Machine +metadata: {name: db-01, namespace: default} +spec: + machineClassRef: {name: synthetic-libvirt} + machineProfileRef: {name: synthetic-libvirt} + locationRef: {name: location-e2e} + powerState: "Off" +--- +apiVersion: metal.datumapis.com/v1alpha1 +kind: MachineCapacity +metadata: {name: db01-capacity, namespace: fleet-provider} +spec: + deviceRef: {name: device-allocated} + allocationPolicy: Enabled + cleaningPolicyRef: {name: synthetic-e2e} + reclaimPolicy: Retain +``` + +Keep the existing location-local capacity/enrollment fixture aligned with the +capacity name and device. The command does not create provider enrollment or +federation registration. Then allocate: + +```sh +fixture() { + "$E2E_DIR/bin/fleet-session-fixture" --synthetic \ + --kubeconfig "$MGMT_KUBECONFIG" \ + --state "$E2E_DIR/session-executor.json" "$@" +} +fixture --phase=allocate --machine db-01 --capacity db01-capacity \ + --principal system:serviceaccount:default:fleet-authorized \ + --member-cluster fleet-location-e2e +``` + +Defaults are `--namespace=default`, `--capacity-namespace=fleet-provider` and +`--private-namespace=fleet-system`. The principal must be the exact username +retained by admission, not the local kubeconfig context name. Allocation prints +only `machineUID` and `epoch`, not the private fence token. Use equivalent calls +for db-02/db-03 rather than creating or patching MachineAllocation CRDs. + +Retain the operator-local simulator state file outside Git across every retry and +reuse. A nonblocking file lock excludes concurrent fixture processes using the +same state path. Use exactly one state path/host per test environment. The +existing persistent simulator supplies **synthetic provider cleanup only**; it +cannot acknowledge gateway sessions or settle unknown Redfish effects. + +## Release and recreation + +Capture the old Machine UID before deletion. Never infer release authority from +a reused object name: + +```sh +old_machine_uid=$(kubectl --kubeconfig "$MGMT_KUBECONFIG" -n default \ + get machine db-01 -o jsonpath='{.metadata.uid}') +fixture --phase=release --machine db-01 --machine-uid "$old_machine_uid" +``` + +With an active session, that call is expected to exit nonzero with +`management session teardown is not verified`, **after** the Coordinator has +transitioned the asset to Releasing and requested revocation. The harness must +assert this specific blocking result, not suppress arbitrary command errors. +The controller stops refresh, revokes projection, and consumes verified gateway +cleanup. Wait for stream closure and the binding's current-generation +`CleanupConfirmed=True`, then retry the exact command. Only a successful release +with `SafeToRemoveFinalizer=true` runs synthetic cleanup, settles claim custody, +and removes the Machine finalizer. No fixture command fabricates that condition. + +After successful release, delete and recreate the Machine, then run allocation +again with its new UID. Reusing the same capacity retains the physical asset +record and increments its epoch; a different capacity must first finish its own +release. Old session bindings remain pinned to their old allocation and Machine +UID. A released Machine lifetime cannot be reallocated without recreation. + +The E2E owner's script changes are: + +- Replace initial and extra MachineAllocation seed/patch blocks with fixture + allocation commands against the existing capacity objects. +- Replace release status patches with the blocked-release, verified-teardown, + retry sequence above. Preserve the exact old UID through retries. +- Before an `up.sh` reset deletes Machines/capacities, release each retained + allocation. Do not delete Coordinator Secrets, immutable grants, or binding + records to bypass cleanup. Recreate a whole disposable environment when a + deliberate unrecoverable fault prevents a subsequent clean run. +- Run unknown-operation tests last or on dedicated capacity. Unknown/pending + journal entries, missing projection/journal evidence, and unresolved accepted + mutations must block teardown, Machine finalizer removal, and reuse forever + absent qualified recovery evidence. A timed-out proxy or restarted gateway is + not such evidence. Do not restart a new session on the same occupied asset to + escape that barrier. + +## Validation and remaining gaps + +```sh +go test ./cmd/fleet-controller ./cmd/fleet-session-fixture ./internal/staging/sessionfixture ./internal/controller +go test -race ./cmd/fleet-controller ./internal/staging/sessionfixture ./internal/controller +kustomize build config/manager >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` + +Tests cover actual reconciler admission, principal and object lifetime rejection, +grant-only denial, release blocking, unknown teardown rejection, next-epoch reuse, +and production/default wiring. Lifecycle deadlines are canonicalized to the +Kubernetes timestamp precision before acquisition so returned authority matches +the exact persisted binding even before a second API round trip. + +Full Kind/Karmada/libvirt acceptance belongs to the E2E harness; it is not proved +by these portable tests. Production caller-preserving authorization, trusted +observations, provider-cleanup qualification and multi-executor fencing remain +unimplemented. Synthetic grants must never be used with real customer assets. diff --git a/internal/controller/management_lifecycle.go b/internal/controller/management_lifecycle.go index 6490a729..5aa85f75 100644 --- a/internal/controller/management_lifecycle.go +++ b/internal/controller/management_lifecycle.go @@ -3,6 +3,7 @@ package controller import ( "context" "errors" + "time" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" @@ -185,6 +186,8 @@ func (a *LifecycleSessionAuthority) resolve(ctx context.Context, binding session } func (a *LifecycleSessionAuthority) Acquire(ctx context.Context, proposed sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) { + proposed.ConnectBefore = metav1.NewTime(proposed.ConnectBefore.UTC().Truncate(time.Second)) + proposed.ExpiresAt = metav1.NewTime(proposed.ExpiresAt.UTC().Truncate(time.Second)) var retained sessionv1.MachineManagementSessionBindingSpec err := retry.RetryOnConflict(retry.DefaultRetry, func() error { asset, access, err := a.resolve(ctx, proposed) diff --git a/internal/staging/sessionfixture/authority.go b/internal/staging/sessionfixture/authority.go new file mode 100644 index 00000000..44e9203f --- /dev/null +++ b/internal/staging/sessionfixture/authority.go @@ -0,0 +1,117 @@ +package sessionfixture + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +type Grant struct { + Principal string `json:"principal"` + MachineNamespace string `json:"machineNamespace"` + MachineName string `json:"machineName"` + MachineGeneration int64 `json:"machineGeneration"` + CapacityGeneration int64 `json:"capacityGeneration"` + Access controller.ManagementAccess `json:"access"` +} + +type Resolver struct { + Client client.Client + PrivateNamespace string +} + +func grantName(uid types.UID) string { + digest := sha256.Sum256([]byte(uid)) + return "synthetic-session-" + hex.EncodeToString(digest[:16]) +} + +func (r Resolver) ResolveManagementAccess(ctx context.Context, binding sessionv1.MachineManagementSessionBindingSpec) (controller.ManagementAccess, error) { + var secret corev1.Secret + if err := r.Client.Get(ctx, client.ObjectKey{Namespace: r.PrivateNamespace, Name: grantName(binding.MachineUID)}, &secret); err != nil { + return controller.ManagementAccess{}, err + } + var grant Grant + if err := json.Unmarshal(secret.Data["grant.json"], &grant); err != nil { + return controller.ManagementAccess{}, err + } + access := grant.Access + if secret.Immutable == nil || !*secret.Immutable || secret.DeletionTimestamp != nil || grant.Principal == "" || grant.Principal != binding.RequestingPrincipal || grant.MachineNamespace != binding.MachineNamespace || grant.MachineName != binding.MachineName || access.MachineUID != binding.MachineUID || binding.Protocol != "Redfish" || binding.AccessProfile != "Provisioning" { + return controller.ManagementAccess{}, controller.ErrUnsupported + } + var claim fleetv1.Machine + var capacity fleetv1.MachineCapacity + var consumer, provider corev1.Namespace + for _, item := range []struct { + key client.ObjectKey + obj client.Object + }{ + {client.ObjectKey{Namespace: grant.MachineNamespace, Name: grant.MachineName}, &claim}, + {client.ObjectKey{Namespace: access.CapacityNamespace, Name: access.CapacityName}, &capacity}, + {client.ObjectKey{Name: grant.MachineNamespace}, &consumer}, + {client.ObjectKey{Name: access.CapacityNamespace}, &provider}, + } { + if err := r.Client.Get(ctx, item.key, item.obj); err != nil { + return controller.ManagementAccess{}, err + } + if item.obj.GetDeletionTimestamp() != nil { + return controller.ManagementAccess{}, controller.ErrRecordInvalid + } + } + if claim.UID != access.MachineUID || claim.Generation != grant.MachineGeneration || consumer.UID != access.NamespaceUID || provider.UID != access.ProviderProject.UID || capacity.UID != access.CapacityUID || capacity.Generation != grant.CapacityGeneration || capacity.Spec.DeviceRef.Name != access.DeviceName || claim.Spec.LocationRef.Name != access.LocationName || capacity.Spec.AllocationPolicy != "Enabled" { + return controller.ManagementAccess{}, controller.ErrRecordInvalid + } + return access, nil +} + +func NewAuthority(kube client.Client, namespace string) (*controller.LifecycleSessionAuthority, error) { + coordinator, err := controller.NewCoordinator(kube, namespace, unavailableExecutor{}, controller.LocalDigestImageResolver{}, nil, time.Minute) + if err != nil { + return nil, err + } + return &controller.LifecycleSessionAuthority{Coordinator: coordinator, Resolver: Resolver{Client: kube, PrivateNamespace: namespace}}, nil +} + +type unavailableExecutor struct{} + +func (unavailableExecutor) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown +} + +func (unavailableExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown +} + +func saveGrant(ctx context.Context, kube client.Client, namespace string, grant Grant) error { + data, err := json.Marshal(grant) + if err != nil { + return err + } + immutable := true + secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: grantName(grant.Access.MachineUID)}, Immutable: &immutable, Data: map[string][]byte{"grant.json": data}} + var existing corev1.Secret + err = kube.Get(ctx, client.ObjectKeyFromObject(secret), &existing) + if client.IgnoreNotFound(err) != nil { + return err + } + if err == nil { + if existing.Immutable == nil || !*existing.Immutable || string(existing.Data["grant.json"]) != string(data) || existing.DeletionTimestamp != nil { + return errors.New("synthetic grant differs from retained immutable inputs") + } + return nil + } + return kube.Create(ctx, secret) +} diff --git a/internal/staging/sessionfixture/executor.go b/internal/staging/sessionfixture/executor.go new file mode 100644 index 00000000..249816c7 --- /dev/null +++ b/internal/staging/sessionfixture/executor.go @@ -0,0 +1,26 @@ +package sessionfixture + +import ( + "context" + "fmt" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +type StoreExecutor struct { + Store *simulator.Store +} + +func (e StoreExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { + operation, lost, err := e.Store.Submit(request) + if err != nil || lost { + return simulator.OperationResult{}, fmt.Errorf("%w: synthetic submit: %v (lost=%t)", executor.ErrOutcomeUnknown, err, lost) + } + return operation.ResultView(), nil +} + +func (e StoreExecutor) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { + operation, found := e.Store.Get(id) + return operation.ResultView(), found, nil +} diff --git a/internal/staging/sessionfixture/fixture.go b/internal/staging/sessionfixture/fixture.go new file mode 100644 index 00000000..a209b575 --- /dev/null +++ b/internal/staging/sessionfixture/fixture.go @@ -0,0 +1,99 @@ +package sessionfixture + +import ( + "context" + "errors" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" +) + +type Fixture struct { + Client client.Client + Coordinator *controller.Coordinator + PrivateNamespace string +} + +func (f Fixture) Allocate(ctx context.Context, machineKey, capacityKey client.ObjectKey, principal, member string) (*controller.AssetRecord, error) { + if principal == "" || member == "" { + return nil, errors.New("explicit synthetic principal and member cluster are required") + } + var claim fleetv1.Machine + var capacity fleetv1.MachineCapacity + var consumer, provider corev1.Namespace + for _, item := range []struct { + key client.ObjectKey + obj client.Object + }{{machineKey, &claim}, {capacityKey, &capacity}, {client.ObjectKey{Name: machineKey.Namespace}, &consumer}, {client.ObjectKey{Name: capacityKey.Namespace}, &provider}} { + if err := f.Client.Get(ctx, item.key, item.obj); err != nil { + return nil, err + } + if item.obj.GetUID() == "" || item.obj.GetDeletionTimestamp() != nil { + return nil, controller.ErrRecordInvalid + } + } + if claim.Spec.LocationRef.Name == "" || claim.Spec.MachineClassRef.Name == "" || claim.Spec.MachineProfileRef.Name == "" || claim.Spec.PowerState != "Off" || capacity.Spec.DeviceRef.Name == "" || capacity.Spec.AllocationPolicy != "Enabled" || len(claim.Spec.NetworkInterfaces) != 0 || claim.Spec.InitialInstallationRef != nil { + return nil, errors.New("synthetic fixture requires a location, class, profile, device, enabled capacity and powered-off networkless claim without installation") + } + grant := Grant{Principal: principal, MachineNamespace: claim.Namespace, MachineName: claim.Name, MachineGeneration: claim.Generation, CapacityGeneration: capacity.Generation, Access: controller.ManagementAccess{ + Scope: controller.LocalClaimScope(consumer.UID), NamespaceUID: consumer.UID, MachineUID: claim.UID, + ConsumerProject: controller.ProjectIdentity{AuthorityID: "local", RouteName: consumer.Name, UID: consumer.UID}, + ProviderProject: controller.ProjectIdentity{AuthorityID: "local", RouteName: provider.Name, UID: provider.UID}, + CapacityNamespace: capacity.Namespace, CapacityName: capacity.Name, CapacityUID: capacity.UID, DeviceName: capacity.Spec.DeviceRef.Name, + LocationName: claim.Spec.LocationRef.Name, MemberCluster: member, + }} + if err := saveGrant(ctx, f.Client, f.PrivateNamespace, grant); err != nil { + return nil, err + } + admission := controller.AdmissionAuthority{PrincipalUID: principal, DecisionID: "synthetic-session-fixture"} + if err := f.Coordinator.EnsureClaimCustody(ctx, &claim, consumer.UID, admission); err != nil { + return nil, err + } + if !controllerutil.ContainsFinalizer(&claim, controller.MachineFinalizer) { + controllerutil.AddFinalizer(&claim, controller.MachineFinalizer) + if err := f.Client.Update(ctx, &claim); err != nil { + return nil, err + } + } + capacity.Status.Conditions = nil + for _, condition := range []string{"Prepared", "Healthy", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, metav1.Condition{Type: condition, Status: metav1.ConditionTrue, ObservedGeneration: capacity.Generation, LastTransitionTime: metav1.Now(), Reason: "SyntheticFixture"}) + } + capacity.Status.Hardware.CPU.Architecture = "amd64" + class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: claim.Spec.MachineClassRef.Name, UID: "synthetic-class"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: capacity.Namespace}}}} + profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: claim.Spec.MachineProfileRef.Name, UID: "synthetic-profile"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64"}}} + return f.Coordinator.Allocate(ctx, controller.AllocationRequest{Claim: &claim, Class: class, Profile: profile, MachineCapacities: []fleetv1.MachineCapacity{capacity}, NamespaceUID: consumer.UID, Admission: admission, EvidenceObservedAt: map[types.UID]time.Time{capacity.UID: time.Now()}}) +} + +func (f Fixture) Release(ctx context.Context, machineKey client.ObjectKey, uid types.UID) (controller.ReleaseResult, error) { + if uid == "" { + return controller.ReleaseResult{}, errors.New("exact --machine-uid required for release") + } + result, err := f.Coordinator.Release(ctx, uid) + if err != nil { + return result, err + } + if !result.SafeToRemoveFinalizer { + return result, errors.New("release is not verified; retain custody and retry") + } + err = retry.RetryOnConflict(retry.DefaultRetry, func() error { + var claim fleetv1.Machine + if err := f.Client.Get(ctx, machineKey, &claim); err != nil { + return client.IgnoreNotFound(err) + } + if claim.UID != uid || !controllerutil.ContainsFinalizer(&claim, controller.MachineFinalizer) { + return nil + } + controllerutil.RemoveFinalizer(&claim, controller.MachineFinalizer) + return f.Client.Update(ctx, &claim) + }) + return result, err +} diff --git a/internal/staging/sessionfixture/fixture_test.go b/internal/staging/sessionfixture/fixture_test.go new file mode 100644 index 00000000..338837fa --- /dev/null +++ b/internal/staging/sessionfixture/fixture_test.go @@ -0,0 +1,181 @@ +package sessionfixture + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/simulator" +) + +func newFixture(t *testing.T) (Fixture, *controller.LifecycleSessionAuthority, *fleetv1.Machine, *fleetv1.MachineCapacity, *simulator.Store) { + t.Helper() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, fleetv1.AddToScheme, sessionv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "consumer", Name: "db-01", UID: "claim-1", Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "synthetic"}, MachineProfileRef: fleetv1.LocalReference{Name: "synthetic"}, LocationRef: fleetv1.LocalReference{Name: "location"}, PowerState: "Off"}} + capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "provider", Name: "capacity", UID: "capacity-1", Generation: 1}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "device"}, AllocationPolicy: "Enabled"}} + kube := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&sessionv1.MachineManagementSession{}, &sessionv1.MachineManagementSessionBinding{}).WithObjects(claim, capacity, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "consumer", UID: "consumer-1"}}, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "provider", UID: "provider-1"}}).Build() + store, err := simulator.Open(filepath.Join(t.TempDir(), "executor.json")) + if err != nil { + t.Fatal(err) + } + coordinator, err := controller.NewCoordinator(kube, "private", StoreExecutor{Store: store}, controller.LocalDigestImageResolver{}, nil, time.Minute) + if err != nil { + t.Fatal(err) + } + authority, err := NewAuthority(kube, "private") + if err != nil { + t.Fatal(err) + } + return Fixture{Client: kube, Coordinator: coordinator, PrivateNamespace: "private"}, authority, claim, capacity, store +} + +func allocate(t *testing.T, fixture Fixture, claim *fleetv1.Machine, capacity *fleetv1.MachineCapacity) *controller.AssetRecord { + t.Helper() + asset, err := fixture.Allocate(context.Background(), client.ObjectKeyFromObject(claim), client.ObjectKeyFromObject(capacity), "alice", "cell") + if err != nil { + t.Fatal(err) + } + return asset +} + +func proposed(claim *fleetv1.Machine) sessionv1.MachineManagementSessionBindingSpec { + return sessionv1.MachineManagementSessionBindingSpec{MachineNamespace: claim.Namespace, MachineName: claim.Name, MachineUID: claim.UID, RequestingPrincipal: "alice", Protocol: "Redfish", AccessProfile: "Provisioning", SessionNamespace: claim.Namespace, SessionName: "access", SessionUID: "session-1", ClientPublicKey: "key", ConnectBefore: metav1.NewTime(time.Now().Add(time.Minute)), ExpiresAt: metav1.NewTime(time.Now().Add(time.Hour)), SessionCorrelationID: "session-correlation", OperationCorrelationID: "operation-correlation"} +} + +func TestFixtureWiresSessionReconcilerToRealCustody(t *testing.T) { + fixture, authority, claim, capacity, _ := newFixture(t) + asset := allocate(t, fixture, claim, capacity) + session := &sessionv1.MachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: "access", Namespace: claim.Namespace, UID: "session-1", Annotations: map[string]string{controller.PrincipalAnnotation: "alice"}}, Spec: sessionv1.MachineManagementSessionSpec{MachineRef: sessionv1.LocalReference{Name: claim.Name}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", TTL: metav1.Duration{Duration: time.Minute}}} + ctx := context.Background() + if err := fixture.Client.Create(ctx, session); err != nil { + t.Fatal(err) + } + reconciler := controller.SessionReconciler{Client: fixture.Client, Lifecycle: authority} + if _, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(session)}); err != nil { + t.Fatal(err) + } + var bindings sessionv1.MachineManagementSessionBindingList + if err := fixture.Client.List(ctx, &bindings); err != nil || len(bindings.Items) != 1 { + t.Fatalf("missing binding: %+v %v", bindings, err) + } + binding := &bindings.Items[0] + if binding.Spec.AllocationUID != types.UID(asset.BindingID) || binding.Spec.DeviceName != capacity.Spec.DeviceRef.Name || !authority.Active(ctx, binding) { + t.Fatalf("binding did not retain real custody: %+v", binding.Spec) + } +} + +func TestReleaseBlocksUntilVerifiedTeardownThenReusesNextEpoch(t *testing.T) { + fixture, authority, claim, capacity, store := newFixture(t) + asset := allocate(t, fixture, claim, capacity) + ctx := context.Background() + retained, err := authority.Acquire(ctx, proposed(claim)) + if err != nil { + t.Fatal(err) + } + binding := &sessionv1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Generation: 1}, Spec: retained} + if err := authority.BeginProjection(ctx, binding); err != nil { + t.Fatal(err) + } + for attempt := 0; attempt < 2; attempt++ { + result, err := fixture.Release(ctx, client.ObjectKeyFromObject(claim), claim.UID) + if !errors.Is(err, controller.ErrManagementActive) || result.SafeToRemoveFinalizer || authority.Active(ctx, binding) { + t.Fatalf("release crossed management barrier: %+v %v", result, err) + } + } + if _, found := store.Get("cleanup-" + asset.BindingID); found { + t.Fatal("cleanup executed before verified session teardown") + } + other := claim.DeepCopyObject().(*fleetv1.Machine) + other.Name, other.UID, other.ResourceVersion = "db-02", "claim-2", "" + if err := fixture.Client.Create(ctx, other); err != nil { + t.Fatal(err) + } + if _, err := fixture.Allocate(ctx, client.ObjectKeyFromObject(other), client.ObjectKeyFromObject(capacity), "alice", "cell"); !errors.Is(err, controller.ErrInsufficientCapacity) { + t.Fatalf("reuse before teardown: %v", err) + } + binding.Annotations = map[string]string{controller.RevokedAtAnnotation: "revoked"} + binding.Status.Conditions = []metav1.Condition{{Type: "CleanupConfirmed", Status: metav1.ConditionUnknown, ObservedGeneration: 1}} + if err := authority.Complete(ctx, binding); !errors.Is(err, controller.ErrManagementActive) { + t.Fatalf("unknown teardown cleared custody: %v", err) + } + binding.Status.Conditions[0].Status = metav1.ConditionTrue + if err := authority.Complete(ctx, binding); err != nil { + t.Fatal(err) + } + result, err := fixture.Release(ctx, client.ObjectKeyFromObject(claim), claim.UID) + if err != nil || !result.SafeToRemoveFinalizer { + t.Fatalf("verified release: %+v %v", result, err) + } + next := allocate(t, fixture, other, capacity) + if next.Epoch != asset.Epoch+1 || next.BindingID == asset.BindingID { + t.Fatalf("reuse did not advance allocation: %+v", next) + } +} + +func TestSyntheticGrantCannotAuthorizeMissingCustodyOrChangedLifetimes(t *testing.T) { + for _, change := range []string{"principal", "machine", "capacity", "namespace", "provider", "device", "grant-only"} { + t.Run(change, func(t *testing.T) { + fixture, authority, claim, capacity, _ := newFixture(t) + allocate(t, fixture, claim, capacity) + binding := proposed(claim) + ctx := context.Background() + switch change { + case "principal": + binding.RequestingPrincipal = "mallory" + case "machine", "capacity", "namespace", "provider", "device": + var object client.Object = claim.DeepCopyObject().(*fleetv1.Machine) + if change == "capacity" || change == "device" { + object = capacity.DeepCopyObject().(*fleetv1.MachineCapacity) + } else if change == "namespace" { + object = &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "consumer"}} + } else if change == "provider" { + object = &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "provider"}} + } + if err := fixture.Client.Get(ctx, client.ObjectKeyFromObject(object), object); err != nil { + t.Fatal(err) + } + if change == "device" { + object.(*fleetv1.MachineCapacity).Spec.DeviceRef.Name = "different" + } else { + object.SetUID("replacement") + } + if err := fixture.Client.Update(ctx, object); err != nil { + t.Fatal(err) + } + case "grant-only": + var secrets corev1.SecretList + if err := fixture.Client.List(ctx, &secrets); err != nil { + t.Fatal(err) + } + for _, secret := range secrets.Items { + if secret.Name != grantName(claim.UID) { + if err := fixture.Client.Delete(ctx, &secret); err != nil { + t.Fatal(err) + } + } + } + } + if _, err := authority.Acquire(ctx, binding); err == nil { + t.Fatal("changed authority or missing custody was accepted") + } + }) + } +} From 0063dce7da4310e54af6aabad001cc29e062e502 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 18:37:43 -0600 Subject: [PATCH 23/24] test(e2e): exercise custody-backed fixtures and guarded lifecycle release --- .../machine-management-prototype.md | 29 ++++ hack/e2e/lifecycle.sh | 56 ++++++++ hack/e2e/test-common.sh | 14 ++ hack/e2e/test.sh | 127 +++++++++--------- hack/e2e/up.sh | 27 ++-- .../machine-management/seed/allocation.yaml | 13 -- 6 files changed, 184 insertions(+), 82 deletions(-) create mode 100644 hack/e2e/lifecycle.sh diff --git a/docs/implementation/machine-management-prototype.md b/docs/implementation/machine-management-prototype.md index 5d6ca8a3..9b14c057 100644 --- a/docs/implementation/machine-management-prototype.md +++ b/docs/implementation/machine-management-prototype.md @@ -389,3 +389,32 @@ must be last or isolated: unknown effects legitimately prevent teardown and allocation reuse, and cannot be cleared merely to continue the test. No native Linux/CI full run, physical BMC, or OpenVPN qualification was obtained in this environment. A complete warning-free validator and lifecycle run remains required. + +### Combined lifecycle harness integration (2026-11-12) + +The harness now builds and invokes the explicit +[synthetic lifecycle fixture](synthetic-bmc-fixture.md), rather than creating or +patching MachineAllocation CRDs. Initial and extra allocations use real +Secret-backed Coordinator custody. Live-session release must return the specific +management-teardown blocking error and durably mark the asset Releasing. The +harness then waits for current-generation `CleanupConfirmed=True` before retrying +the exact old Machine UID's release, deleting/recreating the Machine, and proving +that capacity reuse advances its allocation epoch. + +Repeated setup attempts release retained fixture Machine lifetimes before +resetting domains or replacing workloads. They never delete custody, grants, +private session bindings, or operation journals to bypass an uncertain result. +An unresolved release fails setup; use whole-environment teardown only for these +disposable synthetic resources. Location-outage deletion must retain its session +finalizer while cleanup is Unknown, then wait for verified recovery. The final +lost-response scenario proves duplicate suppression and rejects a distinct new +mutation, release, finalizer removal, and competing allocation while the effect +remains Unknown. It intentionally leaves occupied custody for diagnostics and +whole-environment teardown rather than attempting another session on that asset. + +These combined script assertions are implemented, not yet full-harness verified. +Shell syntax/ShellCheck and helper regressions pass, including rejection of +missing/API-error custody evidence and stale-generation/Unknown cleanup. Focused +Go tests cover the fixture, controller, Redfish, and gateway. Per the integration +handoff, native Linux GitHub CI is the next full-run evidence source; no new local +emulated run was started and no CI success is claimed here. diff --git a/hack/e2e/lifecycle.sh b/hack/e2e/lifecycle.sh new file mode 100644 index 00000000..8a347a87 --- /dev/null +++ b/hack/e2e/lifecycle.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash + +fixture() { + "${E2E_DIR}/bin/fleet-session-fixture" --synthetic --kubeconfig "${MGMT_KUBECONFIG}" \ + --state "${E2E_DIR}/session-executor.json" "$@" +} + +allocate_fixture() { + fixture --phase=allocate --machine "$1" --capacity "$2" \ + --principal system:serviceaccount:default:fleet-authorized --member-cluster fleet-location-e2e +} + +binding_clean() { + local binding=$1 object + object=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system \ + get machinemanagementsessionbinding "${binding}" -o json) || return 1 + jq -e '.metadata.generation as $generation | any(.status.conditions[]?; + .type == "CleanupConfirmed" and .status == "True" and .observedGeneration == $generation)' <<<"${object}" >/dev/null +} + +asset_state() { + local uid=$1 state=$2 objects + objects=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system \ + get secrets -l fleet.datumapis.com/private-record=asset -o json) || return 1 + jq -e --arg uid "${uid}" --arg state "${state}" ' + [.items[].data["record.json"] | @base64d | fromjson | select(.claimUID == $uid)] | + length == 1 and all(.[]; .state == $state)' <<<"${objects}" >/dev/null +} + +release_blocked() { + local machine=$1 uid=$2 + if fixture --phase=release --machine "${machine}" --machine-uid "${uid}" \ + >"${E2E_DIR}/release-${machine}.json" 2>"${E2E_DIR}/release-${machine}.log"; then + fail "release of ${machine} bypassed active management custody" + fi + grep -q 'management session teardown is not verified' "${E2E_DIR}/release-${machine}.log" || fail "unexpected release failure for ${machine}" + jq -e '.State == "Releasing" and .SafeToRemoveFinalizer == false' "${E2E_DIR}/release-${machine}.json" >/dev/null || fail "release did not report blocked custody" + asset_state "${uid}" Releasing || fail "release did not durably mark asset Releasing" +} + +release_fixture() { + local machine=$1 uid=$2 bindings binding + if fixture --phase=release --machine "${machine}" --machine-uid "${uid}" \ + >"${E2E_DIR}/release-${machine}.json" 2>"${E2E_DIR}/release-${machine}.log"; then + jq -e '.SafeToRemoveFinalizer == true' "${E2E_DIR}/release-${machine}.json" >/dev/null + return + fi + grep -q 'management session teardown is not verified' "${E2E_DIR}/release-${machine}.log" || fail "unexpected release failure for ${machine}" + bindings=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -o json | + jq -r --arg uid "${uid}" '.items[] | select(.spec.machineUID == $uid) | .metadata.name') || return 1 + for binding in ${bindings}; do + wait_for "verified teardown for ${binding}; unresolved custody requires whole disposable environment teardown" "binding_clean '${binding}'" + done + fixture --phase=release --machine "${machine}" --machine-uid "${uid}" >"${E2E_DIR}/release-${machine}.json" + jq -e '.SafeToRemoveFinalizer == true' "${E2E_DIR}/release-${machine}.json" >/dev/null +} diff --git a/hack/e2e/test-common.sh b/hack/e2e/test-common.sh index 8fe7ddea..e0c75d2c 100755 --- a/hack/e2e/test-common.sh +++ b/hack/e2e/test-common.sh @@ -2,6 +2,7 @@ set -euo pipefail ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) source "${ROOT_DIR}/hack/e2e/common.sh" +source "${ROOT_DIR}/hack/e2e/lifecycle.sh" wait_for "immediate success" true if (FLEET_E2E_WAIT_SECONDS=1 wait_for "bounded failure" false) 2>/dev/null; then @@ -38,4 +39,17 @@ for summary in '' ' - Pass: 0, Warn: 0, Fail: 0, Skip: 0' ' - Pass: 0, Warn: 1 done printf '%s\n' ' - Pass: 12, Warn: 0, Fail: 0, Skip: 35' >"${report}" validator_coverage "${report}" +MGMT_KUBECONFIG=ignored +kubectl() { return 1; } +if binding_clean binding; then fail "API failure counted as verified teardown"; fi +kubectl() { printf '%s\n' '{"metadata":{"generation":2},"status":{"conditions":[{"type":"CleanupConfirmed","status":"True","observedGeneration":1}]}}'; } +if binding_clean binding; then fail "old generation counted as verified teardown"; fi +kubectl() { printf '%s\n' '{"metadata":{"generation":2},"status":{"conditions":[{"type":"CleanupConfirmed","status":"Unknown","observedGeneration":2}]}}'; } +if binding_clean binding; then fail "unknown counted as verified teardown"; fi +kubectl() { printf '%s\n' '{"metadata":{"generation":2},"status":{"conditions":[{"type":"CleanupConfirmed","status":"True","observedGeneration":2}]}}'; } +binding_clean binding +kubectl() { printf '%s\n' '{"items":[]}'; } +if asset_state uid Releasing; then fail "missing custody counted as occupied"; fi +kubectl() { return 1; } +if asset_state uid Releasing; then fail "API failure counted as occupied custody"; fi echo 'E2E harness helpers: PASS' diff --git a/hack/e2e/test.sh b/hack/e2e/test.sh index ea58970d..b2e822f2 100755 --- a/hack/e2e/test.sh +++ b/hack/e2e/test.sh @@ -10,6 +10,7 @@ KARMADA_KUBECONFIG="${E2E_DIR}/karmada.kubeconfig" PATH="${E2E_DIR}/bin:${PATH}" export PATH source "${ROOT_DIR}/hack/e2e/common.sh" +source "${ROOT_DIR}/hack/e2e/lifecycle.sh" rm -f "${E2E_DIR}/checkpoints.log" "${E2E_DIR}/viewer-ready.json" "${E2E_DIR}/ready-2.json" for file in "${MGMT_KUBECONFIG}" "${LOCATION_KUBECONFIG}" "${KARMADA_KUBECONFIG}" "${E2E_DIR}/management-ca.crt"; do @@ -77,10 +78,13 @@ start_proxy() { } stop_proxy() { + local confirm=${1:-true} kill -TERM "${proxy_pid}" 2>/dev/null || true wait "${proxy_pid}" 2>/dev/null || true proxy_pid= - wait_for "session deletion" "sessions_absent '${MGMT_KUBECONFIG}' default machinemanagementsessions.metal.datumapis.com" + if [[ "${confirm}" == true ]]; then + wait_for "session deletion" "sessions_absent '${MGMT_KUBECONFIG}' default machinemanagementsessions.metal.datumapis.com" + fi } # Nested x86 QEMU on non-x86 developer hosts can take tens of seconds to apply @@ -181,9 +185,8 @@ spec: EOF done db02_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machine db-02 -o jsonpath='{.metadata.uid}') -db03_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machine db-03 -o jsonpath='{.metadata.uid}') -for pair in "db-02:${db02_uid}:db02-capacity:device-unallocated" "db-03:${db03_uid}:db03-capacity:device-rejected"; do - IFS=: read -r machine machine_uid capacity device <<<"${pair}" +for pair in "db-02:db02-capacity:device-unallocated" "db-03:db03-capacity:device-rejected"; do + IFS=: read -r machine capacity device <<<"${pair}" kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - <"${E2E_DIR}/recreated-allocation.json" +jq -e '.epoch > 1' "${E2E_DIR}/recreated-allocation.json" >/dev/null || fail "capacity reuse did not advance allocation epoch" [[ "${new_machine_uid}" != "${old_machine_uid}" ]] || fail "recreated Machine retained its old UID" [[ $(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${old_binding_name}" -o jsonpath='{.spec.machineUID}') == "${old_machine_uid}" ]] || fail "old session binding inherited the recreated Machine" old_binding_revoked=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${old_binding_name}" -o jsonpath='{.metadata.annotations.fleet\.datumapis\.com/revoked-at}') @@ -325,26 +302,6 @@ rf -X POST -H 'Content-Type: application/json' -d '{"ResetType":"On"}' "${root}/ wait_for "new allocation domain power-on" "[[ \$(docker exec fleet-e2e-virtual-bmc virsh domstate unallocated | tr -d '\\r') == running ]]" checkpoint "release fence and same-name Machine recreation" -# Fault-inject a lost BMC response. Retrying the identical admitted operation -# must recover its Unknown task without sending a second physical reset. -stop_proxy -wait_for "prior location projection teardown" \ - "sessions_absent '${LOCATION_KUBECONFIG}' machine-access-system projectedmachinemanagementsessions.coordination.fleet.datumapis.com" -kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch deployment fleet-gateway --type=json \ - -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--fault-drop-reset-response-once"}]' -kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s -start_proxy -reset_path='/redfish/v1/Systems/unallocated/Actions/ComputerSystem.Reset' -reset_before=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) -lost_body='{"ResetType":"ForceRestart"}' -lost_first=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") -lost_second=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") -[[ $(jq -r .TaskState <<<"${lost_first}") == Exception && $(jq -r .TaskStatus <<<"${lost_first}") == Warning ]] || fail "lost response was not reported Unknown" -[[ $(jq -r .Id <<<"${lost_first}") == $(jq -r .Id <<<"${lost_second}") ]] || fail "retry created a second operation" -reset_after=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) -[[ $((reset_after - reset_before)) -eq 1 ]] || fail "lost-response retry sent $((reset_after - reset_before)) physical resets" -checkpoint "lost response remains Unknown and retry sends no second reset" - # The gateway schedules the admitted expiry and closes the stream rather than # treating a still-live client or relay connection as authority. stop_proxy @@ -372,11 +329,59 @@ unknown_session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get m unknown_binding_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -l "fleet.datumapis.com/session-uid=${unknown_session_uid}" -o jsonpath='{.items[0].metadata.name}') docker pause fleet-location-e2e-control-plane >/dev/null location_paused=true -stop_proxy -cleanup_status=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${unknown_binding_name}" -o json | jq -r '.status.conditions[] | select(.type=="CleanupConfirmed") | .status + ":" + .reason') -[[ "${cleanup_status}" == "Unknown:LocationUnconfirmed" ]] || fail "unconfirmed teardown was not Unknown: ${cleanup_status}" +stop_proxy false +wait_for "unconfirmed location teardown" "[[ \$(kubectl --request-timeout=10s --kubeconfig '${MGMT_KUBECONFIG}' -n fleet-system get machinemanagementsessionbinding '${unknown_binding_name}' -o json | jq -r '.status.conditions[] | select(.type==\"CleanupConfirmed\") | .status + \":\" + .reason') == Unknown:LocationUnconfirmed ]]" +unconfirmed_session=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o json) +jq -e --arg uid "${unknown_session_uid}" 'any(.items[]; .metadata.uid == $uid and .metadata.deletionTimestamp != null and (.metadata.finalizers | length > 0))' <<<"${unconfirmed_session}" >/dev/null || fail "unconfirmed session deletion discarded custody" docker unpause fleet-location-e2e-control-plane >/dev/null location_paused=false [[ ! -e "${E2E_DIR}/credentials.json" && ! -e "${E2E_DIR}/ca.pem" ]] || fail "proxy secret files survived shutdown" checkpoint "unconfirmed location teardown remains Unknown; local secrets removed" +wait_for "location recovery verified teardown" "binding_clean '${unknown_binding_name}'" +wait_for "recovered session deletion" "sessions_absent '${MGMT_KUBECONFIG}' default machinemanagementsessions" + +wait_for "prior location projection teardown" \ + "sessions_absent '${LOCATION_KUBECONFIG}' machine-access-system projectedmachinemanagementsessions.coordination.fleet.datumapis.com" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch deployment fleet-gateway --type=json \ + -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--fault-drop-reset-response-once"}]' +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s +start_proxy +lost_session_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.name}') +lost_session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsession "${lost_session_name}" -o jsonpath='{.metadata.uid}') +lost_binding_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -l "fleet.datumapis.com/session-uid=${lost_session_uid}" -o jsonpath='{.items[0].metadata.name}') +reset_path='/redfish/v1/Systems/unallocated/Actions/ComputerSystem.Reset' +reset_before=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) +lost_body='{"ResetType":"ForceRestart"}' +lost_first=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") +lost_second=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") +[[ $(jq -r .TaskState <<<"${lost_first}") == Exception && $(jq -r .TaskStatus <<<"${lost_first}") == Warning ]] || fail "lost response was not reported Unknown" +[[ $(jq -r .Id <<<"${lost_first}") == $(jq -r .Id <<<"${lost_second}") ]] || fail "retry created a second operation" +reset_after=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) +[[ $((reset_after - reset_before)) -eq 1 ]] || fail "lost-response retry sent $((reset_after - reset_before)) physical resets" +[[ $(rf_status -X POST -H 'Content-Type: application/json' -d '{"ResetType":"ForceOff"}' "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") == 409 ]] || fail "unknown effect allowed a new mutation" +release_blocked db-01 "${new_machine_uid}" +stop_proxy false +sleep 35 +release_blocked db-01 "${new_machine_uid}" +if binding_clean "${lost_binding_name}"; then fail "unknown operation fabricated verified teardown"; fi +retained_session=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsession "${lost_session_name}" -o json) +jq -e '.metadata.deletionTimestamp != null and (.metadata.finalizers | length > 0)' <<<"${retained_session}" >/dev/null || fail "unknown session lost its finalizer" +retained_machine=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n default get machine db-01 -o json) +jq -e '.metadata.finalizers | index("fleet.datumapis.com/machine-protection") != null' <<<"${retained_machine}" >/dev/null || fail "unknown effect released Machine protection" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - <"${E2E_DIR}/blocked-reuse.json" 2>"${E2E_DIR}/blocked-reuse.log"; then + fail "unknown effect allowed occupied capacity reuse" +fi +grep -q 'no eligible clean machine is available' "${E2E_DIR}/blocked-reuse.log" || fail "reuse failed for an unexpected reason" +asset_state "${new_machine_uid}" Releasing || fail "failed reuse changed occupied asset custody" +checkpoint "lost response deduplicates; unknown effects block mutation, release, and reuse" echo "machine-management end-to-end scenarios: PASS" diff --git a/hack/e2e/up.sh b/hack/e2e/up.sh index 2ec38243..1d7244d4 100755 --- a/hack/e2e/up.sh +++ b/hack/e2e/up.sh @@ -7,6 +7,8 @@ TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" MGMT_KUBECONFIG="${E2E_DIR}/management.kubeconfig" LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" export FLEET_E2E_STATE="${E2E_DIR}/virtual-bmc" +source "${ROOT_DIR}/hack/e2e/common.sh" +source "${ROOT_DIR}/hack/e2e/lifecycle.sh" for tool in docker kind kubectl helm curl go jq openssl; do command -v "${tool}" >/dev/null || { echo "missing required tool: ${tool}" >&2; exit 1; } @@ -18,6 +20,20 @@ if [[ $(uname -s) != Linux ]]; then export FLEET_FORCE_QEMU=${FLEET_FORCE_QEMU:-1} fi mkdir -p "${E2E_DIR}/bin" "${FLEET_E2E_STATE}/evidence" "${FLEET_E2E_STATE}/images" +go build -o "${E2E_DIR}/bin/fleet-session-fixture" "${ROOT_DIR}/cmd/fleet-session-fixture" +if kind get clusters | grep -qx fleet-management-e2e; then + kind get kubeconfig --name fleet-management-e2e >"${MGMT_KUBECONFIG}" + chmod 0600 "${MGMT_KUBECONFIG}" + machine_crd=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" get crd machines.metal.datumapis.com --ignore-not-found -o name) + if [[ -n "${machine_crd}" ]]; then + retained=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n default get machines -o json) + while IFS=$'\t' read -r machine uid; do + [[ -n "${machine}" ]] || continue + release_fixture "${machine}" "${uid}" + done < <(jq -r '.items[] | select(.metadata.name == "db-01" or .metadata.name == "db-02" or .metadata.name == "db-03" or .metadata.name == "db-04") | + [.metadata.name,.metadata.uid] | @tsv' <<<"${retained}") + fi +fi bash "${ROOT_DIR}/hack/e2e/prepare-schemas.sh" find "${FLEET_E2E_STATE}/evidence" -maxdepth 1 -type f -delete @@ -200,18 +216,13 @@ kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout s # Reset only resources owned by this dedicated E2E environment so repeated up # and test invocations begin from the same authority state. kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machinemanagementsessions --all --timeout=40s --ignore-not-found -kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system delete projectedmachinemanagementsessions --all --ignore-not-found -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system delete machinemanagementsessionbindings --all --ignore-not-found -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machines db-01 db-02 db-03 --ignore-not-found -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system delete machineallocations --all --ignore-not-found -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-provider delete machinecapacities --all --ignore-not-found 2>/dev/null || true +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machines db-01 db-02 db-03 db-04 --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-provider delete machinecapacities --all --ignore-not-found kubectl --kubeconfig "${MGMT_KUBECONFIG}" create namespace fleet-provider --dry-run=client -o yaml | kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/machine.yaml" kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/allocation.yaml" -machine_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machine db-01 -o jsonpath='{.metadata.uid}') -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system annotate machineallocation db-01-allocation fleet.datumapis.com/machine-uid="${machine_uid}" --overwrite -kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system patch machineallocation db-01-allocation --subresource=status --type=merge -p '{"status":{"phase":"Active"}}' +allocate_fixture db-01 allocated-capacity kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${TEST_DIR}/seed/location-management.yaml" kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/test-identities.yaml" diff --git a/test/e2e/machine-management/seed/allocation.yaml b/test/e2e/machine-management/seed/allocation.yaml index cb7db7c9..83b8fc2e 100644 --- a/test/e2e/machine-management/seed/allocation.yaml +++ b/test/e2e/machine-management/seed/allocation.yaml @@ -8,16 +8,3 @@ spec: allocationPolicy: Enabled cleaningPolicyRef: {name: synthetic-e2e} reclaimPolicy: Retain ---- -apiVersion: metal.datumapis.com/v1alpha1 -kind: MachineAllocation -metadata: - name: db-01-allocation - namespace: fleet-system - annotations: - fleet.datumapis.com/member-cluster: fleet-location-e2e - fleet.datumapis.com/location-name: location-e2e - fleet.datumapis.com/provider-project: datum-owned-hardware -spec: - machineRef: {project: project, namespace: default, name: db-01} - machineCapacityRef: {namespace: fleet-provider, name: allocated-capacity} From 62d88c4234028c0269c2ab87552ed6399b40463e Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Thu, 12 Nov 2026 18:53:23 -0600 Subject: [PATCH 24/24] fix: isolate session fixture CLI flags from controller runtime --- cmd/fleet-session-fixture/main.go | 34 ++++++++++++++------------ cmd/fleet-session-fixture/main_test.go | 24 ++++++++++++++++++ 2 files changed, 43 insertions(+), 15 deletions(-) create mode 100644 cmd/fleet-session-fixture/main_test.go diff --git a/cmd/fleet-session-fixture/main.go b/cmd/fleet-session-fixture/main.go index f80f96e5..e5ed0135 100644 --- a/cmd/fleet-session-fixture/main.go +++ b/cmd/fleet-session-fixture/main.go @@ -24,26 +24,30 @@ import ( ) func main() { - if err := run(); err != nil { + if err := run(os.Args[1:]); err != nil && !errors.Is(err, flag.ErrHelp) { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func run() error { - synthetic := flag.Bool("synthetic", false, "required acknowledgment: test-only admission, observations and cleanup; never use with real assets") - kubeconfig := flag.String("kubeconfig", "", "management kubeconfig") - phase := flag.String("phase", "allocate", "allocate or release") - namespace := flag.String("namespace", "default", "Machine namespace") - machine := flag.String("machine", "db-01", "Machine name") - uid := flag.String("machine-uid", "", "exact retained Machine UID, required for release") - capacityNamespace := flag.String("capacity-namespace", "fleet-provider", "MachineCapacity namespace") - capacity := flag.String("capacity", "", "MachineCapacity name, required for allocation") - principal := flag.String("principal", "", "exact authenticated username authorized by this synthetic fixture") - member := flag.String("member-cluster", "", "synthetic member route") - privateNamespace := flag.String("private-namespace", "fleet-system", "Coordinator and immutable synthetic grant Secret namespace") - state := flag.String("state", "", "persistent synthetic executor file; retain across all release retries and reuse") - flag.Parse() +func run(args []string) error { + // controller-runtime registers kubeconfig globally; keep this CLI isolated. + flags := flag.NewFlagSet("fleet-session-fixture", flag.ContinueOnError) + synthetic := flags.Bool("synthetic", false, "required acknowledgment: test-only admission, observations and cleanup; never use with real assets") + kubeconfig := flags.String("kubeconfig", "", "management kubeconfig") + phase := flags.String("phase", "allocate", "allocate or release") + namespace := flags.String("namespace", "default", "Machine namespace") + machine := flags.String("machine", "db-01", "Machine name") + uid := flags.String("machine-uid", "", "exact retained Machine UID, required for release") + capacityNamespace := flags.String("capacity-namespace", "fleet-provider", "MachineCapacity namespace") + capacity := flags.String("capacity", "", "MachineCapacity name, required for allocation") + principal := flags.String("principal", "", "exact authenticated username authorized by this synthetic fixture") + member := flags.String("member-cluster", "", "synthetic member route") + privateNamespace := flags.String("private-namespace", "fleet-system", "Coordinator and immutable synthetic grant Secret namespace") + state := flags.String("state", "", "persistent synthetic executor file; retain across all release retries and reuse") + if err := flags.Parse(args); err != nil { + return err + } if !*synthetic || *kubeconfig == "" || *state == "" || (*phase != "allocate" && *phase != "release") { return errors.New("--synthetic, --kubeconfig, --state and --phase=allocate|release are required") } diff --git a/cmd/fleet-session-fixture/main_test.go b/cmd/fleet-session-fixture/main_test.go new file mode 100644 index 00000000..bff136f9 --- /dev/null +++ b/cmd/fleet-session-fixture/main_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "errors" + "flag" + "strings" + "testing" +) + +func TestFixtureFlagsAreIndependentOfGlobalKubeconfig(t *testing.T) { + // Imported controller-runtime already owns this global flag in the executable. + if flag.Lookup("kubeconfig") == nil { + t.Fatal("expected controller-runtime global kubeconfig flag") + } + for i := 0; i < 2; i++ { + err := run([]string{"--kubeconfig", "/synthetic/test-config"}) + if err == nil || !strings.Contains(err.Error(), "--synthetic") { + t.Fatalf("expected safety validation before accessing a cluster: %v", err) + } + } + if err := run([]string{"--help"}); !errors.Is(err, flag.ErrHelp) { + t.Fatalf("help: %v", err) + } +}