Compare commits
3
Commits
main
..
8ab60b6d6d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ab60b6d6d | ||
|
|
152e4259ae | ||
|
|
5c30fd4fb7 |
+25
-12
@@ -5,22 +5,18 @@ on:
|
|||||||
branches: [main]
|
branches: [main]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: forgejo.riotpiao.com
|
REGISTRY: forgejo.riotpiao.com
|
||||||
IMAGE: forgejo.riotpiao.com/rock/api-gateway
|
IMAGE: forgejo.riotpiao.com/rock/homelab-frontend
|
||||||
DOCKER_HOST: tcp://localhost:2375
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
ci:
|
test:
|
||||||
name: CI
|
name: Test
|
||||||
runs-on: golang
|
runs-on: golang
|
||||||
steps:
|
steps:
|
||||||
- name: Install Node.js and Docker
|
- name: Install Node.js for actions runtime
|
||||||
run: |
|
run: apt-get update && apt-get install -y nodejs
|
||||||
apt-get update
|
|
||||||
apt-get install -y nodejs docker.io
|
|
||||||
|
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -31,9 +27,25 @@ jobs:
|
|||||||
- name: Go test
|
- name: Go test
|
||||||
run: go test ./...
|
run: go test ./...
|
||||||
|
|
||||||
|
build-push:
|
||||||
|
name: Build & Push Image
|
||||||
|
needs: test
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
runs-on: golang
|
||||||
|
steps:
|
||||||
|
- name: Install Node.js and Docker
|
||||||
|
run: |
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y nodejs docker.io
|
||||||
|
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Get short SHA
|
- name: Get short SHA
|
||||||
id: sha
|
id: sha
|
||||||
run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
run: |
|
||||||
|
SHORT_SHA=$(git rev-parse --short HEAD)
|
||||||
|
echo "short_sha=${SHORT_SHA}" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
- name: Registry login
|
- name: Registry login
|
||||||
run: |
|
run: |
|
||||||
@@ -48,13 +60,14 @@ jobs:
|
|||||||
docker build --no-cache \
|
docker build --no-cache \
|
||||||
-t "${IMAGE}:${{ steps.sha.outputs.short_sha }}" \
|
-t "${IMAGE}:${{ steps.sha.outputs.short_sha }}" \
|
||||||
-t "${IMAGE}:latest" \
|
-t "${IMAGE}:latest" \
|
||||||
-f Dockerfile .
|
-f Dockerfile \
|
||||||
|
.
|
||||||
|
|
||||||
- name: Push Docker image
|
- name: Push Docker image
|
||||||
run: |
|
run: |
|
||||||
docker push "${IMAGE}:${{ steps.sha.outputs.short_sha }}"
|
docker push "${IMAGE}:${{ steps.sha.outputs.short_sha }}"
|
||||||
docker push "${IMAGE}:latest"
|
docker push "${IMAGE}:latest"
|
||||||
echo "✓ Pushed: ${IMAGE}:${{ steps.sha.outputs.short_sha }}"
|
echo "✓ Image pushed: ${IMAGE}:${{ steps.sha.outputs.short_sha }}"
|
||||||
|
|
||||||
- name: Prune unused images
|
- name: Prune unused images
|
||||||
run: docker image prune -a --force 2>&1 | tail -3 || true
|
run: docker image prune -a --force 2>&1 | tail -3 || true
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# Forgejo Registry Secrets Configuration
|
||||||
|
|
||||||
|
## One-Time Setup (Org Level)
|
||||||
|
|
||||||
|
All repos in the `rock` org share the same Forgejo registry credentials.
|
||||||
|
|
||||||
|
### Configure at Organization Level
|
||||||
|
|
||||||
|
1. Navigate to: https://forgejo.riotpiao.com/rock
|
||||||
|
2. Click Settings (gear icon)
|
||||||
|
3. Go to: Actions → Secrets
|
||||||
|
4. Add these org-level secrets:
|
||||||
|
- **Name**: `FORGEJO_REGISTRY_USER`
|
||||||
|
**Value**: `rock`
|
||||||
|
|
||||||
|
- **Name**: `FORGEJO_REGISTRY_TOKEN`
|
||||||
|
**Value**: `<your-forgejo-token>`
|
||||||
|
|
||||||
|
### Get Your Forgejo Token
|
||||||
|
|
||||||
|
1. Go to: https://forgejo.riotpiao.com/user/settings/applications
|
||||||
|
2. Click "Generate New Token"
|
||||||
|
3. Set scopes: `api`, `read:registry`, `write:registry`
|
||||||
|
4. Copy the token value into the secret
|
||||||
|
|
||||||
|
## Inheritance
|
||||||
|
|
||||||
|
Once org-level secrets are set:
|
||||||
|
- ✅ All repos in `rock` org automatically inherit them
|
||||||
|
- ✅ No per-repo configuration needed
|
||||||
|
- ✅ Workflows reference via `${{ secrets.FORGEJO_REGISTRY_USER }}`
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Each repo's CI workflow includes a validation step:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Validate registry credentials
|
||||||
|
run: |
|
||||||
|
if [ -z "${{ secrets.FORGEJO_REGISTRY_USER }}" ] || [ -z "${{ secrets.FORGEJO_REGISTRY_TOKEN }}" ]; then
|
||||||
|
echo "❌ ERROR: Registry secrets not configured"
|
||||||
|
echo "Set FORGEJO_REGISTRY_USER and FORGEJO_REGISTRY_TOKEN in org settings"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "✓ Registry credentials configured"
|
||||||
|
```
|
||||||
|
|
||||||
|
If secrets are missing, the validation step will fail with a clear error message pointing to this setup process.
|
||||||
|
|
||||||
|
## Affected Repositories
|
||||||
|
|
||||||
|
The following repos use these shared org-level secrets in their CI workflows:
|
||||||
|
|
||||||
|
- rock/riotpiao.com
|
||||||
|
- rock/homelab-frontend
|
||||||
|
- rock/poimen-workflows
|
||||||
|
- rock/poimen-memory
|
||||||
|
- rock/kmsvc-manage
|
||||||
|
|
||||||
|
All use the unified CI pattern:
|
||||||
|
- `test` job: runs on all branches + PRs (no registry access)
|
||||||
|
- `build-push` job: runs on main push only (requires registry credentials)
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### "Registry secrets not configured" error
|
||||||
|
|
||||||
|
If CI fails with this error:
|
||||||
|
1. Check org settings: https://forgejo.riotpiao.com/rock/settings/actions/secrets
|
||||||
|
2. Verify both secrets exist and are not empty
|
||||||
|
3. Re-trigger the workflow by pushing to main
|
||||||
|
|
||||||
|
### "unauthorized" from docker login
|
||||||
|
|
||||||
|
If you get `error response from daemon: unauthorized`:
|
||||||
|
1. Check the token value is correct (copy-paste carefully)
|
||||||
|
2. Verify token has `read:registry` and `write:registry` scopes
|
||||||
|
3. Generate a new token if the old one expired
|
||||||
+1
-8
@@ -9,7 +9,6 @@ import (
|
|||||||
"os/signal"
|
"os/signal"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/auth"
|
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/config"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/config"
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/proxy"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/proxy"
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/server"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/server"
|
||||||
@@ -76,13 +75,7 @@ func main() {
|
|||||||
_ = registry.Add(a)
|
_ = registry.Add(a)
|
||||||
}
|
}
|
||||||
log.Printf("%d service adapters loaded", registry.Count())
|
log.Printf("%d service adapters loaded", registry.Count())
|
||||||
|
dispatcher := serviceadapter.NewDispatcher(registry)
|
||||||
// Create shared JWT validator for X-Service auth enforcement
|
|
||||||
var jwtValidator *auth.Validator
|
|
||||||
if cfg.Auth.Enabled && cfg.Auth.JWKSURL != "" {
|
|
||||||
jwtValidator = auth.NewValidator(cfg.Auth.Issuer, cfg.Auth.Audience, cfg.Auth.JWKSURL)
|
|
||||||
}
|
|
||||||
dispatcher := serviceadapter.NewDispatcher(registry, jwtValidator)
|
|
||||||
|
|
||||||
// Create router that handles health endpoints, X-Service (ServiceAdapter) routing,
|
// Create router that handles health endpoints, X-Service (ServiceAdapter) routing,
|
||||||
// temporal endpoints, and passes others to upstream handler
|
// temporal endpoints, and passes others to upstream handler
|
||||||
|
|||||||
@@ -1,104 +0,0 @@
|
|||||||
package config_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/config"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestLoadAuthConfig_TokenURLAndClientID(t *testing.T) {
|
|
||||||
yaml := `
|
|
||||||
routes: []
|
|
||||||
models: []
|
|
||||||
auth:
|
|
||||||
enabled: true
|
|
||||||
issuer: "https://authentik.example.com/application/o/api-gw/"
|
|
||||||
audience: "api-gw"
|
|
||||||
jwksUrl: "https://authentik.example.com/application/o/api-gw/jwks/"
|
|
||||||
requiredCapability: "llm:inference"
|
|
||||||
tokenUrl: "https://authentik.example.com/application/o/token/"
|
|
||||||
clientId: "api-gw"
|
|
||||||
`
|
|
||||||
dir := t.TempDir()
|
|
||||||
path := filepath.Join(dir, "config.yaml")
|
|
||||||
if err := os.WriteFile(path, []byte(yaml), 0644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set env for client secret
|
|
||||||
t.Setenv("AUTH_CLIENT_SECRET", "test-secret-value")
|
|
||||||
|
|
||||||
_, _, _, auth, err := config.LoadRoutesAndModelsFromFile(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !auth.Enabled {
|
|
||||||
t.Error("auth should be enabled")
|
|
||||||
}
|
|
||||||
if auth.TokenURL != "https://authentik.example.com/application/o/token/" {
|
|
||||||
t.Errorf("tokenUrl = %q, want authentik token endpoint", auth.TokenURL)
|
|
||||||
}
|
|
||||||
if auth.ClientID != "api-gw" {
|
|
||||||
t.Errorf("clientId = %q, want api-gw", auth.ClientID)
|
|
||||||
}
|
|
||||||
if auth.ClientSecret != "test-secret-value" {
|
|
||||||
t.Errorf("clientSecret = %q, want test-secret-value", auth.ClientSecret)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoadAuthConfig_ClientSecretFromEnvOnly(t *testing.T) {
|
|
||||||
yaml := `
|
|
||||||
routes: []
|
|
||||||
models: []
|
|
||||||
auth:
|
|
||||||
enabled: true
|
|
||||||
tokenUrl: "https://example.com/token/"
|
|
||||||
clientId: "test"
|
|
||||||
`
|
|
||||||
dir := t.TempDir()
|
|
||||||
path := filepath.Join(dir, "config.yaml")
|
|
||||||
os.WriteFile(path, []byte(yaml), 0644)
|
|
||||||
|
|
||||||
// No AUTH_CLIENT_SECRET env set
|
|
||||||
t.Setenv("AUTH_CLIENT_SECRET", "")
|
|
||||||
|
|
||||||
_, _, _, auth, err := config.LoadRoutesAndModelsFromFile(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if auth.ClientSecret != "" {
|
|
||||||
t.Errorf("clientSecret should be empty when env not set, got %q", auth.ClientSecret)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoadAuthConfig_BackwardCompatible(t *testing.T) {
|
|
||||||
// Config without tokenUrl/clientId should still load (zero values)
|
|
||||||
yaml := `
|
|
||||||
routes: []
|
|
||||||
models: []
|
|
||||||
auth:
|
|
||||||
enabled: true
|
|
||||||
issuer: "https://example.com/"
|
|
||||||
jwksUrl: "https://example.com/jwks/"
|
|
||||||
requiredCapability: "llm:inference"
|
|
||||||
`
|
|
||||||
dir := t.TempDir()
|
|
||||||
path := filepath.Join(dir, "config.yaml")
|
|
||||||
os.WriteFile(path, []byte(yaml), 0644)
|
|
||||||
|
|
||||||
_, _, _, auth, err := config.LoadRoutesAndModelsFromFile(path)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if auth.TokenURL != "" {
|
|
||||||
t.Errorf("tokenUrl should be empty, got %q", auth.TokenURL)
|
|
||||||
}
|
|
||||||
if auth.ClientID != "" {
|
|
||||||
t.Errorf("clientId should be empty, got %q", auth.ClientID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -50,12 +50,6 @@ type AuthConfig struct {
|
|||||||
JWKSURL string
|
JWKSURL string
|
||||||
// RequiredCapability is the permission required for LLM inference (e.g., "llm:inference").
|
// RequiredCapability is the permission required for LLM inference (e.g., "llm:inference").
|
||||||
RequiredCapability string
|
RequiredCapability string
|
||||||
// TokenURL is the Authentik token endpoint for password/refresh grants.
|
|
||||||
TokenURL string
|
|
||||||
// ClientID is the OAuth2 client ID for token exchange.
|
|
||||||
ClientID string
|
|
||||||
// ClientSecret is the OAuth2 client secret (loaded from env, never from config file).
|
|
||||||
ClientSecret string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Route represents a single route and its upstream configuration.
|
// Route represents a single route and its upstream configuration.
|
||||||
|
|||||||
@@ -25,8 +25,6 @@ type rawAuth struct {
|
|||||||
Audience string `yaml:"audience"`
|
Audience string `yaml:"audience"`
|
||||||
JWKSURL string `yaml:"jwksUrl"`
|
JWKSURL string `yaml:"jwksUrl"`
|
||||||
RequiredCapability string `yaml:"requiredCapability"`
|
RequiredCapability string `yaml:"requiredCapability"`
|
||||||
TokenURL string `yaml:"tokenUrl"`
|
|
||||||
ClientID string `yaml:"clientId"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// rawRoute represents a single route in the YAML configuration.
|
// rawRoute represents a single route in the YAML configuration.
|
||||||
@@ -178,9 +176,6 @@ func LoadRoutesAndModelsFromFile(path string) (map[string]*Route, map[string]*Mo
|
|||||||
Audience: raw.Auth.Audience,
|
Audience: raw.Auth.Audience,
|
||||||
JWKSURL: raw.Auth.JWKSURL,
|
JWKSURL: raw.Auth.JWKSURL,
|
||||||
RequiredCapability: raw.Auth.RequiredCapability,
|
RequiredCapability: raw.Auth.RequiredCapability,
|
||||||
TokenURL: raw.Auth.TokenURL,
|
|
||||||
ClientID: raw.Auth.ClientID,
|
|
||||||
ClientSecret: os.Getenv("AUTH_CLIENT_SECRET"),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return routes, models, adapters, authConfig, nil
|
return routes, models, adapters, authConfig, nil
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
// Package identity extracts authenticated user identity from JWT claims
|
|
||||||
// and injects forwarding headers into proxied requests.
|
|
||||||
//
|
|
||||||
// Headers injected after JWT validation:
|
|
||||||
//
|
|
||||||
// X-Forwarded-User: subject (sub claim)
|
|
||||||
// X-Forwarded-Roles: comma-separated roles or permissions
|
|
||||||
// X-Acting-Service: authorized party (azp claim), only for service accounts
|
|
||||||
// X-Auth-Verified: "true" when gateway validated the JWT
|
|
||||||
//
|
|
||||||
// Security contract: downstream services MUST only accept traffic from the
|
|
||||||
// gateway (enforced by NetworkPolicy). They trust these headers because the
|
|
||||||
// gateway is the sole ingress path.
|
|
||||||
package identity
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Headers that the gateway controls. Incoming values from clients are
|
|
||||||
// stripped to prevent spoofing.
|
|
||||||
const (
|
|
||||||
HeaderUser = "X-Forwarded-User"
|
|
||||||
HeaderRoles = "X-Forwarded-Roles"
|
|
||||||
HeaderActingService = "X-Acting-Service"
|
|
||||||
HeaderAuthVerified = "X-Auth-Verified"
|
|
||||||
)
|
|
||||||
|
|
||||||
// managed lists all headers this package owns. Used for stripping and cleanup.
|
|
||||||
var managed = []string{
|
|
||||||
HeaderUser,
|
|
||||||
HeaderRoles,
|
|
||||||
HeaderActingService,
|
|
||||||
HeaderAuthVerified,
|
|
||||||
}
|
|
||||||
|
|
||||||
// StripIncoming removes all gateway-managed identity headers from an
|
|
||||||
// inbound request, preventing clients from spoofing identity.
|
|
||||||
// Call this early in the handler chain, before any routing.
|
|
||||||
func StripIncoming(r *http.Request) {
|
|
||||||
for _, h := range managed {
|
|
||||||
r.Header.Del(h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inject extracts identity from validated JWT claims and sets the
|
|
||||||
// corresponding forwarding headers on the request. Only call this
|
|
||||||
// after successful JWT validation.
|
|
||||||
func Inject(r *http.Request, claims jwt.MapClaims) {
|
|
||||||
r.Header.Set(HeaderAuthVerified, "true")
|
|
||||||
|
|
||||||
if sub := claimString(claims, "sub"); sub != "" {
|
|
||||||
r.Header.Set(HeaderUser, sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
if roles := claimStringSlice(claims, "roles"); len(roles) > 0 {
|
|
||||||
r.Header.Set(HeaderRoles, strings.Join(roles, ","))
|
|
||||||
} else if perms := claimStringSlice(claims, "permissions"); len(perms) > 0 {
|
|
||||||
r.Header.Set(HeaderRoles, strings.Join(perms, ","))
|
|
||||||
}
|
|
||||||
|
|
||||||
if azp := claimString(claims, "azp"); azp != "" {
|
|
||||||
sub := claimString(claims, "sub")
|
|
||||||
// Only set acting-service when azp differs from sub
|
|
||||||
// (i.e., a service account acting, not the user themselves)
|
|
||||||
if azp != sub {
|
|
||||||
r.Header.Set(HeaderActingService, azp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// claimString extracts a string value from claims, returning "" if
|
|
||||||
// the key is missing or not a string.
|
|
||||||
func claimString(claims jwt.MapClaims, key string) string {
|
|
||||||
val, ok := claims[key]
|
|
||||||
if !ok || val == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
s, ok := val.(string)
|
|
||||||
if !ok {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// claimStringSlice extracts a []string from claims. JWT libraries
|
|
||||||
// deserialize JSON arrays as []interface{}, so each element is
|
|
||||||
// type-asserted individually. Non-string elements are skipped.
|
|
||||||
func claimStringSlice(claims jwt.MapClaims, key string) []string {
|
|
||||||
val, ok := claims[key]
|
|
||||||
if !ok || val == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
raw, ok := val.([]interface{})
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
out := make([]string, 0, len(raw))
|
|
||||||
for _, v := range raw {
|
|
||||||
if s, ok := v.(string); ok && s != "" {
|
|
||||||
out = append(out, s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(out) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
package identity
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestStripIncoming_RemovesSpoofedHeaders(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set(HeaderUser, "evil-spoof")
|
|
||||||
r.Header.Set(HeaderRoles, "admin:*")
|
|
||||||
r.Header.Set(HeaderActingService, "fake-service")
|
|
||||||
r.Header.Set(HeaderAuthVerified, "true")
|
|
||||||
|
|
||||||
StripIncoming(r)
|
|
||||||
|
|
||||||
for _, h := range managed {
|
|
||||||
if got := r.Header.Get(h); got != "" {
|
|
||||||
t.Errorf("header %s should be stripped, got %q", h, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStripIncoming_PreservesOtherHeaders(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set("Authorization", "Bearer token")
|
|
||||||
r.Header.Set("Content-Type", "application/json")
|
|
||||||
r.Header.Set(HeaderUser, "spoof")
|
|
||||||
|
|
||||||
StripIncoming(r)
|
|
||||||
|
|
||||||
if got := r.Header.Get("Authorization"); got != "Bearer token" {
|
|
||||||
t.Errorf("Authorization should be preserved, got %q", got)
|
|
||||||
}
|
|
||||||
if got := r.Header.Get("Content-Type"); got != "application/json" {
|
|
||||||
t.Errorf("Content-Type should be preserved, got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_ServiceAccount(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "abc123-hashed-id",
|
|
||||||
"azp": "portfolio-agent",
|
|
||||||
"roles": []interface{}{"llm:inference", "memory:read"},
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
assertHeader(t, r, HeaderAuthVerified, "true")
|
|
||||||
assertHeader(t, r, HeaderUser, "abc123-hashed-id")
|
|
||||||
assertHeader(t, r, HeaderRoles, "llm:inference,memory:read")
|
|
||||||
assertHeader(t, r, HeaderActingService, "portfolio-agent")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_HumanUser(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "user-hash-456",
|
|
||||||
"azp": "api-gw",
|
|
||||||
"permissions": []interface{}{"*"},
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
assertHeader(t, r, HeaderAuthVerified, "true")
|
|
||||||
assertHeader(t, r, HeaderUser, "user-hash-456")
|
|
||||||
assertHeader(t, r, HeaderRoles, "*")
|
|
||||||
// azp != sub, so acting-service is set
|
|
||||||
assertHeader(t, r, HeaderActingService, "api-gw")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_SameSubAndAzp_NoActingService(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "portfolio-agent",
|
|
||||||
"azp": "portfolio-agent",
|
|
||||||
"roles": []interface{}{"llm:inference"},
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
assertHeader(t, r, HeaderActingService, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_RolesOverPermissions(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "user-1",
|
|
||||||
"roles": []interface{}{"llm:inference"},
|
|
||||||
"permissions": []interface{}{"admin:*"},
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
// roles takes precedence over permissions
|
|
||||||
assertHeader(t, r, HeaderRoles, "llm:inference")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_PermissionsFallback(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "user-1",
|
|
||||||
"permissions": []interface{}{"grafana:read", "grafana:write"},
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
assertHeader(t, r, HeaderRoles, "grafana:read,grafana:write")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_EmptyClaims(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
assertHeader(t, r, HeaderAuthVerified, "true")
|
|
||||||
assertHeader(t, r, HeaderUser, "")
|
|
||||||
assertHeader(t, r, HeaderRoles, "")
|
|
||||||
assertHeader(t, r, HeaderActingService, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_NilValuesInClaims(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": nil,
|
|
||||||
"azp": nil,
|
|
||||||
"roles": nil,
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
assertHeader(t, r, HeaderAuthVerified, "true")
|
|
||||||
assertHeader(t, r, HeaderUser, "")
|
|
||||||
assertHeader(t, r, HeaderRoles, "")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_WildcardPermission(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "admin-user",
|
|
||||||
"permissions": []interface{}{"*"},
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
// Wildcard passed as literal, never expanded
|
|
||||||
assertHeader(t, r, HeaderRoles, "*")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_MixedTypeRolesArray(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "user-1",
|
|
||||||
"roles": []interface{}{"llm:inference", 42, nil, "", "memory:read"},
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
// Non-string and empty elements skipped
|
|
||||||
assertHeader(t, r, HeaderRoles, "llm:inference,memory:read")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInject_EmptyRolesArray(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "user-1",
|
|
||||||
"roles": []interface{}{},
|
|
||||||
"permissions": []interface{}{"backup:read"},
|
|
||||||
}
|
|
||||||
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
// Empty roles falls through to permissions
|
|
||||||
assertHeader(t, r, HeaderRoles, "backup:read")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStripThenInject_OverwritesSpoof(t *testing.T) {
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set(HeaderUser, "evil-spoof")
|
|
||||||
r.Header.Set(HeaderAuthVerified, "true")
|
|
||||||
|
|
||||||
StripIncoming(r)
|
|
||||||
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"sub": "real-user",
|
|
||||||
"roles": []interface{}{"llm:inference"},
|
|
||||||
}
|
|
||||||
Inject(r, claims)
|
|
||||||
|
|
||||||
assertHeader(t, r, HeaderUser, "real-user")
|
|
||||||
assertHeader(t, r, HeaderAuthVerified, "true")
|
|
||||||
}
|
|
||||||
|
|
||||||
func assertHeader(t *testing.T, r *http.Request, key, want string) {
|
|
||||||
t.Helper()
|
|
||||||
got := r.Header.Get(key)
|
|
||||||
if got != want {
|
|
||||||
t.Errorf("header %s = %q, want %q", key, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -15,7 +15,6 @@ import (
|
|||||||
|
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/auth"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/auth"
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/config"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/config"
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/identity"
|
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/logging"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/logging"
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/tracing"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/tracing"
|
||||||
)
|
)
|
||||||
@@ -304,10 +303,6 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strip spoofed identity headers from all inbound requests.
|
|
||||||
// Must happen before any routing — even unauthenticated paths.
|
|
||||||
identity.StripIncoming(r)
|
|
||||||
|
|
||||||
// JWT Authentication for /v1/* endpoints
|
// JWT Authentication for /v1/* endpoints
|
||||||
if h.jwtValidator != nil && strings.HasPrefix(r.URL.Path, "/v1/") {
|
if h.jwtValidator != nil && strings.HasPrefix(r.URL.Path, "/v1/") {
|
||||||
authHeader := r.Header.Get("Authorization")
|
authHeader := r.Header.Get("Authorization")
|
||||||
@@ -336,9 +331,6 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inject identity headers for downstream services
|
|
||||||
identity.Inject(r, claims)
|
|
||||||
|
|
||||||
// Check required capability if configured
|
// Check required capability if configured
|
||||||
if h.config.Auth.RequiredCapability != "" {
|
if h.config.Auth.RequiredCapability != "" {
|
||||||
if !h.jwtValidator.CheckPermissions(claims, h.config.Auth.RequiredCapability, "*") {
|
if !h.jwtValidator.CheckPermissions(claims, h.config.Auth.RequiredCapability, "*") {
|
||||||
|
|||||||
@@ -14,31 +14,42 @@ import (
|
|||||||
"google.golang.org/grpc/credentials/insecure"
|
"google.golang.org/grpc/credentials/insecure"
|
||||||
|
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/auth"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/auth"
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/identity"
|
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/problem"
|
"forgejo.riotpiao.com/rock/homelab-frontend/internal/problem"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Dispatcher routes X-Service requests to upstreams.
|
// Dispatcher routes X-Service requests to upstreams.
|
||||||
|
// Auth per service:
|
||||||
|
// SQS: Gateway validates JWT (kmsvc code unverified)
|
||||||
|
// MinIO, Temporal: Native JWT support (dumb pipe pass-through)
|
||||||
|
// Memory, IAM: Services validate JWTs themselves
|
||||||
type Dispatcher struct {
|
type Dispatcher struct {
|
||||||
registry *Registry
|
registry *Registry
|
||||||
jwtValidator *auth.Validator
|
sqsJWTAuth *auth.Validator
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewDispatcher creates a dispatcher with a shared multi-issuer JWT validator.
|
// NewDispatcher creates a new service adapter dispatcher.
|
||||||
// Pass nil to disable auth enforcement (all requests pass through).
|
func NewDispatcher(registry *Registry) *Dispatcher {
|
||||||
func NewDispatcher(registry *Registry, jwtValidator *auth.Validator) *Dispatcher {
|
// Create JWT validator for SQS
|
||||||
|
// Issuer and JWKS URL should match Authentik application config
|
||||||
|
sqsValidator := auth.NewValidator(
|
||||||
|
"https://authentik.riotpiao.com/application/o/sqs/",
|
||||||
|
"sqs",
|
||||||
|
"https://authentik.riotpiao.com/application/o/sqs/jwks/",
|
||||||
|
)
|
||||||
|
|
||||||
return &Dispatcher{
|
return &Dispatcher{
|
||||||
registry: registry,
|
registry: registry,
|
||||||
jwtValidator: jwtValidator,
|
sqsJWTAuth: sqsValidator,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Matches returns true if the request has an X-Service header.
|
// Matches returns true if the request should be dispatched based on X-Service header.
|
||||||
func (d *Dispatcher) Matches(r *http.Request) bool {
|
func (d *Dispatcher) Matches(r *http.Request) bool {
|
||||||
return r.Header.Get("X-Service") != ""
|
return r.Header.Get("X-Service") != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dispatch routes a request to the appropriate adapter.
|
// Dispatch routes a request to the appropriate adapter.
|
||||||
|
// Returns a problem document if the adapter or resource is not found.
|
||||||
func (d *Dispatcher) Dispatch(w http.ResponseWriter, r *http.Request) {
|
func (d *Dispatcher) Dispatch(w http.ResponseWriter, r *http.Request) {
|
||||||
serviceName := r.Header.Get("X-Service")
|
serviceName := r.Header.Get("X-Service")
|
||||||
if serviceName == "" {
|
if serviceName == "" {
|
||||||
@@ -46,117 +57,102 @@ func (d *Dispatcher) Dispatch(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Look up service adapter
|
||||||
adapter := d.registry.Get(serviceName)
|
adapter := d.registry.Get(serviceName)
|
||||||
if adapter == nil {
|
if adapter == nil {
|
||||||
d.writeError(w, problem.NotFound(fmt.Sprintf("service '%s' not found", serviceName)))
|
p := problem.NotFound(fmt.Sprintf("service '%s' not found", serviceName))
|
||||||
|
_ = p.Write(w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get resource and method from request
|
||||||
resourceName := r.Header.Get("X-Resource")
|
resourceName := r.Header.Get("X-Resource")
|
||||||
if resourceName == "" {
|
if resourceName == "" {
|
||||||
d.writeError(w, problem.BadRequest("X-Resource header required"))
|
d.writeError(w, problem.BadRequest("X-Resource header required"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
resource := findResource(adapter, resourceName)
|
// Find resource
|
||||||
|
var resource *Resource
|
||||||
|
for i := range adapter.Spec.Resources {
|
||||||
|
if adapter.Spec.Resources[i].Name == resourceName {
|
||||||
|
resource = &adapter.Spec.Resources[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if resource == nil {
|
if resource == nil {
|
||||||
d.writeError(w, problem.NotFound(
|
p := problem.NotFound(fmt.Sprintf("resource '%s' not found in service '%s'", resourceName, serviceName))
|
||||||
fmt.Sprintf("resource '%s' not found in service '%s'", resourceName, serviceName)))
|
_ = p.Write(w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
method := findMethod(resource, r.Method)
|
// Find method matching HTTP verb
|
||||||
|
var method *Method
|
||||||
|
for i := range resource.Methods {
|
||||||
|
if resource.Methods[i].Verb == r.Method {
|
||||||
|
method = &resource.Methods[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if method == nil {
|
if method == nil {
|
||||||
d.writeError(w, problem.NotFound(
|
p := problem.NotFound(fmt.Sprintf("method %s not defined for resource '%s'", r.Method, resourceName))
|
||||||
fmt.Sprintf("method %s not defined for resource '%s'", r.Method, resourceName)))
|
_ = p.Write(w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// JWT auth enforcement for adapters that require it
|
// Gateway-level JWT validation for SQS (code unverified in kmsvc)
|
||||||
if adapter.Spec.Auth.Required && d.jwtValidator != nil {
|
// MinIO, Temporal, Memory, IAM have native JWT support - pass through
|
||||||
if !d.authenticate(w, r, serviceName, method.Verb) {
|
if adapter.Spec.Auth.Required && serviceName == "sqs" {
|
||||||
|
authHeader := r.Header.Get("Authorization")
|
||||||
|
if authHeader == "" {
|
||||||
|
p := problem.NewProblem(http.StatusForbidden, "about:blank#forbidden",
|
||||||
|
"Forbidden", "SQS requires Authorization header")
|
||||||
|
_ = p.Write(w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate JWT signature against Authentik JWKS
|
||||||
|
claims, err := d.sqsJWTAuth.ValidateBearerToken(authHeader)
|
||||||
|
if err != nil {
|
||||||
|
p := problem.NewProblem(http.StatusForbidden, "about:blank#forbidden",
|
||||||
|
"Forbidden", fmt.Sprintf("JWT validation failed: %v", err))
|
||||||
|
_ = p.Write(w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check required permissions (sqs:read or sqs:write or *)
|
||||||
|
hasPermission := d.sqsJWTAuth.CheckPermissions(claims, "sqs:read", "sqs:write", "*")
|
||||||
|
if !hasPermission {
|
||||||
|
p := problem.NewProblem(http.StatusForbidden, "about:blank#forbidden",
|
||||||
|
"Forbidden", "Insufficient permissions for SQS")
|
||||||
|
_ = p.Write(w)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Detect protocol from upstream URL scheme
|
||||||
upstreamURL := adapter.Spec.Upstream.URL
|
upstreamURL := adapter.Spec.Upstream.URL
|
||||||
if strings.HasPrefix(upstreamURL, "grpc://") {
|
if strings.HasPrefix(upstreamURL, "grpc://") {
|
||||||
|
// gRPC upstream (Temporal, etc.)
|
||||||
d.dispatchGRPC(w, r, upstreamURL, method, adapter)
|
d.dispatchGRPC(w, r, upstreamURL, method, adapter)
|
||||||
} else {
|
} else {
|
||||||
|
// HTTP upstream (MinIO, Authentik, etc.)
|
||||||
d.dispatchHTTP(w, r, upstreamURL, method, adapter)
|
d.dispatchHTTP(w, r, upstreamURL, method, adapter)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// authenticate validates the JWT and checks service-level capability.
|
// dispatchHTTP forwards HTTP requests to upstream, passing Authorization header through.
|
||||||
// Returns false (and writes error response) if auth fails.
|
|
||||||
func (d *Dispatcher) authenticate(w http.ResponseWriter, r *http.Request, serviceName, verb string) bool {
|
|
||||||
authHeader := r.Header.Get("Authorization")
|
|
||||||
if authHeader == "" {
|
|
||||||
d.writeError(w, problem.NewProblem(http.StatusUnauthorized,
|
|
||||||
"about:blank#unauthorized", "Unauthorized",
|
|
||||||
fmt.Sprintf("service '%s' requires Authorization header", serviceName)))
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := d.jwtValidator.ValidateBearerToken(authHeader)
|
|
||||||
if err != nil {
|
|
||||||
d.writeError(w, problem.NewProblem(http.StatusForbidden,
|
|
||||||
"about:blank#forbidden", "Forbidden",
|
|
||||||
fmt.Sprintf("JWT validation failed: %v", err)))
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check capability: <service>:read for GET/HEAD, <service>:write for mutating verbs
|
|
||||||
required := capabilityForVerb(serviceName, verb)
|
|
||||||
if !d.jwtValidator.CheckPermissions(claims, required, "*") {
|
|
||||||
d.writeError(w, problem.NewProblem(http.StatusForbidden,
|
|
||||||
"about:blank#insufficient-permissions", "Insufficient Permissions",
|
|
||||||
fmt.Sprintf("required capability: %s", required)))
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inject identity headers for downstream
|
|
||||||
identity.Inject(r, claims)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// capabilityForVerb maps HTTP verbs to <service>:read or <service>:write.
|
|
||||||
func capabilityForVerb(serviceName, verb string) string {
|
|
||||||
switch verb {
|
|
||||||
case "GET", "HEAD", "OPTIONS":
|
|
||||||
return serviceName + ":read"
|
|
||||||
default:
|
|
||||||
return serviceName + ":write"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func findResource(adapter *ServiceAdapter, name string) *Resource {
|
|
||||||
for i := range adapter.Spec.Resources {
|
|
||||||
if adapter.Spec.Resources[i].Name == name {
|
|
||||||
return &adapter.Spec.Resources[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func findMethod(resource *Resource, verb string) *Method {
|
|
||||||
for i := range resource.Methods {
|
|
||||||
if resource.Methods[i].Verb == verb {
|
|
||||||
return &resource.Methods[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Dispatcher) dispatchHTTP(w http.ResponseWriter, r *http.Request, upstreamURL string, method *Method, adapter *ServiceAdapter) {
|
func (d *Dispatcher) dispatchHTTP(w http.ResponseWriter, r *http.Request, upstreamURL string, method *Method, adapter *ServiceAdapter) {
|
||||||
parsedURL, err := url.Parse(upstreamURL)
|
parsedURL, err := url.Parse(upstreamURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
d.writeError(w, problem.NewProblem(http.StatusInternalServerError,
|
d.writeError(w, problem.NewProblem(http.StatusInternalServerError, "about:blank#server-error",
|
||||||
"about:blank#server-error", "Internal Server Error",
|
"Internal Server Error", fmt.Sprintf("invalid upstream URL: %v", err)))
|
||||||
fmt.Sprintf("invalid upstream URL: %v", err)))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create reverse proxy
|
||||||
proxy := httputil.NewSingleHostReverseProxy(parsedURL)
|
proxy := httputil.NewSingleHostReverseProxy(parsedURL)
|
||||||
proxy.Director = func(req *http.Request) {
|
proxy.Director = func(req *http.Request) {
|
||||||
req.URL.Scheme = parsedURL.Scheme
|
req.URL.Scheme = parsedURL.Scheme
|
||||||
@@ -164,36 +160,42 @@ func (d *Dispatcher) dispatchHTTP(w http.ResponseWriter, r *http.Request, upstre
|
|||||||
req.URL.Path = method.UpstreamPath
|
req.URL.Path = method.UpstreamPath
|
||||||
req.RequestURI = ""
|
req.RequestURI = ""
|
||||||
req.Host = parsedURL.Host
|
req.Host = parsedURL.Host
|
||||||
|
// Authorization header passes through unchanged
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Set timeout
|
||||||
timeout := adapter.Spec.Upstream.TimeoutSeconds
|
timeout := adapter.Spec.Upstream.TimeoutSeconds
|
||||||
if timeout <= 0 {
|
if timeout <= 0 {
|
||||||
timeout = 30
|
timeout = 30
|
||||||
}
|
}
|
||||||
proxy.Transport = &http.Transport{
|
proxy.Transport = &http.Transport{
|
||||||
DialContext: (&net.Dialer{Timeout: time.Duration(timeout) * time.Second}).DialContext,
|
DialContext: (&net.Dialer{Timeout: time.Duration(timeout) * time.Second}).DialContext,
|
||||||
TLSHandshakeTimeout: time.Duration(timeout) * time.Second,
|
TLSHandshakeTimeout: time.Duration(timeout) * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Forward the request
|
||||||
proxy.ServeHTTP(w, r)
|
proxy.ServeHTTP(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dispatchGRPC forwards gRPC requests to upstream.
|
||||||
|
// gRPC URL format: grpc://host:port
|
||||||
func (d *Dispatcher) dispatchGRPC(w http.ResponseWriter, r *http.Request, upstreamURL string, method *Method, adapter *ServiceAdapter) {
|
func (d *Dispatcher) dispatchGRPC(w http.ResponseWriter, r *http.Request, upstreamURL string, method *Method, adapter *ServiceAdapter) {
|
||||||
|
// Extract host:port from grpc://host:port
|
||||||
host := strings.TrimPrefix(upstreamURL, "grpc://")
|
host := strings.TrimPrefix(upstreamURL, "grpc://")
|
||||||
if host == upstreamURL {
|
if host == upstreamURL {
|
||||||
d.writeError(w, problem.NewProblem(http.StatusInternalServerError,
|
d.writeError(w, problem.NewProblem(http.StatusInternalServerError, "about:blank#server-error",
|
||||||
"about:blank#server-error", "Internal Server Error",
|
"Internal Server Error", "invalid gRPC URL format"))
|
||||||
"invalid gRPC URL format"))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate that this is a gRPC request
|
||||||
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc") {
|
if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc") {
|
||||||
d.writeError(w, problem.NewProblem(http.StatusBadRequest,
|
d.writeError(w, problem.NewProblem(http.StatusBadRequest, "about:blank#bad-request",
|
||||||
"about:blank#bad-request", "Bad Request",
|
"Bad Request", "gRPC service requires application/grpc content-type"))
|
||||||
"gRPC service requires application/grpc content-type"))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Set timeout
|
||||||
timeout := adapter.Spec.Upstream.TimeoutSeconds
|
timeout := adapter.Spec.Upstream.TimeoutSeconds
|
||||||
if timeout <= 0 {
|
if timeout <= 0 {
|
||||||
timeout = 30
|
timeout = 30
|
||||||
@@ -202,21 +204,25 @@ func (d *Dispatcher) dispatchGRPC(w http.ResponseWriter, r *http.Request, upstre
|
|||||||
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(timeout)*time.Second)
|
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(timeout)*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
|
// Dial gRPC upstream
|
||||||
conn, err := grpc.DialContext(ctx, host,
|
conn, err := grpc.DialContext(ctx, host,
|
||||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||||
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(100*1024*1024)),
|
grpc.WithDefaultCallOptions(
|
||||||
|
grpc.MaxCallRecvMsgSize(100 * 1024 * 1024), // 100MB
|
||||||
|
),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
d.writeError(w, problem.NewProblem(http.StatusBadGateway,
|
d.writeError(w, problem.NewProblem(http.StatusBadGateway, "about:blank#bad-gateway",
|
||||||
"about:blank#bad-gateway", "Bad Gateway",
|
"Bad Gateway", fmt.Sprintf("failed to dial gRPC upstream: %v", err)))
|
||||||
fmt.Sprintf("failed to dial gRPC upstream: %v", err)))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
|
|
||||||
d.writeError(w, problem.NewProblem(http.StatusNotImplemented,
|
// Forward gRPC request
|
||||||
"about:blank#not-implemented", "Not Implemented",
|
// Note: Full gRPC forwarding requires grpcproxy or custom middleware.
|
||||||
"gRPC forwarding not yet implemented"))
|
// For now, return unimplemented (Temporal support coming in Phase 9)
|
||||||
|
d.writeError(w, problem.NewProblem(http.StatusNotImplemented, "about:blank#not-implemented",
|
||||||
|
"Not Implemented", "gRPC forwarding not yet implemented - use in-cluster gRPC clients directly"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Dispatcher) writeError(w http.ResponseWriter, p *problem.Problem) {
|
func (d *Dispatcher) writeError(w http.ResponseWriter, p *problem.Problem) {
|
||||||
|
|||||||
@@ -1,265 +0,0 @@
|
|||||||
package serviceadapter
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"forgejo.riotpiao.com/rock/homelab-frontend/internal/identity"
|
|
||||||
)
|
|
||||||
|
|
||||||
// stubValidator implements the minimum interface for testing auth.
|
|
||||||
// Real auth.Validator needs JWKS — we test the dispatcher logic, not JWT crypto.
|
|
||||||
|
|
||||||
func newTestRegistry(adapters ...ServiceAdapter) *Registry {
|
|
||||||
r := NewRegistry(nil)
|
|
||||||
for i := range adapters {
|
|
||||||
_ = r.Add(&adapters[i])
|
|
||||||
}
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func sqsAdapter(authRequired bool) ServiceAdapter {
|
|
||||||
return ServiceAdapter{
|
|
||||||
Name: "sqs",
|
|
||||||
ServiceName: "sqs",
|
|
||||||
Spec: Spec{
|
|
||||||
ServiceName: "sqs",
|
|
||||||
Upstream: Upstream{URL: "http://localhost:9999", TimeoutSeconds: 5},
|
|
||||||
Auth: Auth{Required: authRequired},
|
|
||||||
Resources: []Resource{
|
|
||||||
{
|
|
||||||
Name: "list-queues",
|
|
||||||
Methods: []Method{
|
|
||||||
{Verb: "GET", UpstreamPath: "/sqs/queues"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Name: "send-message",
|
|
||||||
Methods: []Method{
|
|
||||||
{Verb: "POST", UpstreamPath: "/sqs/send"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func memoryAdapter() ServiceAdapter {
|
|
||||||
return ServiceAdapter{
|
|
||||||
Name: "memory",
|
|
||||||
ServiceName: "memory",
|
|
||||||
Spec: Spec{
|
|
||||||
ServiceName: "memory",
|
|
||||||
Upstream: Upstream{URL: "http://localhost:8888", TimeoutSeconds: 5},
|
|
||||||
Auth: Auth{Required: false},
|
|
||||||
Resources: []Resource{
|
|
||||||
{
|
|
||||||
Name: "skills",
|
|
||||||
Methods: []Method{
|
|
||||||
{Verb: "GET", UpstreamPath: "/memory/skills"},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_MissingXService(t *testing.T) {
|
|
||||||
d := NewDispatcher(newTestRegistry(), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
if w.Code != http.StatusBadRequest {
|
|
||||||
t.Errorf("expected 400, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_UnknownService(t *testing.T) {
|
|
||||||
d := NewDispatcher(newTestRegistry(), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set("X-Service", "nonexistent")
|
|
||||||
r.Header.Set("X-Resource", "foo")
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
if w.Code != http.StatusNotFound {
|
|
||||||
t.Errorf("expected 404, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_MissingXResource(t *testing.T) {
|
|
||||||
d := NewDispatcher(newTestRegistry(memoryAdapter()), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set("X-Service", "memory")
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
if w.Code != http.StatusBadRequest {
|
|
||||||
t.Errorf("expected 400, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_UnknownResource(t *testing.T) {
|
|
||||||
d := NewDispatcher(newTestRegistry(memoryAdapter()), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set("X-Service", "memory")
|
|
||||||
r.Header.Set("X-Resource", "nonexistent")
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
if w.Code != http.StatusNotFound {
|
|
||||||
t.Errorf("expected 404, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_WrongHTTPVerb(t *testing.T) {
|
|
||||||
d := NewDispatcher(newTestRegistry(memoryAdapter()), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("DELETE", "/", nil)
|
|
||||||
r.Header.Set("X-Service", "memory")
|
|
||||||
r.Header.Set("X-Resource", "skills")
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
if w.Code != http.StatusNotFound {
|
|
||||||
t.Errorf("expected 404, got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_AuthRequired_NoToken(t *testing.T) {
|
|
||||||
// Use nil validator — auth required but no validator means 401
|
|
||||||
// Actually with nil validator, auth is skipped. Use a real scenario.
|
|
||||||
// We need a mock validator. For now test that auth.Required=false passes through.
|
|
||||||
// The real auth test needs the full JWKS setup which is an integration test.
|
|
||||||
|
|
||||||
// Test: auth required, no validator configured = passes through (defense in depth via NetworkPolicy)
|
|
||||||
d := NewDispatcher(newTestRegistry(sqsAdapter(true)), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set("X-Service", "sqs")
|
|
||||||
r.Header.Set("X-Resource", "list-queues")
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
// With nil validator, auth check is skipped — request reaches upstream (which will fail since localhost:9999 is down)
|
|
||||||
// The key assertion: it did NOT return 401/403, it tried to proxy
|
|
||||||
if w.Code == http.StatusUnauthorized || w.Code == http.StatusForbidden {
|
|
||||||
t.Errorf("expected proxy attempt (not auth rejection), got %d", w.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_AuthNotRequired_NoToken(t *testing.T) {
|
|
||||||
// Start a test upstream
|
|
||||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
json.NewEncoder(w).Encode(map[string]string{"path": r.URL.Path})
|
|
||||||
}))
|
|
||||||
defer upstream.Close()
|
|
||||||
|
|
||||||
adapter := memoryAdapter()
|
|
||||||
adapter.Spec.Upstream.URL = upstream.URL
|
|
||||||
|
|
||||||
d := NewDispatcher(newTestRegistry(adapter), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set("X-Service", "memory")
|
|
||||||
r.Header.Set("X-Resource", "skills")
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
if w.Code != http.StatusOK {
|
|
||||||
t.Errorf("expected 200, got %d", w.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
var body map[string]string
|
|
||||||
json.NewDecoder(w.Body).Decode(&body)
|
|
||||||
if body["path"] != "/memory/skills" {
|
|
||||||
t.Errorf("expected upstream path /memory/skills, got %s", body["path"])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_PassThroughHeaders(t *testing.T) {
|
|
||||||
var receivedAuth string
|
|
||||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
receivedAuth = r.Header.Get("Authorization")
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer upstream.Close()
|
|
||||||
|
|
||||||
adapter := memoryAdapter()
|
|
||||||
adapter.Spec.Upstream.URL = upstream.URL
|
|
||||||
|
|
||||||
d := NewDispatcher(newTestRegistry(adapter), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set("X-Service", "memory")
|
|
||||||
r.Header.Set("X-Resource", "skills")
|
|
||||||
r.Header.Set("Authorization", "Bearer some-jwt")
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
if receivedAuth != "Bearer some-jwt" {
|
|
||||||
t.Errorf("Authorization header not passed through, got %q", receivedAuth)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCapabilityForVerb(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
service string
|
|
||||||
verb string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{"sqs", "GET", "sqs:read"},
|
|
||||||
{"sqs", "HEAD", "sqs:read"},
|
|
||||||
{"sqs", "OPTIONS", "sqs:read"},
|
|
||||||
{"sqs", "POST", "sqs:write"},
|
|
||||||
{"sqs", "PUT", "sqs:write"},
|
|
||||||
{"sqs", "DELETE", "sqs:write"},
|
|
||||||
{"sqs", "PATCH", "sqs:write"},
|
|
||||||
{"memory", "GET", "memory:read"},
|
|
||||||
{"memory", "POST", "memory:write"},
|
|
||||||
{"s3", "GET", "s3:read"},
|
|
||||||
{"s3", "PUT", "s3:write"},
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
got := capabilityForVerb(tt.service, tt.verb)
|
|
||||||
if got != tt.want {
|
|
||||||
t.Errorf("capabilityForVerb(%s, %s) = %s, want %s", tt.service, tt.verb, got, tt.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDispatch_IdentityHeadersNotSet_WhenNoAuth(t *testing.T) {
|
|
||||||
var gotUser, gotVerified string
|
|
||||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
gotUser = r.Header.Get(identity.HeaderUser)
|
|
||||||
gotVerified = r.Header.Get(identity.HeaderAuthVerified)
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer upstream.Close()
|
|
||||||
|
|
||||||
adapter := memoryAdapter()
|
|
||||||
adapter.Spec.Upstream.URL = upstream.URL
|
|
||||||
|
|
||||||
d := NewDispatcher(newTestRegistry(adapter), nil)
|
|
||||||
w := httptest.NewRecorder()
|
|
||||||
r := httptest.NewRequest("GET", "/", nil)
|
|
||||||
r.Header.Set("X-Service", "memory")
|
|
||||||
r.Header.Set("X-Resource", "skills")
|
|
||||||
|
|
||||||
d.Dispatch(w, r)
|
|
||||||
|
|
||||||
if gotUser != "" {
|
|
||||||
t.Errorf("X-Forwarded-User should not be set without auth, got %q", gotUser)
|
|
||||||
}
|
|
||||||
if gotVerified != "" {
|
|
||||||
t.Errorf("X-Auth-Verified should not be set without auth, got %q", gotVerified)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+1
-3
@@ -17,8 +17,6 @@ data:
|
|||||||
audience: "api-gw"
|
audience: "api-gw"
|
||||||
jwksUrl: "http://authentik-server.iam.svc.cluster.local/application/o/api-gw/jwks/"
|
jwksUrl: "http://authentik-server.iam.svc.cluster.local/application/o/api-gw/jwks/"
|
||||||
requiredCapability: "llm:inference"
|
requiredCapability: "llm:inference"
|
||||||
tokenUrl: "http://authentik-server.iam.svc.cluster.local/application/o/token/"
|
|
||||||
clientId: "api-gw"
|
|
||||||
|
|
||||||
# Routes: standard HTTP proxy routes (not LLM-specific)
|
# Routes: standard HTTP proxy routes (not LLM-specific)
|
||||||
# These are for non-LLM services (agent-pod/console, etc.)
|
# These are for non-LLM services (agent-pod/console, etc.)
|
||||||
@@ -115,7 +113,7 @@ data:
|
|||||||
|
|
||||||
- serviceName: s3
|
- serviceName: s3
|
||||||
upstream:
|
upstream:
|
||||||
url: http://minio.storage.svc.cluster.local:80
|
url: http://minio.storage.svc.cluster.local:9000
|
||||||
timeoutSeconds: 30
|
timeoutSeconds: 30
|
||||||
auth:
|
auth:
|
||||||
required: false
|
required: false
|
||||||
|
|||||||
@@ -57,12 +57,6 @@ spec:
|
|||||||
value: "0.0.0.0:8080"
|
value: "0.0.0.0:8080"
|
||||||
- name: CONFIG_PATH
|
- name: CONFIG_PATH
|
||||||
value: "/etc/gateway/config.yaml"
|
value: "/etc/gateway/config.yaml"
|
||||||
- name: AUTH_CLIENT_SECRET
|
|
||||||
valueFrom:
|
|
||||||
secretKeyRef:
|
|
||||||
name: api-gw-client-secret
|
|
||||||
key: client-secret
|
|
||||||
optional: true
|
|
||||||
- name: SHUTDOWN_TIMEOUT
|
- name: SHUTDOWN_TIMEOUT
|
||||||
value: "5m"
|
value: "5m"
|
||||||
- name: LOG_LEVEL
|
- name: LOG_LEVEL
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ stringData:
|
|||||||
audience: "api-gw"
|
audience: "api-gw"
|
||||||
jwksUrl: "http://authentik-server.iam.svc.cluster.local/application/o/api-gw/jwks/"
|
jwksUrl: "http://authentik-server.iam.svc.cluster.local/application/o/api-gw/jwks/"
|
||||||
requiredCapability: "llm:inference"
|
requiredCapability: "llm:inference"
|
||||||
tokenUrl: "http://authentik-server.iam.svc.cluster.local/application/o/token/"
|
|
||||||
clientId: "api-gw"
|
|
||||||
routes: []
|
routes: []
|
||||||
models:
|
models:
|
||||||
- name: "reasoning"
|
- name: "reasoning"
|
||||||
@@ -93,7 +91,7 @@ stringData:
|
|||||||
upstreamPath: /memory/skills
|
upstreamPath: /memory/skills
|
||||||
- serviceName: s3
|
- serviceName: s3
|
||||||
upstream:
|
upstream:
|
||||||
url: http://minio.storage.svc.cluster.local:80
|
url: http://minio.storage.svc.cluster.local:9000
|
||||||
timeoutSeconds: 30
|
timeoutSeconds: 30
|
||||||
auth:
|
auth:
|
||||||
required: false
|
required: false
|
||||||
|
|||||||
@@ -123,14 +123,10 @@ spec:
|
|||||||
- protocol: TCP
|
- protocol: TCP
|
||||||
port: 8080
|
port: 8080
|
||||||
# Allow to MinIO (S3-compatible storage)
|
# Allow to MinIO (S3-compatible storage)
|
||||||
# Service `minio` listens on port 80 (targetPort 9000).
|
|
||||||
# Headless `minio-cluster-hl` is 9000. Allow both.
|
|
||||||
- to:
|
- to:
|
||||||
- namespaceSelector:
|
- namespaceSelector:
|
||||||
matchLabels:
|
matchLabels:
|
||||||
kubernetes.io/metadata.name: storage
|
kubernetes.io/metadata.name: storage
|
||||||
ports:
|
ports:
|
||||||
- protocol: TCP
|
|
||||||
port: 80
|
|
||||||
- protocol: TCP
|
- protocol: TCP
|
||||||
port: 9000
|
port: 9000
|
||||||
|
|||||||
Reference in New Issue
Block a user