Files
tenant-registry/internal/server/apikeys_integration.go
T
sharang 5b4590d3bc
ci / shared (push) Successful in 13s
ci / test (push) Successful in 25m10s
ci / image (push) Successful in 36s
feat(api-keys): CI licences by API key and integration keys (#71)
2026-10-13 22:12:05 +00:00

158 lines
5.4 KiB
Go

package server
import (
"context"
"net/http"
"slices"
"strings"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/scopes"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// ─── integration keys (ADR 0001 §6) ───────────────────────────────────────
//
// A product that acts for a tenant without a person present (Werkmeister's
// scheduled and triggered runs) holds one key per tenant. It is created with
// the token of the tenant's admin, through the product's web client: the
// registry checks tenant, role, holder and scopes itself, so no service
// client gains cross-tenant power. AUTHZ group: api-keys.integration (a user
// token on any /v1/api-keys route is classified so, see requireAuthz).
// integrationScopes is the allowlist per holder product.
var integrationScopes = map[string][]string{
"werkmeister": {
"firmwerk:projects.read", "firmwerk:projects.write",
"pruefwerk:enisa.read", "pruefwerk:findings.read", "pruefwerk:findings.write",
"pruefwerk:sbom.read", "pruefwerk:scans.read", "pruefwerk:scans.run",
},
}
// integrationHolder maps a web client id (azp) to the holder product:
// "werkmeister-stage" → "werkmeister". Empty when the client may not hold
// integration keys.
func integrationHolder(azp string) string {
h := azp
for _, env := range []string{"-stage", "-prod", "-dev"} {
h = strings.TrimSuffix(h, env)
}
if _, ok := integrationScopes[h]; !ok {
return ""
}
return h
}
// integrationCaller checks a user principal for the integration routes and
// returns its holder; on failure it has written the response.
func integrationCaller(w http.ResponseWriter, p *authn.Principal, tenantID string) (string, bool) {
holder := integrationHolder(p.ClientID)
if holder == "" {
writeError(w, http.StatusForbidden, "FORBIDDEN_CLIENT", "client "+p.ClientID+" may not hold integration keys")
return "", false
}
if !p.IsTenantAdmin() {
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "only a tenant admin may manage integration keys")
return "", false
}
if tenantID != "" && tenantID != p.TenantID {
writeError(w, http.StatusForbidden, "FORBIDDEN_TENANT", "integration keys only for your own tenant")
return "", false
}
return holder, true
}
func (s *Server) createIntegrationKey(w http.ResponseWriter, r *http.Request, p *authn.Principal, in createAPIKeyReq) {
holder, ok := integrationCaller(w, p, in.TenantID)
if !ok {
return
}
if in.Kind != "" && in.Kind != store.APIKeyKindIntegration {
writeError(w, http.StatusBadRequest, "invalid_kind", "a user token creates integration keys only")
return
}
if in.Name != "" && in.Name != holder {
writeError(w, http.StatusBadRequest, "invalid_name", "an integration key is named after its holder ("+holder+")")
return
}
if in.ExpiresAt != nil || in.Product != "" {
writeError(w, http.StatusBadRequest, "invalid_input", "integration keys take no product and no expiry")
return
}
if len(in.Scopes) == 0 {
writeError(w, http.StatusBadRequest, "invalid_scopes", "integration keys need at least one scope")
return
}
norm, err := scopes.Validate(in.Scopes, "")
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_scopes", err.Error())
return
}
for _, sc := range norm {
if !slices.Contains(integrationScopes[holder], sc) {
writeError(w, http.StatusBadRequest, "invalid_scopes", "scope "+sc+" is not allowed for "+holder)
return
}
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
entitled, _, err := s.entitledProducts(ctx, p.TenantID)
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
for _, prod := range append(scopes.Products(norm), holder) {
if !entitled[prod] {
writeError(w, http.StatusUnprocessableEntity, "not_entitled", "tenant is not entitled to "+prod)
return
}
}
plain, err := generateAPIKey()
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", "key generation failed")
return
}
sum := hashKey(plain)
createdBy := p.Email
if createdBy == "" {
createdBy = p.Subject
}
k, err := s.Store.CreateAPIKey(ctx, store.APIKeyCreate{
TenantID: p.TenantID, Name: holder, Scopes: norm, Prefix: plain[:prefixLen], HashSHA256: sum,
Kind: store.APIKeyKindIntegration, Holder: holder, CreatedBy: createdBy,
})
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: p.TenantID, Action: "api_key.created", TargetID: k.ID, TargetType: "api_key", TargetName: holder,
Metadata: map[string]interface{}{"scopes": norm, "kind": store.APIKeyKindIntegration, "holder": holder},
})
writeJSON(w, http.StatusCreated, createAPIKeyResp{
APIKey: *k, Plaintext: plain, WarningMsg: "Store this value now — it cannot be retrieved later.",
})
}
// integrationKeys lists the caller holder's integration keys of its tenant.
func (s *Server) integrationKeys(ctx context.Context, tenantID, holder string) ([]store.APIKey, error) {
all, err := s.Store.ListAPIKeys(ctx, tenantID)
if err != nil {
return nil, err
}
out := []store.APIKey{}
for _, k := range all {
if k.Kind == store.APIKeyKindIntegration && k.Holder == holder {
out = append(out, k)
}
}
return out, nil
}