Skip to content

Modern Docker Management, Designed for Everyone

fix: null user_id for env bootstrap keys + H2 support for registry fetches (#2370)

Giulio Savinia50cd8c63645
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index ed171db17..ffb9f21bb 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -66,8 +66,16 @@ func createAuthValidator(appServices *Services) middleware.AuthValidator {
return func(ctx context.Context, c *gin.Context) bool {
// Check for API key authentication
if apiKey := c.GetHeader("X-API-Key"); apiKey != "" {
- user, err := appServices.ApiKey.ValidateApiKey(ctx, apiKey)
- return err == nil && user != nil
+ // User-owned API key
+ if user, err := appServices.ApiKey.ValidateApiKey(ctx, apiKey); err == nil && user != nil {
+ return true
+ }
+ // Environment bootstrap key (user_id = NULL): used by the proxy when forwarding
+ // requests to a remote env whose apiUrl resolves back to this manager.
+ if _, err := appServices.ApiKey.GetEnvironmentByApiKey(ctx, apiKey); err == nil {
+ return true
+ }
+ return false
}
// Check for Bearer token authentication
@@ -100,7 +108,9 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
Filters: []sloggin.Filter{shouldLogRequest},
}))
- authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).WithApiKeyValidator(appServices.ApiKey)
+ authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).
+ WithApiKeyValidator(appServices.ApiKey).
+ WithEnvironmentAccessTokenResolver(appServices.Environment)
corsMiddleware := middleware.NewCORSMiddleware(cfg).Add()
router.Use(corsMiddleware)
diff --git a/backend/internal/huma/handlers/dashboard_test.go b/backend/internal/huma/handlers/dashboard_test.go
index 6410e4d90..af2966fe1 100644
--- a/backend/internal/huma/handlers/dashboard_test.go
+++ b/backend/internal/huma/handlers/dashboard_test.go
@@ -105,7 +105,7 @@ func TestDashboardHandlerGetDashboardReturnsSnapshot(t *testing.T) {
Name: "expiring-soon",
KeyHash: "hash-soon",
KeyPrefix: "arc_test_handler",
- UserID: "user-1",
+ UserID: new("user-1"),
ExpiresAt: new(time.Now().Add(12 * time.Hour)),
}).Error)
diff --git a/backend/internal/huma/handlers/templates_test.go b/backend/internal/huma/handlers/templates_test.go
index 51b132ccc..59b615b51 100644
--- a/backend/internal/huma/handlers/templates_test.go
+++ b/backend/internal/huma/handlers/templates_test.go
@@ -158,7 +158,7 @@ func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *gin.Engi
}
api := humagin.NewWithGroup(router, apiGroup, humaConfig)
- api.UseMiddleware(humamiddleware.NewAuthBridge(api, authService, nil, &config.Config{}))
+ api.UseMiddleware(humamiddleware.NewAuthBridge(api, authService, nil, nil, &config.Config{}))
RegisterHealth(api)
RegisterTemplates(api, templateService, nil)
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
index ce58f405a..f414bf3df 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/internal/huma/huma.go
@@ -223,7 +223,7 @@ func SetupAPI(router *gin.Engine, apiGroup *gin.RouterGroup, cfg *config.Config,
api := humagin.NewWithGroup(router, apiGroup, humaConfig)
// Add authentication middleware
- api.UseMiddleware(middleware.NewAuthBridge(api, svc.Auth, svc.ApiKey, cfg))
+ api.UseMiddleware(middleware.NewAuthBridge(api, svc.Auth, svc.ApiKey, svc.Environment, cfg))
// Register all Huma handlers
registerHandlers(api, svc)
diff --git a/backend/internal/huma/middleware/auth.go b/backend/internal/huma/middleware/auth.go
index 020dffaa3..8b4fe61d7 100644
--- a/backend/internal/huma/middleware/auth.go
+++ b/backend/internal/huma/middleware/auth.go
@@ -60,6 +60,10 @@ type operationProvider interface {
Operation() *huma.Operation
}
+type environmentAccessTokenResolver interface {
+ ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*models.Environment, error)
+}
+
// parseSecurityRequirementsInternal extracts security requirements from a Huma operation.
func parseSecurityRequirementsInternal(api huma.API, ctx operationProvider) securityRequirements {
reqs := securityRequirements{}
@@ -122,6 +126,19 @@ func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *services.ApiKeyServi
return user, true
}
+func tryEnvironmentAccessTokenAuth(ctx huma.Context, resolver environmentAccessTokenResolver, token string) (*models.User, bool) {
+ if resolver == nil || strings.TrimSpace(token) == "" {
+ return nil, false
+ }
+
+ env, err := resolver.ResolveEnvironmentByAccessToken(ctx.Context(), token)
+ if err != nil || env == nil {
+ return nil, false
+ }
+
+ return createEnvironmentSudoUser(env), true
+}
+
// tryAgentAuthInternal checks if the request is from an authenticated agent.
// Returns a sudo agent user if the agent token is valid.
func tryAgentAuthInternal(ctx huma.Context, cfg *config.Config) (*models.User, bool) {
@@ -157,13 +174,22 @@ func createAgentSudoUserInternal() *models.User {
return &models.User{
BaseModel: models.BaseModel{ID: "agent"},
Email: new(email),
+ Username: "agent",
+ Roles: []string{"admin"},
+ }
+}
+
+func createEnvironmentSudoUser(env *models.Environment) *models.User {
+ return &models.User{
+ BaseModel: models.BaseModel{ID: "environment:" + env.ID},
+ Username: env.Name,
Roles: []string{"admin"},
}
}
// NewAuthBridge creates a Huma middleware that validates JWT tokens and
// enforces security requirements defined on operations.
-func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyService *services.ApiKeyService, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {
+func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyService *services.ApiKeyService, envTokenResolver environmentAccessTokenResolver, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
if authService == nil {
next(ctx)
@@ -195,11 +221,24 @@ func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyServic
next(ctx)
return
}
+ if user, ok := tryEnvironmentAccessTokenAuth(ctx, envTokenResolver, ctx.Header(headerApiKey)); ok {
+ newCtx := setUserInContextInternal(ctx.Context(), user)
+ ctx = huma.WithContext(ctx, newCtx)
+ next(ctx)
+ return
+ }
// API key was present but invalid. Fail immediately.
_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized: invalid API key")
return
}
+ if user, ok := tryEnvironmentAccessTokenAuth(ctx, envTokenResolver, ctx.Header(headerAgentToken)); ok {
+ newCtx := setUserInContextInternal(ctx.Context(), user)
+ ctx = huma.WithContext(ctx, newCtx)
+ next(ctx)
+ return
+ }
+
if reqs.bearerAuth {
if user, ok := tryBearerAuthInternal(ctx, authService); ok {
newCtx := setUserInContextInternal(ctx.Context(), user)
diff --git a/backend/internal/huma/middleware/auth_test.go b/backend/internal/huma/middleware/auth_test.go
index 0fa693926..256ad04cd 100644
--- a/backend/internal/huma/middleware/auth_test.go
+++ b/backend/internal/huma/middleware/auth_test.go
@@ -1,14 +1,90 @@
package middleware
import (
+ "context"
+ "net/http"
+ "net/http/httptest"
"testing"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humagin"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
+type secureInput struct{}
+
+type secureOutput struct {
+ Body struct {
+ UserID string `json:"userId"`
+ } `json:"body"`
+}
+
+type testEnvironmentAccessResolver struct {
+ env *models.Environment
+}
+
+func (r testEnvironmentAccessResolver) ResolveEnvironmentByAccessToken(_ context.Context, token string) (*models.Environment, error) {
+ if r.env != nil && r.env.AccessToken != nil && *r.env.AccessToken == token {
+ return r.env, nil
+ }
+ return nil, context.Canceled
+}
+
+func TestNewAuthBridge_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ token := "env-access-token"
+ router := gin.New()
+ apiGroup := router.Group("/api")
+
+ humaConfig := huma.DefaultConfig("test", "1.0.0")
+ humaConfig.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
+ "ApiKeyAuth": {
+ Type: "apiKey",
+ In: "header",
+ Name: "X-API-Key",
+ },
+ }
+
+ api := humagin.NewWithGroup(router, apiGroup, humaConfig)
+ api.UseMiddleware(NewAuthBridge(api, &services.AuthService{}, nil, testEnvironmentAccessResolver{
+ env: &models.Environment{
+ BaseModel: models.BaseModel{ID: "env-self"},
+ Name: "Self Target",
+ AccessToken: &token,
+ },
+ }, &config.Config{}))
+
+ huma.Register(api, huma.Operation{
+ OperationID: "secure",
+ Method: http.MethodGet,
+ Path: "/secure",
+ Security: []map[string][]string{{"ApiKeyAuth": {}}},
+ }, func(ctx context.Context, _ *secureInput) (*secureOutput, error) {
+ user, ok := GetCurrentUserFromContext(ctx)
+ require.True(t, ok)
+ require.Equal(t, "environment:env-self", user.ID)
+ require.Equal(t, "Self Target", user.Username)
+
+ resp := &secureOutput{}
+ resp.Body.UserID = user.ID
+ return resp, nil
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/api/secure", nil)
+ req.Header.Set("X-API-Key", token)
+ rec := httptest.NewRecorder()
+
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Contains(t, rec.Body.String(), "environment:env-self")
+}
+
type testOperationProvider struct {
operation *huma.Operation
}
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index 8714c2142..06455a37c 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -31,11 +31,16 @@ type ApiKeyValidator interface {
ValidateApiKey(ctx context.Context, rawKey string) (*models.User, error)
}
+type EnvironmentAccessTokenResolver interface {
+ ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*models.Environment, error)
+}
+
type AuthMiddleware struct {
- authService *services.AuthService
- apiKeyValidator ApiKeyValidator
- cfg *config.Config
- options AuthOptions
+ authService *services.AuthService
+ apiKeyValidator ApiKeyValidator
+ envTokenResolver EnvironmentAccessTokenResolver
+ cfg *config.Config
+ options AuthOptions
}
func NewAuthMiddleware(authService *services.AuthService, cfg *config.Config) *AuthMiddleware {
@@ -52,6 +57,12 @@ func (m *AuthMiddleware) WithApiKeyValidator(validator ApiKeyValidator) *AuthMid
return &clone
}
+func (m *AuthMiddleware) WithEnvironmentAccessTokenResolver(resolver EnvironmentAccessTokenResolver) *AuthMiddleware {
+ clone := *m
+ clone.envTokenResolver = resolver
+ return &clone
+}
+
func (m *AuthMiddleware) WithAdminNotRequired() *AuthMiddleware {
clone := *m
clone.options.AdminRequired = false
@@ -108,24 +119,37 @@ func (m *AuthMiddleware) agentAuth(ctx context.Context, c *gin.Context) {
}
func (m *AuthMiddleware) managerAuth(ctx context.Context, c *gin.Context) {
+ if agentToken := c.GetHeader(headerAgentToken); agentToken != "" {
+ if env, ok := m.resolveEnvironmentAccessToken(ctx, agentToken); ok {
+ environmentSudo(c, env)
+ return
+ }
+ }
+
// First, check for API key in X-API-Key header
- if apiKey := c.GetHeader(headerApiKey); apiKey != "" && m.apiKeyValidator != nil {
- user, err := m.apiKeyValidator.ValidateApiKey(ctx, apiKey)
- if err == nil && user != nil {
- isAdmin := pkgutils.UserHasRole(user.Roles, "admin")
- if m.options.AdminRequired && !isAdmin {
- c.JSON(http.StatusForbidden, models.APIError{
- Code: "FORBIDDEN",
- Message: "You don't have permission to access this resource",
- })
- c.Abort()
+ if apiKey := c.GetHeader(headerApiKey); apiKey != "" {
+ if m.apiKeyValidator != nil {
+ user, err := m.apiKeyValidator.ValidateApiKey(ctx, apiKey)
+ if err == nil && user != nil {
+ isAdmin := pkgutils.UserHasRole(user.Roles, "admin")
+ if m.options.AdminRequired && !isAdmin {
+ c.JSON(http.StatusForbidden, models.APIError{
+ Code: "FORBIDDEN",
+ Message: "You don't have permission to access this resource",
+ })
+ c.Abort()
+ return
+ }
+ c.Set("userID", user.ID)
+ c.Set("currentUser", user)
+ c.Set("userIsAdmin", isAdmin)
+ c.Set("authMethod", "api_key")
+ c.Next()
return
}
- c.Set("userID", user.ID)
- c.Set("currentUser", user)
- c.Set("userIsAdmin", isAdmin)
- c.Set("authMethod", "api_key")
- c.Next()
+ }
+ if env, ok := m.resolveEnvironmentAccessToken(ctx, apiKey); ok {
+ environmentSudo(c, env)
return
}
// If API key validation fails, return unauthorized
@@ -191,6 +215,19 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c *gin.Context) {
c.Next()
}
+func (m *AuthMiddleware) resolveEnvironmentAccessToken(ctx context.Context, token string) (*models.Environment, bool) {
+ if m.envTokenResolver == nil {
+ return nil, false
+ }
+
+ env, err := m.envTokenResolver.ResolveEnvironmentByAccessToken(ctx, token)
+ if err != nil || env == nil {
+ return nil, false
+ }
+
+ return env, true
+}
+
func isPreflight(c *gin.Context) bool {
return c.Request.Method == http.MethodOptions
}
@@ -199,11 +236,26 @@ func agentSudo(c *gin.Context) {
agentUser := &models.User{
BaseModel: models.BaseModel{ID: "agent"},
Email: new("[email protected]"),
+ Username: "agent",
Roles: []string{"admin"},
}
c.Set("userID", agentUser.ID)
c.Set("currentUser", agentUser)
c.Set("userIsAdmin", true)
+ c.Set("authMethod", "agent_token")
+ c.Next()
+}
+
+func environmentSudo(c *gin.Context, env *models.Environment) {
+ envUser := &models.User{
+ BaseModel: models.BaseModel{ID: "environment:" + env.ID},
+ Username: env.Name,
+ Roles: []string{"admin"},
+ }
+ c.Set("userID", envUser.ID)
+ c.Set("currentUser", envUser)
+ c.Set("userIsAdmin", true)
+ c.Set("authMethod", "environment_access_token")
c.Next()
}
diff --git a/backend/internal/middleware/auth_middleware_test.go b/backend/internal/middleware/auth_middleware_test.go
new file mode 100644
index 000000000..5509e9409
--- /dev/null
+++ b/backend/internal/middleware/auth_middleware_test.go
@@ -0,0 +1,65 @@
+package middleware
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type testEnvironmentTokenResolver struct {
+ env *models.Environment
+}
+
+func (r testEnvironmentTokenResolver) ResolveEnvironmentByAccessToken(_ context.Context, token string) (*models.Environment, error) {
+ if r.env != nil && r.env.AccessToken != nil && *r.env.AccessToken == token {
+ return r.env, nil
+ }
+ return nil, ErrInvalidEnvironmentAccessTokenForTest
+}
+
+var ErrInvalidEnvironmentAccessTokenForTest = context.Canceled
+
+func TestAuthMiddleware_ManagerAuthAcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ token := "env-access-token"
+ router := gin.New()
+ router.Use(
+ NewAuthMiddleware(nil, &config.Config{}).
+ WithEnvironmentAccessTokenResolver(testEnvironmentTokenResolver{
+ env: &models.Environment{
+ BaseModel: models.BaseModel{ID: "env-self"},
+ Name: "Self Target",
+ AccessToken: &token,
+ },
+ }).
+ Add(),
+ )
+ router.GET("/secure", func(c *gin.Context) {
+ currentUser, exists := c.Get("currentUser")
+ require.True(t, exists)
+
+ user, ok := currentUser.(*models.User)
+ require.True(t, ok)
+ require.Equal(t, "environment:env-self", user.ID)
+ require.Equal(t, "Self Target", user.Username)
+ require.Equal(t, "environment_access_token", c.GetString("authMethod"))
+
+ c.JSON(http.StatusOK, gin.H{"userId": user.ID})
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/secure", nil)
+ req.Header.Set("X-API-Key", token)
+ rec := httptest.NewRecorder()
+
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, http.StatusOK, rec.Code)
+ require.Contains(t, rec.Body.String(), "environment:env-self")
+}
diff --git a/backend/internal/models/api_key.go b/backend/internal/models/api_key.go
index 2f62629f2..861f96858 100644
--- a/backend/internal/models/api_key.go
+++ b/backend/internal/models/api_key.go
@@ -10,7 +10,7 @@ type ApiKey struct {
KeyHash string `json:"-" gorm:"column:key_hash;not null"`
KeyPrefix string `json:"keyPrefix" gorm:"column:key_prefix;not null"`
ManagedBy *string `json:"-" gorm:"column:managed_by"`
- UserID string `json:"userId" gorm:"column:user_id;not null"`
+ UserID *string `json:"userId,omitempty" gorm:"column:user_id"`
EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id"`
ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"column:last_used_at" sortable:"true"`
diff --git a/backend/internal/services/api_key_service.go b/backend/internal/services/api_key_service.go
index 9a2255207..6f655c26a 100644
--- a/backend/internal/services/api_key_service.go
+++ b/backend/internal/services/api_key_service.go
@@ -105,12 +105,12 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req api
return nil, err
}
- return s.createAPIKeyWithRawKey(ctx, userID, rawKey, req, nil, nil)
+ return s.createAPIKeyWithRawKey(ctx, &userID, rawKey, req, nil, nil)
}
func (s *ApiKeyService) createAPIKeyWithRawKey(
ctx context.Context,
- userID string,
+ userID *string,
rawKey string,
req apikey.CreateApiKey,
managedBy *string,
@@ -168,7 +168,7 @@ func toAPIKeyDTOInternal(ak *models.ApiKey) apikey.ApiKey {
}
func (s *ApiKeyService) CreateDefaultAdminAPIKey(ctx context.Context, userID, rawKey string) (*apikey.ApiKeyCreatedDto, error) {
- return s.createAPIKeyWithRawKey(ctx, userID, rawKey, apikey.CreateApiKey{
+ return s.createAPIKeyWithRawKey(ctx, &userID, rawKey, apikey.CreateApiKey{
Name: defaultAdminAPIKeyName,
Description: defaultAdminAPIKeyDescription,
}, new(managedByAdminBootstrap), nil)
@@ -258,7 +258,7 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, raw
KeyHash: keyHash,
KeyPrefix: keyPrefix,
ManagedBy: new(managedByAdminBootstrap),
- UserID: userID,
+ UserID: &userID,
}
if err := tx.Create(ak).Error; err != nil {
@@ -316,7 +316,7 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environment
envIDShort = environmentID[:8]
}
name := fmt.Sprintf("Environment Bootstrap Key - %s", envIDShort)
- return s.createAPIKeyWithRawKey(ctx, userID, rawKey, apikey.CreateApiKey{
+ return s.createAPIKeyWithRawKey(ctx, nil, rawKey, apikey.CreateApiKey{
Name: name,
Description: new("Auto-generated key for environment pairing"),
}, nil, &environmentID)
@@ -450,9 +450,13 @@ func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*mod
return nil, ErrApiKeyExpired
}
+ if apiKey.UserID == nil {
+ return nil, ErrApiKeyInvalid
+ }
+
s.markApiKeyUsedAsync(ctx, apiKey.ID)
- user, err := s.userService.GetUserByID(ctx, apiKey.UserID)
+ user, err := s.userService.GetUserByID(ctx, *apiKey.UserID)
if err != nil {
return nil, fmt.Errorf("failed to get user for API key: %w", err)
}
diff --git a/backend/internal/services/dashboard_service_test.go b/backend/internal/services/dashboard_service_test.go
index e0a0dd46a..2d17b472f 100644
--- a/backend/internal/services/dashboard_service_test.go
+++ b/backend/internal/services/dashboard_service_test.go
@@ -107,28 +107,28 @@ func TestDashboardService_GetActionItems_IncludesExpiringAPIKeys(t *testing.T) {
Name: "expiring-soon",
KeyHash: "hash-soon",
KeyPrefix: "arc_test_s",
- UserID: "user-1",
+ UserID: new("user-1"),
ExpiresAt: new(now.Add(24 * time.Hour)),
})
createDashboardTestAPIKey(t, db, models.ApiKey{
Name: "already-expired",
KeyHash: "hash-expired",
KeyPrefix: "arc_test_e",
- UserID: "user-1",
+ UserID: new("user-1"),
ExpiresAt: new(now.Add(-24 * time.Hour)),
})
createDashboardTestAPIKey(t, db, models.ApiKey{
Name: "future",
KeyHash: "hash-future",
KeyPrefix: "arc_test_f",
- UserID: "user-1",
+ UserID: new("user-1"),
ExpiresAt: new(now.Add(45 * 24 * time.Hour)),
})
createDashboardTestAPIKey(t, db, models.ApiKey{
Name: "never-expires",
KeyHash: "hash-never",
KeyPrefix: "arc_test_n",
- UserID: "user-1",
+ UserID: new("user-1"),
})
actionItems, err := svc.GetActionItems(context.Background(), DashboardActionItemsOptions{})
@@ -150,7 +150,7 @@ func TestDashboardService_GetActionItems_DebugAllGoodReturnsNoItems(t *testing.T
Name: "expiring-soon",
KeyHash: "hash-soon",
KeyPrefix: "arc_test_d",
- UserID: "user-1",
+ UserID: new("user-1"),
ExpiresAt: new(time.Now().Add(2 * time.Hour)),
})
@@ -216,7 +216,7 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
Name: "expiring-soon",
KeyHash: "hash-soon",
KeyPrefix: "arc_test_snapshot",
- UserID: "user-1",
+ UserID: new("user-1"),
ExpiresAt: new(time.Now().Add(12 * time.Hour)),
})
diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.go
index 6a46798e4..6289dfae9 100644
--- a/backend/internal/services/environment_service_test.go
+++ b/backend/internal/services/environment_service_test.go
@@ -533,7 +533,7 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesHiddenChildAn
Order("created_at asc").
Find(&apiKeys).Error)
require.Len(t, apiKeys, 1)
- require.Equal(t, user.ID, apiKeys[0].UserID)
+ require.Nil(t, apiKeys[0].UserID) // environment bootstrap keys have no owner
reusedEnv, reusedToken, err := svc.EnsureSwarmNodeAgentEnvironment(
ctx,
diff --git a/backend/pkg/utils/httpx/client.go b/backend/pkg/utils/httpx/client.go
index 644180e99..d290b9501 100644
--- a/backend/pkg/utils/httpx/client.go
+++ b/backend/pkg/utils/httpx/client.go
@@ -12,6 +12,7 @@ func NewHTTPClient() *http.Client {
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
+ ForceAttemptHTTP2: true,
}
return &http.Client{
Transport: transport,
@@ -26,6 +27,7 @@ func NewHTTPClientWithTimeout(timeout time.Duration) *http.Client {
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
+ ForceAttemptHTTP2: true,
}
return &http.Client{
Transport: transport,
diff --git a/backend/resources/migrations/postgres/046_nullable_api_key_user_id.down.sql b/backend/resources/migrations/postgres/046_nullable_api_key_user_id.down.sql
new file mode 100644
index 000000000..1df2cf8fd
--- /dev/null
+++ b/backend/resources/migrations/postgres/046_nullable_api_key_user_id.down.sql
@@ -0,0 +1,3 @@
+-- Remove environment bootstrap keys (user_id IS NULL) before restoring the NOT NULL constraint.
+DELETE FROM api_keys WHERE user_id IS NULL;
+ALTER TABLE api_keys ALTER COLUMN user_id SET NOT NULL;
diff --git a/backend/resources/migrations/postgres/046_nullable_api_key_user_id.up.sql b/backend/resources/migrations/postgres/046_nullable_api_key_user_id.up.sql
new file mode 100644
index 000000000..98452119a
--- /dev/null
+++ b/backend/resources/migrations/postgres/046_nullable_api_key_user_id.up.sql
@@ -0,0 +1,3 @@
+-- Environment bootstrap keys are owned by the system, not a user.
+-- Allow user_id to be NULL so agent-side key creation doesn't violate the FK constraint.
+ALTER TABLE api_keys ALTER COLUMN user_id DROP NOT NULL;
diff --git a/backend/resources/migrations/sqlite/046_nullable_api_key_user_id.down.sql b/backend/resources/migrations/sqlite/046_nullable_api_key_user_id.down.sql
new file mode 100644
index 000000000..2295401f0
--- /dev/null
+++ b/backend/resources/migrations/sqlite/046_nullable_api_key_user_id.down.sql
@@ -0,0 +1,61 @@
+-- Remove environment bootstrap keys (user_id IS NULL) before restoring the NOT NULL constraint.
+PRAGMA foreign_keys=OFF;
+
+DROP TABLE IF EXISTS api_keys_old;
+
+CREATE TABLE api_keys_old (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ key_hash TEXT NOT NULL,
+ key_prefix TEXT NOT NULL,
+ managed_by TEXT,
+ user_id TEXT NOT NULL,
+ environment_id TEXT,
+ expires_at DATETIME,
+ last_used_at DATETIME,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ FOREIGN KEY (environment_id) REFERENCES environments(id) ON DELETE CASCADE
+);
+
+INSERT INTO api_keys_old (
+ id,
+ name,
+ description,
+ key_hash,
+ key_prefix,
+ managed_by,
+ user_id,
+ environment_id,
+ expires_at,
+ last_used_at,
+ created_at,
+ updated_at
+)
+SELECT
+ id,
+ name,
+ description,
+ key_hash,
+ key_prefix,
+ managed_by,
+ user_id,
+ environment_id,
+ expires_at,
+ last_used_at,
+ created_at,
+ updated_at
+FROM api_keys
+WHERE user_id IS NOT NULL;
+
+DROP TABLE api_keys;
+ALTER TABLE api_keys_old RENAME TO api_keys;
+
+CREATE INDEX IF NOT EXISTS idx_api_keys_key_hash ON api_keys(key_hash);
+CREATE INDEX IF NOT EXISTS idx_api_keys_key_prefix ON api_keys(key_prefix);
+CREATE INDEX IF NOT EXISTS idx_api_keys_expires_at_not_null ON api_keys(expires_at) WHERE expires_at IS NOT NULL;
+CREATE INDEX IF NOT EXISTS idx_api_keys_user_managed_by_created_at ON api_keys(user_id, managed_by, created_at, id);
+
+PRAGMA foreign_keys=ON;
diff --git a/backend/resources/migrations/sqlite/046_nullable_api_key_user_id.up.sql b/backend/resources/migrations/sqlite/046_nullable_api_key_user_id.up.sql
new file mode 100644
index 000000000..43d4a3527
--- /dev/null
+++ b/backend/resources/migrations/sqlite/046_nullable_api_key_user_id.up.sql
@@ -0,0 +1,61 @@
+-- Environment bootstrap keys are owned by the system, not a user.
+-- Allow user_id to be NULL so agent-side key creation doesn't violate the FK constraint.
+PRAGMA foreign_keys=OFF;
+
+DROP TABLE IF EXISTS api_keys_new;
+
+CREATE TABLE api_keys_new (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ description TEXT,
+ key_hash TEXT NOT NULL,
+ key_prefix TEXT NOT NULL,
+ managed_by TEXT,
+ user_id TEXT,
+ environment_id TEXT,
+ expires_at DATETIME,
+ last_used_at DATETIME,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ FOREIGN KEY (environment_id) REFERENCES environments(id) ON DELETE CASCADE
+);
+
+INSERT INTO api_keys_new (
+ id,
+ name,
+ description,
+ key_hash,
+ key_prefix,
+ managed_by,
+ user_id,
+ environment_id,
+ expires_at,
+ last_used_at,
+ created_at,
+ updated_at
+)
+SELECT
+ id,
+ name,
+ description,
+ key_hash,
+ key_prefix,
+ managed_by,
+ user_id,
+ environment_id,
+ expires_at,
+ last_used_at,
+ created_at,
+ updated_at
+FROM api_keys;
+
+DROP TABLE api_keys;
+ALTER TABLE api_keys_new RENAME TO api_keys;
+
+CREATE INDEX IF NOT EXISTS idx_api_keys_key_hash ON api_keys(key_hash);
+CREATE INDEX IF NOT EXISTS idx_api_keys_key_prefix ON api_keys(key_prefix);
+CREATE INDEX IF NOT EXISTS idx_api_keys_expires_at_not_null ON api_keys(expires_at) WHERE expires_at IS NOT NULL;
+CREATE INDEX IF NOT EXISTS idx_api_keys_user_managed_by_created_at ON api_keys(user_id, managed_by, created_at, id);
+
+PRAGMA foreign_keys=ON;
diff --git a/types/apikey/apikey.go b/types/apikey/apikey.go
index 75cdcb8d3..bbb165d10 100644
--- a/types/apikey/apikey.go
+++ b/types/apikey/apikey.go
@@ -15,7 +15,7 @@ type ApiKey struct {
Name string `json:"name" doc:"Name of the API key"`
Description *string `json:"description,omitempty" doc:"Description of the API key"`
KeyPrefix string `json:"keyPrefix" doc:"Prefix of the API key for identification"`
- UserID string `json:"userId" doc:"ID of the user who owns the API key"`
+ UserID *string `json:"userId,omitempty" doc:"ID of the user who owns the API key"`
IsStatic bool `json:"isStatic" doc:"Whether the API key is environment-managed and protected from deletion"`
ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Expiration date of the API key"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty" doc:"Last time the API key was used"`