421 lines
13 KiB
Go
421 lines
13 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"net/http"
|
|
"slices"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/argon2"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/scopes"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// Plaintext key format: `bp_<32 base64 chars>`. Prefix stored for UI is
|
|
// the first 11 chars (`bp_<8 chars>`). New keys are stored as sha256 of the
|
|
// plaintext: 192 random bits need no slow KDF, and the lookup is an index
|
|
// hit. Keys created before migration 0015 keep their argon2id hash.
|
|
const (
|
|
keyPrefix = "bp_"
|
|
prefixLen = 11 // bp_ + 8
|
|
keyEntropyBy = 24 // 24 bytes → 32 base64 chars
|
|
)
|
|
|
|
var (
|
|
argonTime uint32 = 1
|
|
argonMemory uint32 = 64 * 1024
|
|
argonThreads uint8 = 4
|
|
argonKeyLen uint32 = 32
|
|
)
|
|
|
|
// ciKeyMaxTTL bounds a CI key's lifetime; CI keys must expire.
|
|
const ciKeyMaxTTL = 365 * 24 * time.Hour
|
|
|
|
type createAPIKeyReq struct {
|
|
TenantID string `json:"tenant_id"`
|
|
Name string `json:"name"`
|
|
Product string `json:"product,omitempty"`
|
|
Scopes []string `json:"scopes,omitempty"`
|
|
Kind string `json:"kind,omitempty"` // user (default) | ci
|
|
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
|
CreatedBy string `json:"created_by,omitempty"`
|
|
}
|
|
|
|
type createAPIKeyResp struct {
|
|
APIKey store.APIKey `json:"api_key"`
|
|
Plaintext string `json:"plaintext"` // shown ONCE — caller must store
|
|
WarningMsg string `json:"warning"`
|
|
}
|
|
|
|
func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) {
|
|
var in createAPIKeyReq
|
|
if !decodeJSON(w, r, &in) {
|
|
return
|
|
}
|
|
if p, ok := authn.PrincipalFrom(r.Context()); ok && p.IsUser() {
|
|
s.createIntegrationKey(w, r, p, in)
|
|
return
|
|
}
|
|
if in.TenantID == "" || in.Name == "" {
|
|
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and name are required")
|
|
return
|
|
}
|
|
if len(in.Name) > 100 {
|
|
writeError(w, http.StatusBadRequest, "invalid_name", "name too long")
|
|
return
|
|
}
|
|
switch in.Kind {
|
|
case "":
|
|
in.Kind = store.APIKeyKindUser
|
|
case store.APIKeyKindUser, store.APIKeyKindCI:
|
|
case store.APIKeyKindIntegration:
|
|
writeError(w, http.StatusBadRequest, "invalid_kind", "integration keys are created by their holder product")
|
|
return
|
|
default:
|
|
writeError(w, http.StatusBadRequest, "invalid_kind", "kind must be user or ci")
|
|
return
|
|
}
|
|
now := time.Now().UTC()
|
|
if in.ExpiresAt != nil && !in.ExpiresAt.After(now) {
|
|
writeError(w, http.StatusBadRequest, "invalid_expiry", "expires_at must be in the future")
|
|
return
|
|
}
|
|
if in.Kind == store.APIKeyKindCI {
|
|
if in.ExpiresAt == nil || in.ExpiresAt.After(now.Add(ciKeyMaxTTL)) {
|
|
writeError(w, http.StatusBadRequest, "invalid_expiry", "ci keys need expires_at within 365 days")
|
|
return
|
|
}
|
|
if len(in.Scopes) == 0 {
|
|
writeError(w, http.StatusBadRequest, "invalid_scopes", "ci keys need at least one scope")
|
|
return
|
|
}
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer cancel()
|
|
if in.Product != "" && !s.knownProduct(ctx, in.Product) {
|
|
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
|
|
return
|
|
}
|
|
// Empty scopes = legacy full grant on product (portal keys before the
|
|
// scope picker); scoped keys only for products the tenant has booked.
|
|
if len(in.Scopes) > 0 {
|
|
norm, err := scopes.Validate(in.Scopes, in.Product)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid_scopes", err.Error())
|
|
return
|
|
}
|
|
in.Scopes = norm
|
|
entitled, _, err := s.entitledProducts(ctx, in.TenantID)
|
|
if err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
for _, p := range scopes.Products(in.Scopes) {
|
|
if !entitled[p] {
|
|
writeError(w, http.StatusUnprocessableEntity, "not_entitled", "tenant is not entitled to "+p)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
plain, err := generateAPIKey()
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", "key generation failed")
|
|
return
|
|
}
|
|
k, err := s.Store.CreateAPIKey(ctx, store.APIKeyCreate{
|
|
TenantID: in.TenantID,
|
|
Product: in.Product,
|
|
Name: in.Name,
|
|
Scopes: in.Scopes,
|
|
Prefix: plain[:prefixLen],
|
|
HashSHA256: hashKey(plain),
|
|
Kind: in.Kind,
|
|
ExpiresAt: in.ExpiresAt,
|
|
CreatedBy: in.CreatedBy,
|
|
})
|
|
if err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
|
|
s.emitAudit(ctx, r, store.AuditEvent{
|
|
TenantID: in.TenantID, Action: "api_key.created",
|
|
TargetID: k.ID, TargetType: "api_key", TargetName: in.Name,
|
|
Metadata: map[string]interface{}{"product": in.Product, "scopes": in.Scopes, "kind": in.Kind},
|
|
})
|
|
|
|
writeJSON(w, http.StatusCreated, createAPIKeyResp{
|
|
APIKey: *k,
|
|
Plaintext: plain,
|
|
WarningMsg: "Store this value now — it cannot be retrieved later.",
|
|
})
|
|
}
|
|
|
|
// listAPIKeyScopes — GET /v1/api-keys/scopes: the scope catalogue, for the
|
|
// portal's scope picker.
|
|
func (s *Server) listAPIKeyScopes(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": scopes.All()})
|
|
}
|
|
|
|
func (s *Server) listAPIKeys(w http.ResponseWriter, r *http.Request) {
|
|
tenantID := r.URL.Query().Get("tenant_id")
|
|
if tenantID == "" {
|
|
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
var list []store.APIKey
|
|
var err error
|
|
if p, ok := authn.PrincipalFrom(r.Context()); ok && p.IsUser() {
|
|
holder, ok := integrationCaller(w, p, tenantID)
|
|
if !ok {
|
|
return
|
|
}
|
|
list, err = s.integrationKeys(ctx, tenantID, holder)
|
|
} else {
|
|
list, err = s.Store.ListAPIKeys(ctx, tenantID)
|
|
}
|
|
if err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"items": list})
|
|
}
|
|
|
|
// revokeAPIKey — DELETE /v1/api-keys/{id}[?tenant_id=…]. With tenant_id the
|
|
// key must belong to that tenant (404 otherwise).
|
|
func (s *Server) revokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer cancel()
|
|
id := r.PathValue("id")
|
|
tenantID := r.URL.Query().Get("tenant_id")
|
|
if p, ok := authn.PrincipalFrom(r.Context()); ok && p.IsUser() {
|
|
// A user token revokes only its holder's integration keys, in its
|
|
// own tenant.
|
|
holder, ok := integrationCaller(w, p, tenantID)
|
|
if !ok {
|
|
return
|
|
}
|
|
tenantID = p.TenantID
|
|
keys, err := s.integrationKeys(ctx, tenantID, holder)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
if !slices.ContainsFunc(keys, func(k store.APIKey) bool { return k.ID == id }) {
|
|
writeError(w, http.StatusNotFound, "not_found", "api key not found")
|
|
return
|
|
}
|
|
}
|
|
if err := s.Store.RevokeAPIKey(ctx, id, tenantID); err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
s.emitAudit(ctx, r, store.AuditEvent{
|
|
TenantID: tenantID, Action: "api_key.revoked", TargetID: id, TargetType: "api_key",
|
|
})
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
type verifyAPIKeyReq struct {
|
|
Key string `json:"key"`
|
|
}
|
|
|
|
type verifyAPIKeyResp struct {
|
|
Valid bool `json:"valid"`
|
|
TenantID string `json:"tenant_id,omitempty"`
|
|
Product string `json:"product,omitempty"`
|
|
Scopes []string `json:"scopes,omitempty"`
|
|
KeyID string `json:"key_id,omitempty"`
|
|
Kind string `json:"kind,omitempty"`
|
|
Holder string `json:"holder,omitempty"`
|
|
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
|
TenantStatus string `json:"tenant_status,omitempty"`
|
|
// Legacy — the key has no scopes and grants everything on Product (or
|
|
// on every entitled product when Product is empty), as before scopes.
|
|
Legacy bool `json:"legacy,omitempty"`
|
|
}
|
|
|
|
// verifyAPIKey — POST /v1/internal/api-keys/verify. Used by products to
|
|
// validate inbound keys. Returns 200 with valid=false rather than 401 so the
|
|
// caller can decide what to do. Products cache results for at most 60 s, so
|
|
// a revocation takes up to a minute to reach them.
|
|
func (s *Server) verifyAPIKey(w http.ResponseWriter, r *http.Request) {
|
|
var in verifyAPIKeyReq
|
|
if !decodeJSON(w, r, &in) {
|
|
return
|
|
}
|
|
if !looksLikeKey(in.Key) {
|
|
writeJSON(w, http.StatusOK, verifyAPIKeyResp{Valid: false})
|
|
return
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
|
|
k, err := s.findAPIKey(ctx, in.Key)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
writeJSON(w, http.StatusOK, verifyAPIKeyResp{Valid: false})
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
if k.ExpiresAt != nil && !k.ExpiresAt.After(time.Now()) {
|
|
writeJSON(w, http.StatusOK, verifyAPIKeyResp{Valid: false})
|
|
return
|
|
}
|
|
entitled, status, err := s.entitledProducts(ctx, k.TenantID)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
writeJSON(w, http.StatusOK, verifyAPIKeyResp{Valid: false})
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
|
|
// Best-effort touch — failures are non-fatal.
|
|
if err := s.Store.TouchAPIKeyUsed(ctx, k.ID); err != nil {
|
|
s.Log.Warn("touch api_key failed", "err", err)
|
|
}
|
|
|
|
resp := verifyAPIKeyResp{
|
|
Valid: true, TenantID: k.TenantID, Product: k.Product,
|
|
KeyID: k.ID, Kind: k.Kind, Holder: k.Holder, ExpiresAt: k.ExpiresAt,
|
|
TenantStatus: status, Legacy: len(k.Scopes) == 0,
|
|
}
|
|
if !resp.Legacy {
|
|
resp.Scopes = scopes.Effective(k.Scopes, entitled)
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
// findAPIKey resolves a plaintext key: keys since migration 0015 by their
|
|
// sha256 (indexed), older ones by prefix + argon2id. Prefixes are not
|
|
// unique, so every active candidate is checked.
|
|
func (s *Server) findAPIKey(ctx context.Context, plain string) (*store.APIKey, error) {
|
|
k, err := s.Store.FindAPIKeyBySHA256(ctx, hashKey(plain))
|
|
if err == nil || !errors.Is(err, store.ErrNotFound) {
|
|
return k, err
|
|
}
|
|
cands, err := s.Store.FindAPIKeysByPrefix(ctx, plain[:prefixLen])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i := range cands {
|
|
if verifyHash(plain, cands[i].Hash) {
|
|
return &cands[i].APIKey, nil
|
|
}
|
|
}
|
|
return nil, store.ErrNotFound
|
|
}
|
|
|
|
// entitledProducts returns the products the tenant may use now (enabled, not
|
|
// expired) and the tenant status. Archived and halted tenants are entitled
|
|
// to nothing.
|
|
func (s *Server) entitledProducts(ctx context.Context, tenantID string) (map[string]bool, string, error) {
|
|
t, err := s.Store.GetTenant(ctx, tenantID)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
out := map[string]bool{}
|
|
if t.Status == store.StatusArchived || t.Status == store.StatusHalted {
|
|
return out, t.Status, nil
|
|
}
|
|
tps, err := s.Store.ListTenantProducts(ctx, t.ID)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
now := time.Now()
|
|
for _, tp := range tps {
|
|
if tp.Enabled && (tp.ExpiresAt == nil || tp.ExpiresAt.After(now)) {
|
|
out[tp.Product] = true
|
|
}
|
|
}
|
|
return out, t.Status, nil
|
|
}
|
|
|
|
// ─── helpers ──────────────────────────────────────────────────────────────
|
|
|
|
// hashKey is the stored form of keys since migration 0015.
|
|
func hashKey(plain string) []byte {
|
|
sum := sha256.Sum256([]byte(plain))
|
|
return sum[:]
|
|
}
|
|
|
|
func generateAPIKey() (string, error) {
|
|
buf := make([]byte, keyEntropyBy)
|
|
if _, err := rand.Read(buf); err != nil {
|
|
return "", err
|
|
}
|
|
return keyPrefix + base64.RawURLEncoding.EncodeToString(buf), nil
|
|
}
|
|
|
|
func looksLikeKey(k string) bool {
|
|
if len(k) < prefixLen {
|
|
return false
|
|
}
|
|
if k[:len(keyPrefix)] != keyPrefix {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// verifyHash checks a key created before migration 0015 against its stored
|
|
// argon2id hash. Format: argon2id|<salt-b64>|<hash-b64>.
|
|
func verifyHash(plain, stored string) bool {
|
|
if len(stored) < 12 || stored[:9] != "argon2id|" {
|
|
return false
|
|
}
|
|
rest := stored[9:]
|
|
sep := -1
|
|
for i := range rest {
|
|
if rest[i] == '|' {
|
|
sep = i
|
|
break
|
|
}
|
|
}
|
|
if sep <= 0 {
|
|
return false
|
|
}
|
|
salt, err := base64.RawStdEncoding.DecodeString(rest[:sep])
|
|
if err != nil {
|
|
return false
|
|
}
|
|
want, err := base64.RawStdEncoding.DecodeString(rest[sep+1:])
|
|
if err != nil {
|
|
return false
|
|
}
|
|
got := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
|
if len(want) != len(got) {
|
|
return false
|
|
}
|
|
var diff byte
|
|
for i := range want {
|
|
diff |= want[i] ^ got[i]
|
|
}
|
|
return diff == 0
|
|
}
|