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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ flowchart LR
end
subgraph Node[Sandbox node]
Noded[ucloud-noded]
Agent[Python node agent / Warden]
Storage[storage-native daemon]
EnvIO[environment I/O]
Runsc[runsc sandboxes]
Expand All @@ -41,12 +40,11 @@ flowchart LR
Relay --> PG
API -->|node-control token| Noded
Placement -->|node-control token| Noded
Noded -->|Unix socket| Agent
Agent --> Storage
Agent --> Runsc
Noded --> Storage
Noded --> EnvIO
Noded --> Runsc
Runsc --> EnvIO --> Store --> S3
Agent -->|heartbeats| API
Noded -->|heartbeats| API
Runsc -->|model calls| Relay
Relay -->|park / wake| API
Autoscaler --> Provider
Expand Down
165 changes: 165 additions & 0 deletions runtime/gatewayd/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package main

import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"strings"
)

const (
execSessionPrefixHeader = "X-UCloud-Exec-Session-Prefix"
execRouteVersion = "xr1"
execRouteMACBytes = 16
execRouteKeyContext = "ucloud-sandboxes exec session route v1"
maxPrefixLength = 768
)

var (
prefixRE = regexp.MustCompile(`^xr1\.[A-Za-z0-9_-]{1,700}\.[A-Za-z0-9_-]{22}$`)
sessionRE = regexp.MustCompile(`^(xr1\.[A-Za-z0-9_-]{1,700}\.[A-Za-z0-9_-]{22})\.[0-9a-f]{32}$`)
)

// SignedExecRoute mirrors sandboxes/exec_session_routes.py SignedExecRoute.
type SignedExecRoute struct {
SandboxID string
SandboxGeneration int64
NodeID string
JobID string
IssuedAt int64
}

// ExecSessionRoutes implements byte-for-byte compatible HMAC signing and
// verification with sandboxes/exec_session_routes.py.
type ExecSessionRoutes struct {
key []byte
}

func NewExecSessionRoutes(gatewaySecret string) (*ExecSessionRoutes, error) {
trimmed := strings.TrimSpace(gatewaySecret)
if trimmed == "" {
return nil, errors.New("exec session routes require a gateway secret")
}
mac := hmac.New(sha256.New, []byte(trimmed))
mac.Write([]byte(execRouteKeyContext))
return &ExecSessionRoutes{key: mac.Sum(nil)}, nil
}

func (e *ExecSessionRoutes) computeMAC(payload string) string {
mac := hmac.New(sha256.New, e.key)
mac.Write([]byte(execRouteVersion + "." + payload))
sum := mac.Sum(nil)
return base64.RawURLEncoding.EncodeToString(sum[:execRouteMACBytes])
}

func (e *ExecSessionRoutes) Prefix(route SignedExecRoute) (string, error) {
// Python json.dumps([sandbox_id, generation, node_id, job_id, issued_at], separators=(",", ":"), ensure_ascii=False)
raw, err := json.Marshal([]any{
route.SandboxID,
route.SandboxGeneration,
route.NodeID,
route.JobID,
route.IssuedAt,
})
if err != nil {
return "", err
}
payload := base64.RawURLEncoding.EncodeToString(raw)
prefix := fmt.Sprintf("%s.%s.%s", execRouteVersion, payload, e.computeMAC(payload))
if len(prefix) > maxPrefixLength || !prefixRE.MatchString(prefix) {
return "", errors.New("exec route identity is too long for a session prefix")
}
return prefix, nil
}

func (e *ExecSessionRoutes) Decode(sessionID string) (SignedExecRoute, bool) {
matches := sessionRE.FindStringSubmatch(sessionID)
if len(matches) != 2 {
return SignedExecRoute{}, false
}
parts := strings.Split(matches[1], ".")
if len(parts) != 3 {
return SignedExecRoute{}, false
}
payload, mac := parts[1], parts[2]
expected := e.computeMAC(payload)
if !hmac.Equal([]byte(mac), []byte(expected)) {
return SignedExecRoute{}, false
}
decoded, err := base64.RawURLEncoding.DecodeString(payload)
if err != nil {
return SignedExecRoute{}, false
}
var values []json.RawMessage
if err := json.Unmarshal(decoded, &values); err != nil || len(values) != 5 {
return SignedExecRoute{}, false
}
var sandboxID, nodeID, jobID string
var generation, issuedAt int64
if err := json.Unmarshal(values[0], &sandboxID); err != nil || sandboxID == "" {
return SignedExecRoute{}, false
}
if err := json.Unmarshal(values[1], &generation); err != nil || generation <= 0 {
return SignedExecRoute{}, false
}
if err := json.Unmarshal(values[2], &nodeID); err != nil || nodeID == "" {
return SignedExecRoute{}, false
}
if err := json.Unmarshal(values[3], &jobID); err != nil || jobID == "" {
return SignedExecRoute{}, false
}
if err := json.Unmarshal(values[4], &issuedAt); err != nil || issuedAt <= 0 {
return SignedExecRoute{}, false
}
return SignedExecRoute{
SandboxID: sandboxID,
SandboxGeneration: generation,
NodeID: nodeID,
JobID: jobID,
IssuedAt: issuedAt,
}, true
}

type Credentials struct {
GatewayToken string
SandboxAPIToken string
NodeControlToken string
}

func tokenMatches(headers http.Header, expected string, allowSandboxHeader bool) bool {
if expected == "" {
return false
}
auth := headers.Get("Authorization")
if strings.HasPrefix(auth, "Bearer ") {
bearer := auth[len("Bearer "):]
if bearer != "" && hmac.Equal([]byte(bearer), []byte(expected)) {
return true
}
}
if allowSandboxHeader {
tok := headers.Get("X-UCloud-Sandbox-Token")
if tok != "" && hmac.Equal([]byte(tok), []byte(expected)) {
return true
}
}
return false
}

// AuthorizeSDKRoute returns true if the request carries either the gateway
// control token or the public sandbox API key (matching sandboxes/gateway/auth.py).
func (c Credentials) AuthorizeSDKRoute(headers http.Header) bool {
if tokenMatches(headers, c.GatewayToken, false) {
return true
}
return tokenMatches(headers, c.SandboxAPIToken, true)
}

func (c Credentials) AuthorizeGatewayToken(headers http.Header) bool {
return tokenMatches(headers, c.GatewayToken, false)
}
Loading
Loading