feat: add scoped tenant api keys
This commit is contained in:
+174
-4
@@ -25,6 +25,7 @@ import (
|
||||
// through the REST API endpoints
|
||||
type TenantHandler struct {
|
||||
service interfaces.TenantService
|
||||
apiKeyService interfaces.TenantAPIKeyService
|
||||
userService interfaces.UserService
|
||||
memberService interfaces.TenantMemberService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
@@ -55,6 +56,7 @@ type TenantHandler struct {
|
||||
// stays focused on business logic.
|
||||
func NewTenantHandler(
|
||||
service interfaces.TenantService,
|
||||
apiKeyService interfaces.TenantAPIKeyService,
|
||||
userService interfaces.UserService,
|
||||
memberService interfaces.TenantMemberService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
@@ -63,6 +65,7 @@ func NewTenantHandler(
|
||||
) *TenantHandler {
|
||||
return &TenantHandler{
|
||||
service: service,
|
||||
apiKeyService: apiKeyService,
|
||||
userService: userService,
|
||||
memberService: memberService,
|
||||
kbService: kbService,
|
||||
@@ -130,6 +133,29 @@ type apiPrincipalTestTokenResponse struct {
|
||||
ExternalUserID string `json:"external_user_id"`
|
||||
}
|
||||
|
||||
type tenantAPIKeyCreateRequest struct {
|
||||
Name string `json:"name"`
|
||||
Scopes []string `json:"scopes"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
|
||||
ExpiresAt *int64 `json:"expires_at_unix"`
|
||||
}
|
||||
|
||||
type tenantAPIKeyResponse struct {
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
APIKey string `json:"api_key"`
|
||||
Scopes types.StringArray `json:"scopes"`
|
||||
KnowledgeBaseIDs types.StringArray `json:"knowledge_base_ids"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type tenantAPIKeyCreateResponse struct {
|
||||
tenantAPIKeyResponse
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
const (
|
||||
defaultAPIPrincipalDirectHeader = "X-External-User-ID"
|
||||
defaultAPIPrincipalTokenHeader = "X-External-User-Token"
|
||||
@@ -210,8 +236,9 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
|
||||
} else {
|
||||
// Self-service path: a regular user can only set name and
|
||||
// description. Everything else is server-generated by
|
||||
// TenantService.CreateTenant (api_key, status="active",
|
||||
// storage_quota default, retriever engines from RETRIEVE_DRIVER).
|
||||
// TenantService.CreateTenant (status="active", storage_quota
|
||||
// default, retriever engines from RETRIEVE_DRIVER). API keys are
|
||||
// created explicitly through the integration API-key list.
|
||||
var req createTenantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
@@ -531,7 +558,19 @@ func (h *TenantHandler) ResetAPIKey(c *gin.Context) {
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Resetting API key for tenant, ID: %d", id)
|
||||
apiKey, err := h.service.UpdateAPIKey(ctx, id)
|
||||
if h.apiKeyService == nil {
|
||||
c.Error(errors.NewInternalServerError("API key service is not configured"))
|
||||
return
|
||||
}
|
||||
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: id,
|
||||
Name: "Tenant API key",
|
||||
Scopes: []string{
|
||||
types.TenantAPIKeyScopeRead,
|
||||
types.TenantAPIKeyScopeWrite,
|
||||
types.TenantAPIKeyScopeAdmin,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
logger.Error(ctx, "Failed to reset API key: application error", appErr)
|
||||
@@ -547,11 +586,142 @@ func (h *TenantHandler) ResetAPIKey(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"api_key": apiKey,
|
||||
"api_key": result.APIKey.APIKey,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *TenantHandler) ListAPIKeys(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
|
||||
return
|
||||
}
|
||||
keys, err := h.apiKeyService.ListAPIKeys(ctx, id)
|
||||
if err != nil {
|
||||
c.Error(errors.NewInternalServerError("Failed to list API keys").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
resp := make([]tenantAPIKeyResponse, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
resp = append(resp, tenantAPIKeyForResponse(key))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": resp})
|
||||
}
|
||||
|
||||
func (h *TenantHandler) CreateAPIKey(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
|
||||
return
|
||||
}
|
||||
var req tenantAPIKeyCreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if err := validateTenantAPIKeyRequest(ctx, h.kbService, id, req); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
var expiresAt *time.Time
|
||||
if req.ExpiresAt != nil {
|
||||
t := time.Unix(*req.ExpiresAt, 0)
|
||||
if !t.After(time.Now()) {
|
||||
c.Error(errors.NewValidationError("expires_at_unix must be in the future"))
|
||||
return
|
||||
}
|
||||
expiresAt = &t
|
||||
}
|
||||
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: id,
|
||||
Name: req.Name,
|
||||
Scopes: req.Scopes,
|
||||
KnowledgeBaseIDs: req.KnowledgeBaseIDs,
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
c.Error(errors.NewInternalServerError("Failed to create API key").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"success": true,
|
||||
"data": tenantAPIKeyCreateResponse{
|
||||
tenantAPIKeyResponse: tenantAPIKeyForResponse(result.APIKey),
|
||||
Token: result.Token,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *TenantHandler) DeleteAPIKey(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tenantID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
|
||||
return
|
||||
}
|
||||
keyID, err := strconv.ParseUint(c.Param("key_id"), 10, 64)
|
||||
if err != nil || keyID == 0 {
|
||||
c.Error(errors.NewBadRequestError("Invalid API key ID"))
|
||||
return
|
||||
}
|
||||
if err := h.apiKeyService.RevokeAPIKey(ctx, tenantID, keyID); err != nil {
|
||||
c.Error(errors.NewNotFoundError("API key not found"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
func tenantAPIKeyForResponse(key *types.TenantAPIKey) tenantAPIKeyResponse {
|
||||
if key == nil {
|
||||
return tenantAPIKeyResponse{}
|
||||
}
|
||||
return tenantAPIKeyResponse{
|
||||
ID: key.ID,
|
||||
Name: key.Name,
|
||||
APIKey: key.APIKey,
|
||||
Scopes: key.Scopes,
|
||||
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
||||
LastUsedAt: key.LastUsedAt,
|
||||
ExpiresAt: key.ExpiresAt,
|
||||
CreatedAt: key.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func validateTenantAPIKeyRequest(
|
||||
ctx context.Context,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
tenantID uint64,
|
||||
req tenantAPIKeyCreateRequest,
|
||||
) *errors.AppError {
|
||||
if strings.TrimSpace(req.Name) == "" {
|
||||
return errors.NewValidationError("name is required")
|
||||
}
|
||||
for _, scope := range req.Scopes {
|
||||
switch strings.ToLower(strings.TrimSpace(scope)) {
|
||||
case types.TenantAPIKeyScopeRead, types.TenantAPIKeyScopeWrite, types.TenantAPIKeyScopeAdmin:
|
||||
default:
|
||||
return errors.NewValidationError("scopes must contain only read, write, or admin")
|
||||
}
|
||||
}
|
||||
for _, kbID := range req.KnowledgeBaseIDs {
|
||||
kbID = strings.TrimSpace(kbID)
|
||||
if kbID == "" {
|
||||
continue
|
||||
}
|
||||
kb, err := kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil || kb == nil {
|
||||
return errors.NewValidationError("knowledge_base_ids contains an unknown knowledge base")
|
||||
}
|
||||
if kb.TenantID != tenantID {
|
||||
return errors.NewForbiddenError("knowledge_base_ids contains a knowledge base outside this tenant")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func apiPrincipalConfigForResponse(cfg *types.APIPrincipalConfig) apiPrincipalConfigResponse {
|
||||
if cfg == nil {
|
||||
cfg = &types.APIPrincipalConfig{}
|
||||
|
||||
Reference in New Issue
Block a user