Files
ghaymah_dev2 ea900387de
ci / test (push) Canceled after 0s
ci / cross-build (amd64, darwin) (push) Canceled after 0s
ci / cross-build (amd64, linux) (push) Canceled after 0s
ci / cross-build (amd64, windows) (push) Canceled after 0s
ci / cross-build (arm64, darwin) (push) Canceled after 0s
ci / cross-build (arm64, linux) (push) Canceled after 0s
ci / cross-build (arm64, windows) (push) Canceled after 0s
Security hardening: dockerignore engine, upload limits, client-side encryption, cross-platform builds
- archive: use Docker's own patternmatcher for .dockerignore/.gitignore/.gyignore + hard secret/VCS/build-output exclusions
- crypto: AES-256-CTR encrypt the source archive before upload (key/IV to gateway via HTTPS)
- deploy: --max-upload / GY_MAX_UPLOAD (default 500 MB)
- Makefile + CI matrix: cross-compile linux/darwin/windows x amd64/arm64
- tests: crypto round-trip + ignore rules
2026-10-24 10:02:34 -04:00

274 lines
7.2 KiB
Go

// Package apiclient is a thin client for the Ghaymah gateway REST API. Every
// response is wrapped in a {"data": ...} envelope; errors carry an HTTP status
// plus a human-readable message extracted from the gateway's error body.
package apiclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// DefaultBaseURL is the production gateway endpoint.
const DefaultBaseURL = "https://gateway.ghaymah.systems"
// Client talks to the gateway.
type Client struct {
BaseURL string
Token string
HTTP *http.Client
}
// New builds a client (baseURL defaults to DefaultBaseURL).
func New(baseURL, token string) *Client {
if strings.TrimSpace(baseURL) == "" {
baseURL = DefaultBaseURL
}
return &Client{
BaseURL: strings.TrimSuffix(baseURL, "/"),
Token: token,
HTTP: &http.Client{Timeout: 60 * time.Second},
}
}
// APIError is a non-2xx gateway response.
type APIError struct {
Status int
Message string
}
func (e *APIError) Error() string { return e.Message }
func (c *Client) do(ctx context.Context, method, path string, body, out any) error {
var rdr io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return err
}
rdr = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, rdr)
if err != nil {
return err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
resp, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20))
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
msg := strings.TrimSpace(string(data))
var e struct {
Error string `json:"error"`
Message string `json:"message"`
}
if json.Unmarshal(data, &e) == nil {
if e.Message != "" {
msg = e.Message
} else if e.Error != "" {
msg = e.Error
}
}
if msg == "" {
msg = resp.Status
}
return &APIError{Status: resp.StatusCode, Message: msg}
}
if out == nil {
return nil
}
return decodeEnvelope(data, out)
}
func decodeEnvelope(data []byte, out any) error {
var envelope struct {
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(data, &envelope); err != nil {
return fmt.Errorf("decode response: %w", err)
}
if envelope.Data == nil {
// Legacy endpoints return the object directly.
return json.Unmarshal(data, out)
}
return json.Unmarshal(envelope.Data, out)
}
// --- types ---
// Deployment is the response of POST /v1/deployments.
type Deployment struct {
ProjectID string `json:"project_id"`
BuildID string `json:"build_id"`
Name string `json:"name"`
UploadURL string `json:"upload_url"`
ExpiresIn int `json:"expires_in"`
}
// Build is a CI build / deployment status.
type Build struct {
ID string `json:"id"`
ProjectID string `json:"project_id"`
CommitSHA string `json:"commit_sha"`
Branch string `json:"branch"`
Status string `json:"status"`
TriggeredBy string `json:"triggered_by"`
ImageRef string `json:"image_ref"`
Error string `json:"error"`
CreatedAt string `json:"created_at"`
FinishedAt string `json:"finished_at"`
}
// Terminal reports whether a build has finished.
func (b Build) Terminal() bool {
switch b.Status {
case "succeeded", "failed", "cancelled":
return true
}
return false
}
// LogEntry is one log line.
type LogEntry struct {
Timestamp string `json:"timestamp"`
Message string `json:"message"`
Source string `json:"source"`
Severity string `json:"severity"`
}
// Port is an exposed app port.
type Port struct {
Name string `json:"name"`
Number int `json:"number"`
Hostname string `json:"hostname"`
}
// App is a Cumin app.
type App struct {
ID string `json:"id"`
ProjectID string `json:"project_id"`
Name string `json:"name"`
Image string `json:"image"`
Ports []Port `json:"ports"`
Status string `json:"status"`
Tags map[string]string `json:"tags"`
Hibernated bool `json:"hibernated"`
Ephemeral bool `json:"ephemeral"`
Instances int `json:"instances"`
}
// URL returns the app's first public URL. Cumin returns hostnames both with
// and without a scheme (auto-generated ones include https://), so strip any
// existing scheme before prepending exactly one.
func (a App) URL() string {
for _, p := range a.Ports {
if p.Hostname != "" {
h := strings.TrimPrefix(strings.TrimPrefix(p.Hostname, "https://"), "http://")
return "https://" + h
}
}
return ""
}
// --- endpoints ---
// Verify checks the token is valid (returns nil on a 200 from /v1/apps).
func (c *Client) Verify(ctx context.Context) error {
var apps []App
return c.do(ctx, http.MethodGet, "/v1/apps", nil, &apps)
}
// CreateDeployment starts a CLI deployment and returns the upload details.
// encKey/encIV are the hex AES-256-CTR key + IV the CLI used to encrypt the
// source archive; sourceSize is the (unencrypted == encrypted) byte size, used
// by the gateway to enforce the upload limit before presigning.
func (c *Client) CreateDeployment(ctx context.Context, name, strategy string, port int, encKey, encIV string, sourceSize int64) (*Deployment, error) {
body := map[string]any{
"name": name,
"strategy": strategy,
"runtime": map[string]any{"port": port},
}
if encKey != "" {
body["encryption_key"] = encKey
body["encryption_iv"] = encIV
}
if sourceSize > 0 {
body["source_size"] = sourceSize
}
var out Deployment
err := c.do(ctx, http.MethodPost, "/v1/deployments", body, &out)
return &out, err
}
// CompleteDeployment signals the source upload finished and starts the build.
func (c *Client) CompleteDeployment(ctx context.Context, buildID string) (*Build, error) {
var out Build
err := c.do(ctx, http.MethodPost, "/v1/deployments/"+buildID+"/complete", nil, &out)
return &out, err
}
// GetDeployment returns the build status plus the deployed app's public URL.
func (c *Client) GetDeployment(ctx context.Context, buildID string) (*Build, string, error) {
var out struct {
Build Build `json:"build"`
AppURL string `json:"app_url"`
}
err := c.do(ctx, http.MethodGet, "/v1/deployments/"+buildID, nil, &out)
return &out.Build, out.AppURL, err
}
// DeploymentLogs returns the build's log lines.
func (c *Client) DeploymentLogs(ctx context.Context, buildID string, max int) ([]LogEntry, error) {
var out []LogEntry
if max <= 0 {
max = 200
}
path := fmt.Sprintf("/v1/deployments/%s/logs?max=%d", buildID, max)
err := c.do(ctx, http.MethodGet, path, nil, &out)
return out, err
}
// ListApps returns the caller's apps.
func (c *Client) ListApps(ctx context.Context) ([]App, error) {
var out []App
if err := c.do(ctx, http.MethodGet, "/v1/apps", nil, &out); err != nil {
return nil, err
}
if out == nil {
out = []App{}
}
return out, nil
}
// AppLogs returns an app's recent log lines.
func (c *Client) AppLogs(ctx context.Context, appID string, max int) ([]LogEntry, error) {
var out []LogEntry
if max <= 0 {
max = 200
}
path := fmt.Sprintf("/v1/apps/%s/logs?max=%d", appID, max)
err := c.do(ctx, http.MethodGet, path, nil, &out)
return out, err
}