This commit is contained in:
greeneclipse committed 2026-10-14 16:13:51 +02:00
1 parent 7ab7acd533
commit 176b1fe47f
18 files changed
+423 -31

No files matched your search

+57 -3
View File
@@ -6,11 +6,65 @@ import (
"strings"
"github.com/descrybe/descrybe-v2/apps/api/internal/auth"
"github.com/descrybe/descrybe-v2/apps/api/internal/billing"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// allowAPIKeyManager authorizes API-key management using the SAME per-member
// settings.api_keys permission as the dashboard and RequireMemberFeature.
// Members with the area disabled cannot create, rename or revoke keys. Company
// admins, owners and platform admins keep their existing privileges.
// This check is deliberately repeated at the handler: direct calls must not
// bypass the router's member-permission middleware.
func (s *Server) allowAPIKeyManager(w http.ResponseWriter, r *http.Request) bool {
if CompanyAdminAllowed(r.Context()) {
return true
}
uid, okUser := UserIDFromContext(r.Context())
cid, okCompany := CompanyIDFromContext(r.Context())
if !okUser || !okCompany {
Error(w, http.StatusUnauthorized, "unauthorized")
return false
}
isPlatformAdmin, err := s.checkPlatformAdmin(r.Context(), uid)
if err != nil {
Error(w, http.StatusInternalServerError, "authorization check failed")
return false
}
if isPlatformAdmin {
return true
}
isOwner, err := s.checkCompanyOwner(r.Context(), uid)
if err != nil {
Error(w, http.StatusInternalServerError, "authorization check failed")
return false
}
if isOwner {
return true
}
// Ordinary members need both the company's API entitlement and their
// effective per-member grant. A permissions lookup error fails closed.
if s.Billing == nil {
Error(w, http.StatusForbidden, "API keys permission required")
return false
}
if !s.requireFeatures(w, r, "settings.api_keys", "capability.api_access") {
return false
}
perms, err := s.Billing.MemberPermissions(r.Context(), cid, uid)
if err != nil {
Error(w, http.StatusServiceUnavailable, "permissions temporarily unavailable")
return false
}
if billing.MemberDeniesFeature(perms, "settings.api_keys") {
Error(w, http.StatusForbidden, "API keys permission required")
return false
}
return true
}
func (s *Server) handleListAPIKeys(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context())
limit, offset := ParseLimitOffset(r)
@@ -49,7 +103,7 @@ func (s *Server) handleListAPIKeys(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context())
uid, _ := UserIDFromContext(r.Context())
if !s.allowCompanyAdminOrPlatform(w, r) {
if !s.allowAPIKeyManager(w, r) {
return
}
if !s.requireFeatures(w, r, "settings.api_keys", "capability.api_access") {
@@ -85,7 +139,7 @@ func (s *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleUpdateAPIKey(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context())
if !s.allowCompanyAdminOrPlatform(w, r) {
if !s.allowAPIKeyManager(w, r) {
return
}
if !s.requireFeatures(w, r, "settings.api_keys", "capability.api_access") {
@@ -140,7 +194,7 @@ func (s *Server) handleUpdateAPIKey(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleRevokeAPIKey(w http.ResponseWriter, r *http.Request) {
cid, _ := CompanyIDFromContext(r.Context())
if !s.allowCompanyAdminOrPlatform(w, r) {
if !s.allowAPIKeyManager(w, r) {
return
}
id, err := uuid.Parse(chi.URLParam(r, "id"))
@@ -55,3 +55,44 @@ func TestHandleUpdateAPIKeyRejectsInvalidID(t *testing.T) {
t.Fatalf("status = %d body=%s, want 400", rec.Code, rec.Body.String())
}
}
// API-key management is separate from company-admin / team / billing privileges.
// Explicit permission checks are also enforced for handler calls that do not
// pass through the router's RequireMemberFeature middleware.
func TestAllowAPIKeyManagerPrivilegesAndMissingGrant(t *testing.T) {
t.Parallel()
uid := uuid.MustParse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
cid := uuid.MustParse("11111111-1111-1111-1111-111111111111")
cases := []struct {
name string
role string
platform bool
owner bool
want int
}{
{name: "company admin", role: "admin", want: http.StatusOK},
{name: "platform admin", role: "member", platform: true, want: http.StatusOK},
{name: "company owner", role: "member", owner: true, want: http.StatusOK},
{name: "ordinary member without loaded permissions", role: "member", want: http.StatusForbidden},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := &Server{
testPlatformAdmin: func(context.Context, uuid.UUID) (bool, error) { return tc.platform, nil },
testCompanyOwner: func(context.Context, uuid.UUID) (bool, error) { return tc.owner, nil },
}
ctx := context.WithValue(context.Background(), ctxUserID, uid)
ctx = context.WithValue(ctx, ctxCompanyID, cid)
ctx = context.WithValue(ctx, ctxRole, tc.role)
req := httptest.NewRequest(http.MethodPost, "/api/api-keys", nil).WithContext(ctx)
rec := httptest.NewRecorder()
allowed := s.allowAPIKeyManager(rec, req)
if allowed != (tc.want == http.StatusOK) {
t.Fatalf("allowAPIKeyManager allowed=%v status=%d", allowed, rec.Code)
}
if !allowed && rec.Code != tc.want {
t.Fatalf("status=%d body=%s, want %d", rec.Code, rec.Body.String(), tc.want)
}
})
}
}
@@ -270,6 +270,76 @@ func TestAuthSessionCoreEndpoints(t *testing.T) {
t.Fatalf("revoke api-key status=%d body=%s", rec.Code, rec.Body.String())
}
// A normal teammate with an explicit API Keys area grant may manage keys,
// without being made a company administrator. Denying the area closes both
// the list endpoint and the create/rename/revoke endpoints.
_, err = pg.Exec(ctx, `
UPDATE memberships SET role = 'member', permissions = '{"settings.api_keys":false}'::jsonb
WHERE company_id = $1 AND user_id = $2`, companyID, userID)
if err != nil {
t.Fatalf("restrict api-key member: %v", err)
}
rec = do(http.MethodGet, "/api/api-keys", "", false)
if rec.Code != http.StatusForbidden {
t.Fatalf("member denied api-keys list status=%d body=%s", rec.Code, rec.Body.String())
}
rec = do(http.MethodPost, "/api/api-keys", `{"name":"blocked"}`, true)
if rec.Code != http.StatusForbidden {
t.Fatalf("member denied api-key create status=%d body=%s", rec.Code, rec.Body.String())
}
_, err = pg.Exec(ctx, `
UPDATE memberships SET permissions = '{}'::jsonb
WHERE company_id = $1 AND user_id = $2`, companyID, userID)
if err != nil {
t.Fatalf("allow api-key member: %v", err)
}
rec = do(http.MethodPost, "/api/api-keys", `{"name":"member-key"}`, true)
if rec.Code != http.StatusCreated {
t.Fatalf("member create api-key status=%d body=%s", rec.Code, rec.Body.String())
}
memberKey := decode(t, rec)
memberKeyID := fmt.Sprint(memberKey["id"])
if !strings.HasPrefix(fmt.Sprint(memberKey["key"]), "dk_") {
t.Fatalf("member create did not return one-time secret: %v", memberKey)
}
rec = do(http.MethodGet, "/api/api-keys", "", false)
if rec.Code != http.StatusOK {
t.Fatalf("member list api-keys status=%d body=%s", rec.Code, rec.Body.String())
}
if strings.Contains(rec.Body.String(), fmt.Sprint(memberKey["key"])) {
t.Fatal("list endpoint must never expose full API secrets")
}
rec = do(http.MethodPatch, "/api/api-keys/"+memberKeyID, `{"name":"member-renamed"}`, true)
if rec.Code != http.StatusOK || fmt.Sprint(decode(t, rec)["name"]) != "member-renamed" {
t.Fatalf("member rename api-key status=%d body=%s", rec.Code, rec.Body.String())
}
// Revoking the member's API Keys area closes modification of keys they
// previously created, without affecting unrelated team permissions.
_, err = pg.Exec(ctx, `
UPDATE memberships SET permissions = '{"settings.api_keys":false}'::jsonb
WHERE company_id = $1 AND user_id = $2`, companyID, userID)
if err != nil {
t.Fatalf("remove api-key access: %v", err)
}
rec = do(http.MethodPatch, "/api/api-keys/"+memberKeyID, `{"name":"should-not-rename"}`, true)
if rec.Code != http.StatusForbidden {
t.Fatalf("member denied api-key rename status=%d body=%s", rec.Code, rec.Body.String())
}
rec = do(http.MethodDelete, "/api/api-keys/"+memberKeyID, "", true)
if rec.Code != http.StatusForbidden {
t.Fatalf("member denied api-key revoke status=%d body=%s", rec.Code, rec.Body.String())
}
_, err = pg.Exec(ctx, `
UPDATE memberships SET permissions = '{}'::jsonb
WHERE company_id = $1 AND user_id = $2`, companyID, userID)
if err != nil {
t.Fatalf("restore api-key access: %v", err)
}
rec = do(http.MethodDelete, "/api/api-keys/"+memberKeyID, "", true)
if rec.Code != http.StatusOK {
t.Fatalf("member revoke api-key status=%d body=%s", rec.Code, rec.Body.String())
}
rec = do(http.MethodPost, "/api/auth/logout", `{}`, true)
if rec.Code != http.StatusOK {
t.Fatalf("logout status=%d body=%s", rec.Code, rec.Body.String())