This is an automated email from the ASF dual-hosted git repository. lahirujayathilake pushed a commit to branch signer-machine-api in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 902130a3ab8884e4c67fad8399710071b01aba0f Author: lahiruj <[email protected]> AuthorDate: Mon Nov 9 15:03:23 2026 -0500 signer connector decides who gets a certificate and who can revoke them --- .env.example | 2 + config/custos.yaml | 3 + connectors/Signer/README.md | 57 ++-- connectors/Signer/internal/handlers.go | 298 ++++++++++++++++++--- connectors/Signer/internal/handlers_test.go | 199 +++++++++++++- connectors/Signer/internal/privileges.go | 1 - .../Signer/internal/privileges_integration_test.go | 2 +- connectors/Signer/pkg/signer/loader.go | 32 ++- docs/architecture.md | 136 +++++----- docs/privileges.md | 112 ++++---- 10 files changed, 630 insertions(+), 212 deletions(-) diff --git a/.env.example b/.env.example index cfa8fdfb9..10d630f9a 100644 --- a/.env.example +++ b/.env.example @@ -103,3 +103,5 @@ EMAIL_TEMPLATES_DIR= # Leave SIGNER_BASE_URL empty to run without the signer routes. SIGNER_BASE_URL= +# At least 32 characters. +SIGNER_SERVICE_TOKEN= diff --git a/config/custos.yaml b/config/custos.yaml index 0af8bb9dc..5aaff2055 100644 --- a/config/custos.yaml +++ b/config/custos.yaml @@ -221,4 +221,7 @@ connectors: type: "signer" enabled: true base_url: "${SIGNER_BASE_URL}" + service_token: "${SIGNER_SERVICE_TOKEN}" + cluster_id: "${CUSTOS_CLUSTER_ID}" + certificate_ttl_seconds: 28800 timeout_seconds: 10 diff --git a/connectors/Signer/README.md b/connectors/Signer/README.md index 5a1d31dec..950cfebd2 100644 --- a/connectors/Signer/README.md +++ b/connectors/Signer/README.md @@ -19,32 +19,45 @@ # Signer -The Signer connector puts the [SSH certificate signer](../../extensions/SSH-Certificate-Signer/README.md) behind the -Custos server. It registers the `signer:` privileges and forwards the certificate routes to the signer with the caller's -own token, so the signer applies its owner and privilege checks to the real user. +The Signer connector is the only caller of +the [SSH certificate signer](../../extensions/SSH-Certificate-Signer/README.md). +It decides who may have a certificate, then calls the signer with one service token. The caller's own token never goes +to the signer. To offer the signer without the rest of Custos, enable only this connector. ## Routes -| Route | Needs | Forwards to | -|--------------------------------------------------------|-----------------------------|-------------------------------------------------------------------| -| `GET /connectors/signer/certificates` | `signer:certificates:read` | `GET /api/v1/admin/certificates` | -| `GET /connectors/signer/certificates/{serial}` | `signer:certificates:read` | `GET /api/v1/admin/certificates/{serial}` | -| `POST /connectors/signer/certificates/{serial}/revoke` | `signer:certificates:write` | `POST /api/v1/certificates/{serial}/revoke` | -| `GET /connectors/signer/me/certificates` | Signed in | `GET /api/v1/certificates` | -| `GET /connectors/signer/me/certificates/{serial}` | Signed in | `GET /api/v1/certificates/{serial}` | -| `GET /connectors/signer/status` | `signer:certificates:read` | Reports whether the signer answers its health route, and how fast | - -Query strings, request bodies and the signer's response pass through unchanged. The certificate list is keyset-paged: -pass `limit` and the last `next_cursor` as `cursor`. A signer that cannot be reached returns 502. +| Route | Needs | Does | +|-----------------------------------------------------------|-----------------------------|---------------------------------------------------------------| +| `GET /connectors/signer/certificates` | `signer:certificates:read` | All certificates | +| `GET /connectors/signer/certificates/{serial}` | `signer:certificates:read` | Any certificate | +| `POST /connectors/signer/certificates/{serial}/revoke` | `signer:certificates:write` | Revoke any certificate, recorded under the email of the admin | +| `GET /connectors/signer/me/certificates` | Signed in | The caller's own certificates | +| `POST /connectors/signer/me/certificates` | Signed in | Generate a certificate for the caller's account | +| `GET /connectors/signer/me/certificates/{serial}` | Signed in | One of the caller's own certificates | +| `POST /connectors/signer/me/certificates/{serial}/revoke` | Signed in | Revoke one of the caller's own, recorded as `self` | +| `GET /connectors/signer/status` | `signer:certificates:read` | Whether the signer answers its health route, and how fast | + +The certificate lists are keyset-paged: pass `limit` and the last `next_cursor` as `cursor`. Someone else's certificate +on a `me` route is a 404. + +To generate, the caller needs an approved and provisioned cluster account on `cluster_id`, and an active membership in +an +active allocation on that cluster. The username comes from the cluster account, and the email and subject from the +caller's verified token, never from the request. + +A refusal has an `error` code: `user_not_active`, `no_cluster_account`, `cluster_account_not_ready`, +`no_active_allocation`, `signer_unavailable`, or from the signer `reserved_username`, `invalid_public_key` and +`key_type_not_allowed`. ## Configuration -Settings are in the `connectors.signer` block of [`config/custos.yaml`](../../config/custos.yaml). With an empty -`base_url` the connector skips loading and reports the gap on `GET /connectors`. - -| Key | Variable in `config/custos.yaml` | Required | Purpose | -|-------------------|----------------------------------|----------|-------------------------------| -| `base_url` | `SIGNER_BASE_URL` | yes | The signer's URL | -| `timeout_seconds` | | no | Request timeout, default `10` | +Settings are in the `connectors.signer` block of [`config/custos.yaml`](../../config/custos.yaml). When a required +setting is empty the connector skips loading and reports the gap on `GET /connectors`. -The connector holds no signer client credentials. Those stay with the applications that call `POST /api/v1/sign`. +| Key | Variable in `config/custos.yaml` | Required | Purpose | +|---------------------------|----------------------------------|----------|------------------------------------------------| +| `base_url` | `SIGNER_BASE_URL` | yes | The signer's URL. Keep it off public networks. | +| `service_token` | `SIGNER_SERVICE_TOKEN` | yes | The same token set on the signer | +| `cluster_id` | `CUSTOS_CLUSTER_ID` | yes | The cluster certificates log in to | +| `certificate_ttl_seconds` | | no | Certificate lifetime, default `28800` | +| `timeout_seconds` | | no | Request timeout, default `10` | diff --git a/connectors/Signer/internal/handlers.go b/connectors/Signer/internal/handlers.go index 5c765f59c..3b95bfbe5 100644 --- a/connectors/Signer/internal/handlers.go +++ b/connectors/Signer/internal/handlers.go @@ -18,7 +18,9 @@ package internal import ( + "bytes" "context" + "encoding/json" "errors" "fmt" "io" @@ -31,65 +33,278 @@ import ( "github.com/apache/airavata-custos/internal/connectors/health" "github.com/apache/airavata-custos/pkg/common" "github.com/apache/airavata-custos/pkg/identity" + "github.com/apache/airavata-custos/pkg/models" + "github.com/apache/airavata-custos/pkg/service" ) const Type = "signer" -// The raw error has the signer's internal address, so callers get this instead. -var errSignerUnavailable = errors.New("signer unavailable") +const maxRequestBytes = 16 << 10 + +var errServiceTokenRefused = errors.New("signer refused the service token") + +// CoreAccounts is what the connector reads from core to decide who can generate. +type CoreAccounts interface { + GetComputeClusterUserByPair(ctx context.Context, clusterID, userID string) (*models.ComputeClusterUser, error) + ListAllocationsForUser(ctx context.Context, userID string) ([]models.ComputeAllocationMembership, error) + GetComputeAllocation(ctx context.Context, id string) (*models.ComputeAllocation, error) +} + +type Config struct { + BaseURL string + ServiceToken string + ClusterID string + TTLSeconds int + Timeout time.Duration +} type Handlers struct { - client *http.Client - baseURL string + client *http.Client + cfg Config + core CoreAccounts } -func NewHandlers(baseURL string, timeout time.Duration) *Handlers { - return &Handlers{ - client: &http.Client{Timeout: timeout}, - baseURL: strings.TrimSuffix(baseURL, "/"), - } +func NewHandlers(cfg Config, core CoreAccounts) *Handlers { + cfg.BaseURL = strings.TrimSuffix(cfg.BaseURL, "/") + return &Handlers{client: &http.Client{Timeout: cfg.Timeout}, cfg: cfg, core: core} } func (h *Handlers) RegisterRoutes(router *identity.Router) { - router.RequirePrivilege("GET /connectors/signer/certificates", CertificatesRead, h.forwardTo("/api/v1/admin/certificates")) - router.RequirePrivilege("GET /connectors/signer/certificates/{serial}", CertificatesRead, h.forwardTo("/api/v1/admin/certificates/{serial}")) - router.RequirePrivilege("POST /connectors/signer/certificates/{serial}/revoke", CertificatesWrite, h.forwardTo("/api/v1/certificates/{serial}/revoke")) - router.RequireAuth("GET /connectors/signer/me/certificates", h.forwardTo("/api/v1/certificates")) - router.RequireAuth("GET /connectors/signer/me/certificates/{serial}", h.forwardTo("/api/v1/certificates/{serial}")) + router.RequirePrivilege("GET /connectors/signer/certificates", CertificatesRead, h.listAllCertificates) + router.RequirePrivilege("GET /connectors/signer/certificates/{serial}", CertificatesRead, h.getAnyCertificate) + router.RequirePrivilege("POST /connectors/signer/certificates/{serial}/revoke", CertificatesWrite, h.revokeAnyCertificate) + router.RequireAuth("GET /connectors/signer/me/certificates", h.listOwnCertificates) + router.RequireAuth("POST /connectors/signer/me/certificates", h.generateCertificate) + router.RequireAuth("GET /connectors/signer/me/certificates/{serial}", h.getOwnCertificate) + router.RequireAuth("POST /connectors/signer/me/certificates/{serial}/revoke", h.revokeOwnCertificate) router.RequirePrivilege("GET /connectors/signer/status", CertificatesRead, h.status) } -// The caller's own token goes to the signer, so the signer checks the real user. -func (h *Handlers) forwardTo(path string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - target := h.baseURL + strings.Replace(path, "{serial}", url.PathEscape(r.PathValue("serial")), 1) - if r.URL.RawQuery != "" { - target += "?" + r.URL.RawQuery - } - req, err := http.NewRequestWithContext(r.Context(), r.Method, target, r.Body) +func refuse(w http.ResponseWriter, status int, code, message string) { + common.WriteJSON(w, status, map[string]string{"error": code, "message": message}) +} + +func signerUnavailable(w http.ResponseWriter) { + refuse(w, http.StatusBadGateway, "signer_unavailable", "The certificate service cannot be reached") +} + +func certificatePath(r *http.Request) string { + return "/api/v1/certificates/" + url.PathEscape(r.PathValue("serial")) +} + +// requireClaims writes the refusal and returns nil if the token does not say who the caller is. +func requireClaims(w http.ResponseWriter, r *http.Request) *identity.Claims { + claims := identity.ClaimsFromContext(r.Context()) + if claims == nil || claims.Sub == "" || claims.Email == "" { + refuse(w, http.StatusForbidden, "user_not_active", "Your account cannot do this") + return nil + } + return claims +} + +// The caller's own token never goes to the signer. +func (h *Handlers) callSigner(ctx context.Context, method, path string, body any) (*http.Response, error) { + var payload io.Reader + if body != nil { + encoded, err := json.Marshal(body) if err != nil { - common.WriteError(w, http.StatusInternalServerError, errSignerUnavailable) - return + return nil, err } - req.Header.Set("Authorization", r.Header.Get("Authorization")) - if ct := r.Header.Get("Content-Type"); ct != "" { - req.Header.Set("Content-Type", ct) + payload = bytes.NewReader(encoded) + } + req, err := http.NewRequestWithContext(ctx, method, h.cfg.BaseURL+path, payload) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+h.cfg.ServiceToken) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := h.client.Do(req) + if err == nil && resp.StatusCode == http.StatusUnauthorized { + resp.Body.Close() + err = errServiceTokenRefused + } + health.Record(Type, Type, callResult(resp, err)) + if err != nil { + slog.Warn("signer request failed", "path", path, "error", err) + return nil, err + } + return resp, nil +} + +func copyResponse(w http.ResponseWriter, resp *http.Response) { + w.Header().Set("Content-Type", resp.Header.Get("Content-Type")) + w.WriteHeader(resp.StatusCode) + io.Copy(w, resp.Body) +} + +func (h *Handlers) relay(w http.ResponseWriter, r *http.Request, method, path string, body any) { + resp, err := h.callSigner(r.Context(), method, path, body) + if err != nil { + signerUnavailable(w) + return + } + defer resp.Body.Close() + copyResponse(w, resp) +} + +func (h *Handlers) listAllCertificates(w http.ResponseWriter, r *http.Request) { + h.relay(w, r, http.MethodGet, "/api/v1/certificates?"+r.URL.RawQuery, nil) +} + +func (h *Handlers) getAnyCertificate(w http.ResponseWriter, r *http.Request) { + h.relay(w, r, http.MethodGet, certificatePath(r), nil) +} + +func (h *Handlers) revokeAnyCertificate(w http.ResponseWriter, r *http.Request) { + if claims := requireClaims(w, r); claims != nil { + h.revoke(w, r, claims.Email) + } +} + +// revokedBy is the admin's email, or "self" when users revoke their own. +func (h *Handlers) revoke(w http.ResponseWriter, r *http.Request, revokedBy string) { + var req struct { + Reason string `json:"reason"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBytes)).Decode(&req); err != nil && !errors.Is(err, io.EOF) { + refuse(w, http.StatusBadRequest, "invalid_request", "Invalid request body") + return + } + h.relay(w, r, http.MethodPost, certificatePath(r)+"/revoke", map[string]string{"reason": req.Reason, "revoked_by": revokedBy}) +} + +func (h *Handlers) listOwnCertificates(w http.ResponseWriter, r *http.Request) { + claims := requireClaims(w, r) + if claims == nil { + return + } + query := r.URL.Query() + query.Set("user_sub", claims.Sub) + h.relay(w, r, http.MethodGet, "/api/v1/certificates?"+query.Encode(), nil) +} + +// fetchIfOwned extracts own certificate from the Signer and returns false if it is not the caller's. +func (h *Handlers) fetchIfOwned(w http.ResponseWriter, r *http.Request) ([]byte, bool) { + claims := requireClaims(w, r) + if claims == nil { + return nil, false + } + resp, err := h.callSigner(r.Context(), http.MethodGet, certificatePath(r), nil) + if err != nil { + signerUnavailable(w) + return nil, false + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + copyResponse(w, resp) + return nil, false + } + body, err := io.ReadAll(resp.Body) + if err != nil { + signerUnavailable(w) + return nil, false + } + var certificate struct { + UserSub string `json:"user_sub"` + } + if err := json.Unmarshal(body, &certificate); err != nil { + signerUnavailable(w) + return nil, false + } + if certificate.UserSub != claims.Sub { + refuse(w, http.StatusNotFound, "not_found", "Certificate not found") + return nil, false + } + return body, true +} + +func (h *Handlers) getOwnCertificate(w http.ResponseWriter, r *http.Request) { + body, ok := h.fetchIfOwned(w, r) + if !ok { + return + } + w.Header().Set("Content-Type", "application/json") + w.Write(body) +} + +func (h *Handlers) revokeOwnCertificate(w http.ResponseWriter, r *http.Request) { + if _, ok := h.fetchIfOwned(w, r); ok { + h.revoke(w, r, "self") + } +} + +func (h *Handlers) generateCertificate(w http.ResponseWriter, r *http.Request) { + claims := requireClaims(w, r) + if claims == nil { + return + } + userID := identity.CallerFromContext(r.Context()).UserID + var req struct { + PublicKey string `json:"public_key"` + } + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBytes)).Decode(&req); err != nil || req.PublicKey == "" { + refuse(w, http.StatusBadRequest, "invalid_public_key", "A public key is required") + return + } + username, code, err := h.loginName(r.Context(), userID) + if err != nil { + slog.Error("signer: reading the caller's account failed", "error", err) + refuse(w, http.StatusInternalServerError, "internal_error", "Could not read your account") + return + } + if code != "" { + refuse(w, http.StatusForbidden, code, "Your account cannot generate a certificate") + return + } + h.relay(w, r, http.MethodPost, "/api/v1/sign", map[string]any{ + "principal": username, + "public_key": req.PublicKey, + "ttl_seconds": h.cfg.TTLSeconds, + "user_email": claims.Email, + "user_sub": claims.Sub, + "requested_by": "user/" + userID, + }) +} + +// loginName returns the username to sign for. +func (h *Handlers) loginName(ctx context.Context, userID string) (username, code string, err error) { + account, err := h.core.GetComputeClusterUserByPair(ctx, h.cfg.ClusterID, userID) + if errors.Is(err, service.ErrNotFound) { + return "", "no_cluster_account", nil + } + if err != nil { + return "", "", err + } + if account.ApprovalStatus != models.ClusterAccountApproved || account.ProvisionedAt == nil { + return "", "cluster_account_not_ready", nil + } + memberships, err := h.core.ListAllocationsForUser(ctx, userID) + if err != nil { + return "", "", err + } + now := time.Now() + for _, membership := range memberships { + if !activeAt(now, membership.MembershipStatus, membership.StartTime, membership.EndTime) { + continue } - resp, err := h.client.Do(req) - health.Record(Type, Type, callResult(resp, err)) + allocation, err := h.core.GetComputeAllocation(ctx, membership.ComputeAllocationID) if err != nil { - slog.Warn("signer request failed", "path", path, "error", err) - common.WriteError(w, http.StatusBadGateway, errSignerUnavailable) - return + return "", "", err + } + if allocation.ComputeClusterID == h.cfg.ClusterID && activeAt(now, allocation.Status, allocation.StartTime, allocation.EndTime) { + return account.LocalUsername, "", nil } - defer resp.Body.Close() - w.Header().Set("Content-Type", resp.Header.Get("Content-Type")) - w.WriteHeader(resp.StatusCode) - io.Copy(w, resp.Body) } + return "", "no_active_allocation", nil +} + +func activeAt(now time.Time, status models.AllocationStatus, start, end time.Time) bool { + return status == models.ACTIVE && !now.Before(start) && now.Before(end) } -// A 5xx counts as a failure. A 4xx is the signer working and refusing the caller. +// A 5xx counts as a failure. A 4xx is the signer working and refusing the request. func callResult(resp *http.Response, err error) error { if err == nil && resp.StatusCode >= http.StatusInternalServerError { return fmt.Errorf("signer returned %d", resp.StatusCode) @@ -98,13 +313,12 @@ func callResult(resp *http.Response, err error) error { } type statusResponse struct { - Reachable bool `json:"reachable"` - LatencyMs int64 `json:"latency_ms"` - BaseURL string `json:"base_url"` + Reachable bool `json:"reachable"` + LatencyMs int64 `json:"latency_ms"` } func (h *Handlers) CheckHealth(ctx context.Context) error { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.baseURL+"/api/v1/health", nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.cfg.BaseURL+"/api/v1/health", nil) if err != nil { return err } @@ -123,5 +337,5 @@ func (h *Handlers) CheckHealth(ctx context.Context) error { func (h *Handlers) status(w http.ResponseWriter, r *http.Request) { start := time.Now() err := h.CheckHealth(r.Context()) - common.WriteJSON(w, http.StatusOK, statusResponse{Reachable: err == nil, LatencyMs: time.Since(start).Milliseconds(), BaseURL: h.baseURL}) + common.WriteJSON(w, http.StatusOK, statusResponse{Reachable: err == nil, LatencyMs: time.Since(start).Milliseconds()}) } diff --git a/connectors/Signer/internal/handlers_test.go b/connectors/Signer/internal/handlers_test.go index 18e22e5ec..1999fd765 100644 --- a/connectors/Signer/internal/handlers_test.go +++ b/connectors/Signer/internal/handlers_test.go @@ -18,6 +18,7 @@ package internal import ( + "context" "encoding/json" "io" "net/http" @@ -29,11 +30,17 @@ import ( "github.com/apache/airavata-custos/internal/connectors/health" "github.com/apache/airavata-custos/pkg/identity" "github.com/apache/airavata-custos/pkg/models" + "github.com/apache/airavata-custos/pkg/service" +) + +const ( + testClusterID = "cluster-1" + testSub = "sub-of-jdoe" ) // signerCall is what the fake signer saw on its last request. type signerCall struct { - path, query, auth string + method, path, query, auth, body string } // mockSignerServer stands in for the signer. Health is always ok. Every other path gets the status and body the test gives it. @@ -41,7 +48,8 @@ func mockSignerServer(t *testing.T, status int, body string) (*httptest.Server, t.Helper() seen := &signerCall{} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - *seen = signerCall{r.URL.Path, r.URL.RawQuery, r.Header.Get("Authorization")} + sent, _ := io.ReadAll(r.Body) + *seen = signerCall{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Get("Authorization"), string(sent)} w.Header().Set("Content-Type", "application/json") if r.URL.Path == "/api/v1/health" { w.Write([]byte(`{"status":"ok"}`)) @@ -54,30 +62,185 @@ func mockSignerServer(t *testing.T, status int, body string) (*httptest.Server, return srv, seen } -func serve(baseURL string, r *http.Request, privs ...models.PrivilegeKey) *httptest.ResponseRecorder { +// fakeCore stands in for core. The zero value is a user with no account. +type fakeCore struct { + account *models.ComputeClusterUser + memberships []models.ComputeAllocationMembership + allocation models.ComputeAllocation +} + +func (f *fakeCore) GetComputeClusterUserByPair(context.Context, string, string) (*models.ComputeClusterUser, error) { + if f.account == nil { + return nil, service.ErrNotFound + } + return f.account, nil +} + +func (f *fakeCore) ListAllocationsForUser(context.Context, string) ([]models.ComputeAllocationMembership, error) { + return f.memberships, nil +} + +func (f *fakeCore) GetComputeAllocation(context.Context, string) (*models.ComputeAllocation, error) { + return &f.allocation, nil +} + +// readyCore is a user who can generate certificates +func readyCore() *fakeCore { + provisioned := time.Now().Add(-time.Hour) + start, end := time.Now().Add(-time.Hour), time.Now().Add(time.Hour) + return &fakeCore{ + account: &models.ComputeClusterUser{LocalUsername: "jdoe", ApprovalStatus: models.ClusterAccountApproved, ProvisionedAt: &provisioned}, + memberships: []models.ComputeAllocationMembership{{ComputeAllocationID: "a1", MembershipStatus: models.ACTIVE, StartTime: start, EndTime: end}}, + allocation: models.ComputeAllocation{ComputeClusterID: testClusterID, Status: models.ACTIVE, StartTime: start, EndTime: end}, + } +} + +func serveWith(core CoreAccounts, baseURL string, r *http.Request, privs ...models.PrivilegeKey) *httptest.ResponseRecorder { mux := http.NewServeMux() - NewHandlers(baseURL, 2*time.Second).RegisterRoutes(identity.NewRouter(mux)) + NewHandlers(Config{BaseURL: baseURL, ServiceToken: "service-token", ClusterID: testClusterID, TTLSeconds: 3600, Timeout: 2 * time.Second}, core).RegisterRoutes(identity.NewRouter(mux)) r.Header.Set("Authorization", "Bearer user-token") - r = r.WithContext(identity.WithPrivilegesForTest(r.Context(), privs)) + ctx := identity.WithCaller(r.Context(), &identity.Caller{UserID: "user-1"}) + ctx = identity.WithClaims(ctx, &identity.Claims{Sub: testSub, Email: "[email protected]"}) + r = r.WithContext(identity.WithPrivilegesForTest(ctx, privs)) rec := httptest.NewRecorder() mux.ServeHTTP(rec, r) return rec } -// Make sure the caller's token and paging go to the signer, and the signer's answer comes back unchanged. -func TestCertificates_ForwardsCallerTokenAndPaging(t *testing.T) { - srv, seen := mockSignerServer(t, http.StatusOK, `{"items":[],"next_cursor":"c2"}`) +func serve(baseURL string, r *http.Request, privs ...models.PrivilegeKey) *httptest.ResponseRecorder { + return serveWith(readyCore(), baseURL, r, privs...) +} + +func errorCode(t *testing.T, rec *httptest.ResponseRecorder) string { + t.Helper() + var body struct { + Error string `json:"error"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("body %s: %v", rec.Body, err) + } + return body.Error +} + +// Make sure the signer gets the service token. +func TestCertificates_UsesServiceTokenAndPaging(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{"certificates":[],"next_cursor":"c2"}`) rec := serve(srv.URL, httptest.NewRequest(http.MethodGet, "/connectors/signer/certificates?limit=20&cursor=c1", nil), CertificatesRead) - if seen.path != "/api/v1/admin/certificates" || seen.query != "limit=20&cursor=c1" || seen.auth != "Bearer user-token" { + if seen.path != "/api/v1/certificates" || seen.query != "limit=20&cursor=c1" || seen.auth != "Bearer service-token" { t.Fatalf("signer got %+v", *seen) } - if rec.Code != http.StatusOK || rec.Body.String() != `{"items":[],"next_cursor":"c2"}` { + if rec.Code != http.StatusOK || rec.Body.String() != `{"certificates":[],"next_cursor":"c2"}` { t.Fatalf("got %d %s", rec.Code, rec.Body) } } +// Make sure the username comes from the cluster account and who it is for comes from the verified token. +func TestGenerate_SignsForTheCallersOwnAccount(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{"certificate":"[email protected] AAAA"}`) + + body := `{"public_key":"ssh-ed25519 AAAA","principal":"root","user_email":"[email protected]","user_sub":"someone"}` + rec := serve(srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates", strings.NewReader(body))) + + if rec.Code != http.StatusOK || seen.path != "/api/v1/sign" { + t.Fatalf("got %d, signer saw %+v", rec.Code, *seen) + } + var sent map[string]any + if err := json.Unmarshal([]byte(seen.body), &sent); err != nil { + t.Fatal(err) + } + if sent["principal"] != "jdoe" || sent["user_email"] != "[email protected]" || sent["user_sub"] != testSub || sent["ttl_seconds"] != float64(3600) { + t.Fatalf("signer got %v", sent) + } + if sent["requested_by"] != "user/user-1" { + t.Fatalf("requested_by = %v", sent["requested_by"]) + } +} + +// Only with an active account and allocation can generate certificates. +func TestGenerate_RefusesWithoutAccountOrAllocation(t *testing.T) { + expired := func(core *fakeCore) { core.memberships[0].EndTime = time.Now().Add(-time.Minute) } + cases := []struct { + name string + change func(*fakeCore) + code string + }{ + {"no cluster account", func(c *fakeCore) { c.account = nil }, "no_cluster_account"}, + {"account not approved", func(c *fakeCore) { c.account.ApprovalStatus = models.ClusterAccountPending }, "cluster_account_not_ready"}, + {"account not provisioned", func(c *fakeCore) { c.account.ProvisionedAt = nil }, "cluster_account_not_ready"}, + {"no memberships", func(c *fakeCore) { c.memberships = nil }, "no_active_allocation"}, + {"membership expired", expired, "no_active_allocation"}, + {"allocation on another cluster", func(c *fakeCore) { c.allocation.ComputeClusterID = "other" }, "no_active_allocation"}, + {"allocation inactive", func(c *fakeCore) { c.allocation.Status = models.INACTIVE }, "no_active_allocation"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{}`) + core := readyCore() + tc.change(core) + + rec := serveWith(core, srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates", strings.NewReader(`{"public_key":"k"}`))) + + if rec.Code != http.StatusForbidden || errorCode(t, rec) != tc.code || seen.path != "" { + t.Fatalf("got %d %s, signer saw %q", rec.Code, rec.Body, seen.path) + } + }) + } +} + +// Make sure the own list is always filtered to the caller. +func TestListOwn_AlwaysFiltersToTheCaller(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{"certificates":[]}`) + + serve(srv.URL, httptest.NewRequest(http.MethodGet, "/connectors/signer/me/certificates?user_sub=someone-else&limit=5", nil)) + + if seen.query != "limit=5&user_sub="+testSub { + t.Fatalf("signer got query %q", seen.query) + } +} + +// Make sure a user cannot see or revoke someone else's certificate and gets the same response when there's none existing. +func TestOwnRoutes_HideOtherUsersCertificates(t *testing.T) { + requests := map[string]*http.Request{ + "get": httptest.NewRequest(http.MethodGet, "/connectors/signer/me/certificates/42", nil), + "revoke": httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates/42/revoke", strings.NewReader(`{}`)), + } + for name, r := range requests { + t.Run(name, func(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{"user_sub":"someone-else"}`) + + rec := serve(srv.URL, r) + + if rec.Code != http.StatusNotFound || seen.method != http.MethodGet { + t.Fatalf("got %d, last signer call %+v", rec.Code, *seen) + } + }) + } +} + +// Make sure a user can revoke their own certificate with no privilege, recorded as self. +func TestRevokeOwn_RecordedAsSelf(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{"user_sub":"`+testSub+`"}`) + + rec := serve(srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/me/certificates/42/revoke", strings.NewReader(`{}`))) + + if rec.Code != http.StatusOK || seen.path != "/api/v1/certificates/42/revoke" || !strings.Contains(seen.body, `"revoked_by":"self"`) { + t.Fatalf("got %d, signer saw %+v", rec.Code, *seen) + } +} + +// Make sure an admin revoke is recorded under the admin's email. +func TestRevokeAny_RecordedAsTheAdmin(t *testing.T) { + srv, seen := mockSignerServer(t, http.StatusOK, `{}`) + + serve(srv.URL, httptest.NewRequest(http.MethodPost, "/connectors/signer/certificates/42/revoke", strings.NewReader(`{"reason":"lost laptop"}`)), CertificatesWrite) + + if !strings.Contains(seen.body, `"revoked_by":"[email protected]"`) || !strings.Contains(seen.body, `"reason":"lost laptop"`) { + t.Fatalf("signer got %s", seen.body) + } +} + // Make sure a caller without the write privilege cannot revoke, and the signer is never called. func TestRevoke_WithoutWritePrivilegeNeverReachesSigner(t *testing.T) { srv, seen := mockSignerServer(t, http.StatusOK, `{}`) @@ -99,7 +262,7 @@ func TestStatus_ReportsReachable(t *testing.T) { if err := json.NewDecoder(rec.Body).Decode(&got); err != nil { t.Fatal(err) } - if !got.Reachable || got.BaseURL != srv.URL { + if !got.Reachable { t.Fatalf("got %+v", got) } if seen.path != "/api/v1/health" || seen.auth != "" { @@ -119,6 +282,18 @@ func TestForward_SignerServerErrorRecordsFailedCheck(t *testing.T) { } } +// Make sure a wrong service token shows as a failed check and the caller sees signer_unavailable. +func TestForward_RefusedServiceTokenIsAnOutage(t *testing.T) { + srv, _ := mockSignerServer(t, http.StatusUnauthorized, `{"error":"unauthorized"}`) + + rec := serve(srv.URL, httptest.NewRequest(http.MethodGet, "/connectors/signer/me/certificates", nil)) + + checks := health.For(Type) + if rec.Code != http.StatusBadGateway || errorCode(t, rec) != "signer_unavailable" || len(checks) != 1 || checks[0].OK { + t.Fatalf("got %d %s, checks %+v", rec.Code, rec.Body, checks) + } +} + // Make sure a signer that is down does not show its internal address to the caller. func TestForward_SignerDownHidesItsAddress(t *testing.T) { srv, _ := mockSignerServer(t, http.StatusOK, `{}`) @@ -126,7 +301,7 @@ func TestForward_SignerDownHidesItsAddress(t *testing.T) { rec := serve(srv.URL, httptest.NewRequest(http.MethodGet, "/connectors/signer/me/certificates", nil)) - if rec.Code != http.StatusBadGateway || strings.Contains(rec.Body.String(), srv.Listener.Addr().String()) { + if rec.Code != http.StatusBadGateway || errorCode(t, rec) != "signer_unavailable" || strings.Contains(rec.Body.String(), srv.Listener.Addr().String()) { t.Fatalf("got %d %s", rec.Code, rec.Body) } } diff --git a/connectors/Signer/internal/privileges.go b/connectors/Signer/internal/privileges.go index f072ca236..d6ecbc0f9 100644 --- a/connectors/Signer/internal/privileges.go +++ b/connectors/Signer/internal/privileges.go @@ -19,7 +19,6 @@ package internal import "github.com/apache/airavata-custos/pkg/models" -// The signer checks these same keys on the caller's /me, so they must match its names. const ( CertificatesRead models.PrivilegeKey = "signer:certificates:read" CertificatesWrite models.PrivilegeKey = "signer:certificates:write" diff --git a/connectors/Signer/internal/privileges_integration_test.go b/connectors/Signer/internal/privileges_integration_test.go index eb63a0f25..b28044834 100644 --- a/connectors/Signer/internal/privileges_integration_test.go +++ b/connectors/Signer/internal/privileges_integration_test.go @@ -33,7 +33,7 @@ import ( coreservice "github.com/apache/airavata-custos/pkg/service" ) -// Make sure the super admin holds the signer privileges and can grant read to another user, since the signer reads these keys from that user's /me. +// Make sure the super admin holds the signer privileges and can grant read to another user. func TestSignerPrivileges_GrantableAndHeldBySuperAdmin(t *testing.T) { dsn := os.Getenv("CORE_TEST_DATABASE_DSN") if dsn == "" { diff --git a/connectors/Signer/pkg/signer/loader.go b/connectors/Signer/pkg/signer/loader.go index 8643b733d..521c1f1bf 100644 --- a/connectors/Signer/pkg/signer/loader.go +++ b/connectors/Signer/pkg/signer/loader.go @@ -19,7 +19,7 @@ package signer import ( "context" - "errors" + "fmt" "log/slog" "sync" "time" @@ -36,21 +36,35 @@ import ( const Type = internal.Type -func LoadConnector(ctx context.Context, _ *sqlx.DB, _ *events.Bus, _ *service.Service, _ *sync.WaitGroup, router *identity.Router, cfg *config.ConnectorConfig) error { - baseURL, _ := cfg.GetStringField("base_url") - if baseURL == "" { - slog.Info("signer: base_url not set; skipping") - health.Record(Type, "config", errors.New("required setting base_url not set")) - return nil +func LoadConnector(ctx context.Context, _ *sqlx.DB, _ *events.Bus, core *service.Service, _ *sync.WaitGroup, router *identity.Router, cfg *config.ConnectorConfig) error { + settings := make(map[string]string, 3) + for _, key := range []string{"base_url", "service_token", "cluster_id"} { + value, _ := cfg.GetStringField(key) + if value == "" { + slog.Info("signer: required setting not set; skipping", "setting", key) + health.Record(Type, "config", fmt.Errorf("required setting %s not set", key)) + return nil + } + settings[key] = value } timeout, err := cfg.GetIntField("timeout_seconds") if err != nil { timeout = 10 } - handlers := internal.NewHandlers(baseURL, time.Duration(timeout)*time.Second) + ttl, err := cfg.GetIntField("certificate_ttl_seconds") + if err != nil { + ttl = 28800 + } + handlers := internal.NewHandlers(internal.Config{ + BaseURL: settings["base_url"], + ServiceToken: settings["service_token"], + ClusterID: settings["cluster_id"], + TTLSeconds: ttl, + Timeout: time.Duration(timeout) * time.Second, + }, core) handlers.RegisterRoutes(router) // In the background so a down signer does not hold up startup. go handlers.CheckHealth(ctx) - slog.Info("signer: routes registered", "base_url", baseURL) + slog.Info("signer: routes registered", "base_url", settings["base_url"]) return nil } diff --git a/docs/architecture.md b/docs/architecture.md index 95b506b0e..d6f619bd4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -26,11 +26,11 @@ write a connector. Only three parts of Custos are fixed: -| Part | What it is | -|---|---| -| Core records | Users, organizations, projects, allocations, memberships and cluster accounts, in PostgreSQL | +| Part | What it is | +|---------------|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Core records | Users, organizations, projects, allocations, memberships and cluster accounts, in PostgreSQL | | State machine | The service layer in `pkg/service`. It is the only code that changes the records, for example by approving a cluster account or deactivating a membership. | -| Event bus | `pkg/events`. The service layer publishes each change as an event in the same transaction. The bus delivers it to each subscriber with retries. | +| Event bus | `pkg/events`. The service layer publishes each change as an event in the same transaction. The bus delivers it to each subscriber with retries. | Everything that talks to another system is a connector: allocation intake from ACCESS, accounts in COmanage, SLURM associations, storage on VAST, email. No connector is required. A site enables one with a block in @@ -58,17 +58,17 @@ airavata-custos/ └── dev-ops/ # Local Compose stack, Terraform, Ansible ``` -| Directory | Contents | Examples | -|---|---|---| -| `cmd/server` | Opens the database, runs migrations, builds the service, loads connectors and serves HTTP | `main.go`, `bootstrap.go` | -| `pkg` | Contracts that connectors build on. `service.Service` is the domain API; `events.Bus` carries domain events | `pkg/models`, `pkg/service`, `pkg/events`, `pkg/identity` | -| `internal` | Code private to the server module | `internal/server` (handlers), `internal/store`, `internal/db/migrations`, `internal/connectors/loader.go` | -| `connectors` | Packages compiled into the server, one per external system | `ACCESS/AMIE-Processor`, `SLURM/Association-Mapper` | -| `extensions` | Separate processes a site deploys if it wants them | `CILogon-SSH-PAM`, `SSH-Certificate-Signer` | -| `api` | `core.openapi.yaml`, generated from handler annotations | [`api/README.md`](../api/README.md) | -| `config` | `custos.yaml`, with `${VAR}` interpolation for secrets | [`CONFIG.md`](../CONFIG.md) | -| `web` | The portal that calls the REST API | [`web/README.md`](../web/README.md) | -| `dev-ops` | Local dev stack and deployment automation | `compose/`, `terraform/`, `account-provisioning/`, `local-amie/` | +| Directory | Contents | Examples | +|--------------|-------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------| +| `cmd/server` | Opens the database, runs migrations, builds the service, loads connectors and serves HTTP | `main.go`, `bootstrap.go` | +| `pkg` | Contracts that connectors build on. `service.Service` is the domain API; `events.Bus` carries domain events | `pkg/models`, `pkg/service`, `pkg/events`, `pkg/identity` | +| `internal` | Code private to the server module | `internal/server` (handlers), `internal/store`, `internal/db/migrations`, `internal/connectors/loader.go` | +| `connectors` | Packages compiled into the server, one per external system | `ACCESS/AMIE-Processor`, `SLURM/Association-Mapper` | +| `extensions` | Separate processes a site deploys if it wants them | `CILogon-SSH-PAM`, `SSH-Certificate-Signer` | +| `api` | `core.openapi.yaml`, generated from handler annotations | [`api/README.md`](../api/README.md) | +| `config` | `custos.yaml`, with `${VAR}` interpolation for secrets | [`CONFIG.md`](../CONFIG.md) | +| `web` | The portal that calls the REST API | [`web/README.md`](../web/README.md) | +| `dev-ops` | Local dev stack and deployment automation | `compose/`, `terraform/`, `account-provisioning/`, `local-amie/` | ## Runtime topology @@ -94,17 +94,17 @@ shutdown the HTTP server gets 15 seconds to finish in-flight requests. The serve ### Connectors in the tree -| `type:` in config | Directory | Role | -|---|---|---| -| `amie-processor` | `connectors/ACCESS/AMIE-Processor` | Polls ACCESS-CI AMIE packets, applies them to core and sends replies | -| `comanage-identity-provisioner` | `connectors/COmanage/Identity-Provisioner` | Provisions approved cluster accounts and allocation groups in COmanage | -| `slurm-association-mapper` | `connectors/SLURM/Association-Mapper` | Mirrors allocation membership into SLURM accounts and associations | -| `slurm-usage-monitor` | `connectors/SLURM/Usage-Monitor` | Polls `slurmrestd` for finished jobs and records usage in core | -| `vast-storage-provisioner` | `connectors/Storage/VAST-Provisioner` | Creates directories, views and quotas on VAST | -| `email-notifier` | `connectors/Notification/Email` | Emails users about their cluster account requests | -| `analytics` | `connectors/Analytics` | Usage summaries and job lists for allocation participants | -| `temp-account` | `connectors/TempAccount` | Creates temporary accounts and assigns them allocations | -| `signer` | `connectors/Signer` | Forwards certificate list and revoke calls to the SSH certificate signer | +| `type:` in config | Directory | Role | +|---------------------------------|--------------------------------------------|---------------------------------------------------------------------------------------| +| `amie-processor` | `connectors/ACCESS/AMIE-Processor` | Polls ACCESS-CI AMIE packets, applies them to core and sends replies | +| `comanage-identity-provisioner` | `connectors/COmanage/Identity-Provisioner` | Provisions approved cluster accounts and allocation groups in COmanage | +| `slurm-association-mapper` | `connectors/SLURM/Association-Mapper` | Mirrors allocation membership into SLURM accounts and associations | +| `slurm-usage-monitor` | `connectors/SLURM/Usage-Monitor` | Polls `slurmrestd` for finished jobs and records usage in core | +| `vast-storage-provisioner` | `connectors/Storage/VAST-Provisioner` | Creates directories, views and quotas on VAST | +| `email-notifier` | `connectors/Notification/Email` | Emails users about their cluster account requests | +| `analytics` | `connectors/Analytics` | Usage summaries and job lists for allocation participants | +| `temp-account` | `connectors/TempAccount` | Creates temporary accounts and assigns them allocations | +| `signer` | `connectors/Signer` | Decides who may have an SSH certificate and calls the signer to issue and revoke them | `connectors/SLURM/Rest-Client` is the shared `slurmrestd` client library, not a connector. `GET /connectors` lists the configured connectors with their load status and requires `core:clusters:read`. @@ -117,10 +117,10 @@ The SLURM, VAST and account-ready email steps wait until the COmanage connector Extensions are separate processes that `LoadConnectorsFromConfig` does not load. Each has its own OIDC configuration. -| Extension | What it does | Relation to core | -|---|---|---| -| `CILogon-SSH-PAM` | A PAM module that lets `sshd` accept an OIDC device-flow login, CILogon at Custos sites | Does not call core | -| `SSH-Certificate-Signer` | Signs short-lived SSH certificates for OIDC-authenticated callers | Calls core `GET /me` to read the caller's privileges for its admin APIs | +| Extension | What it does | Relation to core | +|--------------------------|-----------------------------------------------------------------------------------------|-------------------------------------------------------------------------| +| `CILogon-SSH-PAM` | A PAM module that lets `sshd` accept an OIDC device-flow login, CILogon at Custos sites | Does not call core | +| `SSH-Certificate-Signer` | Signs short-lived SSH certificates for OIDC-authenticated callers | Calls core `GET /me` to read the caller's privileges for its admin APIs | ## Identity and authentication @@ -130,13 +130,13 @@ Inbound authentication is an OIDC bearer JWT. `pkg/identity/verifier.go` checks Routes register through one of five router methods: -| Method | Who gets through | Example | -|---|---|---| -| `Public(pattern, h)` | Anyone; the token is not checked | `GET /healthz` | -| `RequireAuthWithoutUserConsent(pattern, h)` | A verified caller, before onboarding or accepting the user agreement | `GET /me`, `POST /me/onboarding` | -| `RequireAuth(pattern, h)` | A verified caller who has onboarded and accepted the current agreement | `GET /projects`, `GET /compute-allocations` | -| `RequireScoped(pattern, authorize, h)` | A verified caller whom `authorize` admits for that resource | `GET /compute-allocations/{id}` | -| `RequirePrivilege(pattern, key, h)` | A verified caller who holds `key` | `POST /compute-clusters` | +| Method | Who gets through | Example | +|---------------------------------------------|------------------------------------------------------------------------|---------------------------------------------| +| `Public(pattern, h)` | Anyone; the token is not checked | `GET /healthz` | +| `RequireAuthWithoutUserConsent(pattern, h)` | A verified caller, before onboarding or accepting the user agreement | `GET /me`, `POST /me/onboarding` | +| `RequireAuth(pattern, h)` | A verified caller who has onboarded and accepted the current agreement | `GET /projects`, `GET /compute-allocations` | +| `RequireScoped(pattern, authorize, h)` | A verified caller whom `authorize` admits for that resource | `GET /compute-allocations/{id}` | +| `RequirePrivilege(pattern, key, h)` | A verified caller who holds `key` | `POST /compute-clusters` | `GET /projects` and `GET /compute-allocations` return everything to a caller with the matching read privilege and only the caller's own records otherwise. `RequireScoped` routes admit the read privilege or a participant in that @@ -144,16 +144,16 @@ project or allocation, and return `404` to anyone else. The middleware answers authentication failures with `{"code": ..., "message": ...}`: -| Status | `code` | Cause | -|---|---|---| -| `401` | `missing_bearer` | No `Authorization: Bearer` header | -| `401` | `invalid_token` | Signature, issuer, audience or expiry check failed | -| `401` | `identity_not_linked` | The token's identity matches no Custos user | -| `403` | `user_disabled` | The user is disabled | -| `403` | `onboarding_required` | First sign-in; the user has not onboarded | -| `403` | `consent_required` | A newer user agreement waits for acceptance | -| `403` | `insufficient_privilege` | The route's privilege is missing | -| `503` | `auth_lookup_failed` | Caller resolution failed | +| Status | `code` | Cause | +|--------|--------------------------|----------------------------------------------------| +| `401` | `missing_bearer` | No `Authorization: Bearer` header | +| `401` | `invalid_token` | Signature, issuer, audience or expiry check failed | +| `401` | `identity_not_linked` | The token's identity matches no Custos user | +| `403` | `user_disabled` | The user is disabled | +| `403` | `onboarding_required` | First sign-in; the user has not onboarded | +| `403` | `consent_required` | A newer user agreement waits for acceptance | +| `403` | `insufficient_privilege` | The route's privilege is missing | +| `503` | `auth_lookup_failed` | Caller resolution failed | ### Privileges @@ -169,23 +169,23 @@ through a role (`roles`, `role_privileges`, `user_roles`). `coreService.Effectiv is no external broker. A subscriber is a connector, named by its `Type` constant. Subscriptions are saved, so an event published while a connector is not loaded gets a delivery row and waits for it. -| Setting | Value | -|---|---| -| Poll interval for due deliveries | 10 seconds | -| Handler timeout | 2 minutes | -| Retry backoff | 30 seconds, doubling up to 1 hour | -| Attempts | 10 | -| Fail without retry | The handler's error wraps `events.ErrPermanent` | +| Setting | Value | +|----------------------------------|-------------------------------------------------| +| Poll interval for due deliveries | 10 seconds | +| Handler timeout | 2 minutes | +| Retry backoff | 30 seconds, doubling up to 1 hour | +| Attempts | 10 | +| Fail without retry | The handler's error wraps `events.ErrPermanent` | Handlers must be safe to run more than once for the same event. The bus worker writes an `audit_events` row for each delivery attempt, under the event's trace. Four endpoints expose the bus: -| Endpoint | Use | -|---|---| -| `GET /events/deliveries` | List deliveries | -| `POST /events/deliveries/{id}/retry` | Retry a failed delivery | -| `GET /events/subscriptions` | Show which subscribers are loaded | -| `GET /events/graph` | Show which events lead to which ([how it is built](../internal/server/eventgraph/README.md)) | +| Endpoint | Use | +|--------------------------------------|----------------------------------------------------------------------------------------------| +| `GET /events/deliveries` | List deliveries | +| `POST /events/deliveries/{id}/retry` | Retry a failed delivery | +| `GET /events/subscriptions` | Show which subscribers are loaded | +| `GET /events/graph` | Show which events lead to which ([how it is built](../internal/server/eventgraph/README.md)) | ## Worked example: approving a cluster account @@ -232,11 +232,11 @@ and same-transaction write, see ## Where to look next -| Topic | Document | -|---|---| -| Writing a connector | [`contributing/writing-a-connector.md`](contributing/writing-a-connector.md) | -| Privilege keys and the routes they gate | [`privileges.md`](privileges.md) | -| Allocation domain model | [`Allocation-Data-Models.md`](Allocation-Data-Models.md) | -| REST API | [`API-Docs.md`](API-Docs.md) | -| ACCESS-CI resource provider setup | [`ACCESS-HPC-Reference.md`](ACCESS-HPC-Reference.md) | -| Domain terms | [`glossary.md`](glossary.md) | +| Topic | Document | +|-----------------------------------------|------------------------------------------------------------------------------| +| Writing a connector | [`contributing/writing-a-connector.md`](contributing/writing-a-connector.md) | +| Privilege keys and the routes they gate | [`privileges.md`](privileges.md) | +| Allocation domain model | [`Allocation-Data-Models.md`](Allocation-Data-Models.md) | +| REST API | [`API-Docs.md`](API-Docs.md) | +| ACCESS-CI resource provider setup | [`ACCESS-HPC-Reference.md`](ACCESS-HPC-Reference.md) | +| Domain terms | [`glossary.md`](glossary.md) | diff --git a/docs/privileges.md b/docs/privileges.md index 9e6d69718..1f2c24946 100644 --- a/docs/privileges.md +++ b/docs/privileges.md @@ -36,32 +36,32 @@ A key exists only once it is registered with `models.Register(...)`. Grants and <owner>:<scope>:<action> ``` -| Segment | Meaning | Examples | -|---|---|---| -| `owner` | The component that defines and checks the key: `core`, or the connector's short name | `core`, `amie`, `temp-account` | -| `scope` | The resource inside that owner | `clusters`, `packets`, `agreements` | -| `action` | The verb: `read` for reads, `write` for mutations, `grant` or `manage` for meta operations | `read`, `write`, `grant`, `manage` | +| Segment | Meaning | Examples | +|----------|--------------------------------------------------------------------------------------------|-------------------------------------| +| `owner` | The component that defines and checks the key: `core`, or the connector's short name | `core`, `amie`, `temp-account` | +| `scope` | The resource inside that owner | `clusters`, `packets`, `agreements` | +| `action` | The verb: `read` for reads, `write` for mutations, `grant` or `manage` for meta operations | `read`, `write`, `grant`, `manage` | ## Core (`pkg/models/privilege.go`) -| Privilege | Routes it gates | -|---|---| -| `core:clusters:read` | `GET /compute-clusters`<br>`GET /compute-clusters/{id}`<br>`GET /compute-clusters/{id}/users`<br>`GET /compute-clusters/{id}/users/{userId}`<br>`GET /compute-cluster-users`<br>`GET /compute-cluster-users/{id}`<br>`GET /users/{id}/compute-cluster-users`<br>`GET /connectors`<br>`GET /connectors/vast/folders` | -| `core:clusters:write` | `POST /compute-clusters`<br>`POST /compute-cluster-users`<br>`POST /compute-cluster-users/{id}/approve`<br>`POST /compute-cluster-users/{id}/deny`<br>`PUT /compute-cluster-users/{id}`<br>`DELETE /compute-cluster-users/{id}`<br>`DELETE /connectors/vast/folders/{id}`<br>`PUT /connectors/vast/folders/{id}/quota` | -| `core:allocations:read` | Each `GET` across the allocation family: `/compute-allocation-resources*`<br>`/compute-allocation-resource-rates*`<br>`/compute-allocation-diffs*`<br>`/compute-allocation-change-requests*`<br>`/compute-allocation-change-request-events*`<br>`/compute-allocation-memberships*`<br>`/compute-allocation-membership-resource-overrides*`<br>`/compute-allocation-usages*`<br>the sub-resources of `/compute-allocations/{id}` not listed under [routes without a privilege](#r [...] -| `core:allocations:write` | Each `POST`, `PUT` and `DELETE` across the same allocation family, including `POST /compute-allocations` and `DELETE /compute-allocations/{id}` | -| `core:projects:read` | `GET /projects/{id}/members` | -| `core:projects:write` | `POST /projects`, `PUT /projects/{id}`, `PUT /projects/{id}/status`, `DELETE /projects/{id}`, `PUT /projects/{id}/members/{userId}` | -| `core:users:read` | `GET /users`<br>`GET /users/{id}`<br>`GET /user-identities/{id}`<br>`GET /user-identities/sources/{source}/external/{externalId}`<br>`GET /user-identities/oidc-subjects/{oidcSub}`<br>`GET /users/{id}/user-identities` | -| `core:users:write` | `POST /users`<br>`PUT /users/{id}`<br>`PUT /users/{id}/status`<br>`POST /users/merge`<br>`POST /user-identities`<br>`PUT /user-identities/{id}`<br>`DELETE /user-identities/{id}` | -| `core:organizations:read` | `GET /organizations`<br>`GET /organizations/{id}` | -| `core:organizations:write` | `POST /organizations` | -| `core:traces:read` | `GET /audit/traces`<br>`GET /audit/traces/{trace_id}`<br>`GET /audit/events`<br>`GET /audit/sources`<br>`GET /events/deliveries`<br>`GET /events/deliveries/{id}`<br>`GET /events/subscriptions` | -| `core:events:manage` | `POST /events/deliveries/{id}/retry`<br>`GET /events/graph` | -| `core:privileges:grant` | `GET /privileges/catalog`<br>`GET /users/{id}/privileges`<br>`GET /privileges/{key}/holders`<br>`POST /users/{id}/privileges`<br>`DELETE /users/{id}/privileges/{key}` | -| `core:roles:manage` | `GET /roles`<br>`POST /roles`<br>`GET /roles/{id}`<br>`PUT /roles/{id}`<br>`DELETE /roles/{id}`<br>`POST /roles/{id}/privileges`<br>`DELETE /roles/{id}/privileges/{key}`<br>`GET /roles/{id}/holders`<br>`GET /users/{id}/roles`<br>`POST /users/{id}/roles`<br>`DELETE /users/{id}/roles/{roleId}` | -| `core:agreements:read` | `GET /agreements`<br>`GET /agreements/{id}`<br>`GET /agreements/{id}/acceptances` | -| `core:agreements:manage` | `POST /agreements`<br>`PUT /agreements/{id}`<br>`DELETE /agreements/{id}`<br>`POST /agreements/{id}/publish`<br>`POST /agreements/{id}/remove` | +| Privilege | Routes it gates [...] +|----------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ [...] +| `core:clusters:read` | `GET /compute-clusters`<br>`GET /compute-clusters/{id}`<br>`GET /compute-clusters/{id}/users`<br>`GET /compute-clusters/{id}/users/{userId}`<br>`GET /compute-cluster-users`<br>`GET /compute-cluster-users/{id}`<br>`GET /users/{id}/compute-cluster-users`<br>`GET /connectors`<br>`GET /connectors/vast/folders` [...] +| `core:clusters:write` | `POST /compute-clusters`<br>`POST /compute-cluster-users`<br>`POST /compute-cluster-users/{id}/approve`<br>`POST /compute-cluster-users/{id}/deny`<br>`PUT /compute-cluster-users/{id}`<br>`DELETE /compute-cluster-users/{id}`<br>`DELETE /connectors/vast/folders/{id}`<br>`PUT /connectors/vast/folders/{id}/quota` [...] +| `core:allocations:read` | Each `GET` across the allocation family: `/compute-allocation-resources*`<br>`/compute-allocation-resource-rates*`<br>`/compute-allocation-diffs*`<br>`/compute-allocation-change-requests*`<br>`/compute-allocation-change-request-events*`<br>`/compute-allocation-memberships*`<br>`/compute-allocation-membership-resource-overrides*`<br>`/compute-allocation-usages*`<br>the sub-resources of `/compute-allocations/{id}` not listed under [routes without a privilege] [...] +| `core:allocations:write` | Each `POST`, `PUT` and `DELETE` across the same allocation family, including `POST /compute-allocations` and `DELETE /compute-allocations/{id}` [...] +| `core:projects:read` | `GET /projects/{id}/members` [...] +| `core:projects:write` | `POST /projects`, `PUT /projects/{id}`, `PUT /projects/{id}/status`, `DELETE /projects/{id}`, `PUT /projects/{id}/members/{userId}` [...] +| `core:users:read` | `GET /users`<br>`GET /users/{id}`<br>`GET /user-identities/{id}`<br>`GET /user-identities/sources/{source}/external/{externalId}`<br>`GET /user-identities/oidc-subjects/{oidcSub}`<br>`GET /users/{id}/user-identities` [...] +| `core:users:write` | `POST /users`<br>`PUT /users/{id}`<br>`PUT /users/{id}/status`<br>`POST /users/merge`<br>`POST /user-identities`<br>`PUT /user-identities/{id}`<br>`DELETE /user-identities/{id}` [...] +| `core:organizations:read` | `GET /organizations`<br>`GET /organizations/{id}` [...] +| `core:organizations:write` | `POST /organizations` [...] +| `core:traces:read` | `GET /audit/traces`<br>`GET /audit/traces/{trace_id}`<br>`GET /audit/events`<br>`GET /audit/sources`<br>`GET /events/deliveries`<br>`GET /events/deliveries/{id}`<br>`GET /events/subscriptions` [...] +| `core:events:manage` | `POST /events/deliveries/{id}/retry`<br>`GET /events/graph` [...] +| `core:privileges:grant` | `GET /privileges/catalog`<br>`GET /users/{id}/privileges`<br>`GET /privileges/{key}/holders`<br>`POST /users/{id}/privileges`<br>`DELETE /users/{id}/privileges/{key}` [...] +| `core:roles:manage` | `GET /roles`<br>`POST /roles`<br>`GET /roles/{id}`<br>`PUT /roles/{id}`<br>`DELETE /roles/{id}`<br>`POST /roles/{id}/privileges`<br>`DELETE /roles/{id}/privileges/{key}`<br>`GET /roles/{id}/holders`<br>`GET /users/{id}/roles`<br>`POST /users/{id}/roles`<br>`DELETE /users/{id}/roles/{roleId}` [...] +| `core:agreements:read` | `GET /agreements`<br>`GET /agreements/{id}`<br>`GET /agreements/{id}/acceptances` [...] +| `core:agreements:manage` | `POST /agreements`<br>`PUT /agreements/{id}`<br>`DELETE /agreements/{id}`<br>`POST /agreements/{id}/publish`<br>`POST /agreements/{id}/remove` [...] `POST /users` with `portal_admin` or `cluster_admin` set also requires `core:roles:manage`. @@ -69,43 +69,41 @@ A key exists only once it is registered with `models.Register(...)`. Grants and These routes need a verified caller but no key. -| Router method | Routes | Access | -|---|---|---| -| `Public` | `GET /healthz` | Anyone, no token | -| `RequireAuthWithoutUserConsent` | `GET /me`<br>`GET /user/privileges`<br>`GET /me/agreements/pending`<br>`POST /me/agreements/{id}/accept`<br>`GET /me/onboarding/username`<br>`POST /me/onboarding` | The caller's own profile and onboarding, before consent | -| `RequireAuth` | `GET /me/onboarding/status` | The caller's own status | -| `RequireAuth` | `GET /projects`<br>`GET /compute-allocations` | All records with `core:projects:read` or `core:allocations:read`; otherwise the caller's own | -| `RequireScoped` | `GET /projects/{id}` | `core:projects:read`, or a participant in the project; `404` otherwise | -| `RequireScoped` | `GET /compute-allocations/{id}`<br>`GET /compute-allocations/{id}/resources`<br>`GET /compute-allocations/{id}/memberships`<br>`GET /compute-allocations/{id}/usages`<br>`GET /compute-allocations/{id}/usages/total` | `core:allocations:read`, or a participant in the allocation; `404` otherwise | -| `RequireAuth` | `GET /connectors/analytics/contexts`<br>`GET /connectors/analytics/allocations/{id}/usage-summary`<br>`GET /connectors/analytics/allocations/{id}/jobs` | Decided by allocation role alone: PI, CO_PI and ALLOCATION_MANAGER see all members, plain members see their own records | -| `RequireAuth` | `GET /connectors/signer/me/certificates`<br>`GET /connectors/signer/me/certificates/{serial}` | The caller's own certificates, as decided by the signer | +| Router method | Routes | Access | +|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------| +| `Public` | `GET /healthz` | Anyone, no token | +| `RequireAuthWithoutUserConsent` | `GET /me`<br>`GET /user/privileges`<br>`GET /me/agreements/pending`<br>`POST /me/agreements/{id}/accept`<br>`GET /me/onboarding/username`<br>`POST /me/onboarding` | The caller's own profile and onboarding, before consent | +| `RequireAuth` | `GET /me/onboarding/status` | The caller's own status | +| `RequireAuth` | `GET /projects`<br>`GET /compute-allocations` | All records with `core:projects:read` or `core:allocations:read`; otherwise the caller's own | +| `RequireScoped` | `GET /projects/{id}` | `core:projects:read`, or a participant in the project; `404` otherwise | +| `RequireScoped` | `GET /compute-allocations/{id}`<br>`GET /compute-allocations/{id}/resources`<br>`GET /compute-allocations/{id}/memberships`<br>`GET /compute-allocations/{id}/usages`<br>`GET /compute-allocations/{id}/usages/total` | `core:allocations:read`, or a participant in the allocation; `404` otherwise | +| `RequireAuth` | `GET /connectors/analytics/contexts`<br>`GET /connectors/analytics/allocations/{id}/usage-summary`<br>`GET /connectors/analytics/allocations/{id}/jobs` | Decided by allocation role alone: PI, CO_PI and ALLOCATION_MANAGER see all members, plain members see their own records | +| `RequireAuth` | `GET /connectors/signer/me/certificates`<br>`POST /connectors/signer/me/certificates`<br>`GET /connectors/signer/me/certificates/{serial}`<br>`POST /connectors/signer/me/certificates/{serial}/revoke` | The caller's own certificates. Generating also needs a ready cluster account and an active allocation | ## AMIE connector (`connectors/ACCESS/AMIE-Processor/server/privileges.go`) -| Privilege | Routes it gates | -|---|---| -| `amie:packets:read` | `GET /connectors/amie/packets`<br>`GET /connectors/amie/packets/{id}`<br>`GET /connectors/amie/packets/{id}/events`<br>`GET /connectors/amie/packets/{packet_id}/audits`<br>`GET /connectors/amie/stats` | -| `amie:packets:write` | `POST /connectors/amie/packets/{id}/retry`<br>`POST /connectors/amie/packets/{id}/resolve` | -| `amie:replies:read` | `GET /connectors/amie/replies` | -| `amie:replies:write` | `POST /connectors/amie/replies/{id}/retry` | -| `amie:unmapped:read` | `GET /connectors/amie/unmapped` | -| `amie:unmapped:write` | `POST /connectors/amie/unmapped/{id}/link` | +| Privilege | Routes it gates | +|-----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `amie:packets:read` | `GET /connectors/amie/packets`<br>`GET /connectors/amie/packets/{id}`<br>`GET /connectors/amie/packets/{id}/events`<br>`GET /connectors/amie/packets/{packet_id}/audits`<br>`GET /connectors/amie/stats` | +| `amie:packets:write` | `POST /connectors/amie/packets/{id}/retry`<br>`POST /connectors/amie/packets/{id}/resolve` | +| `amie:replies:read` | `GET /connectors/amie/replies` | +| `amie:replies:write` | `POST /connectors/amie/replies/{id}/retry` | +| `amie:unmapped:read` | `GET /connectors/amie/unmapped` | +| `amie:unmapped:write` | `POST /connectors/amie/unmapped/{id}/link` | ## TempAccount connector (`connectors/TempAccount/internal/privileges.go`) -| Privilege | Routes it gates | -|---|---| -| `temp-account:accounts:read` | `GET /connectors/temp-account/membership/{user_id}` | +| Privilege | Routes it gates | +|-------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `temp-account:accounts:read` | `GET /connectors/temp-account/membership/{user_id}` | | `temp-account:accounts:write` | `POST /connectors/temp-account/create`<br>`POST /connectors/temp-account/assign-allocation`<br>`POST /connectors/temp-account/update-allocation`<br>`DELETE /connectors/temp-account/remove/{user_id}` | ## Signer connector (`connectors/Signer/internal/privileges.go`) -| Privilege | Routes it gates | -|---|---| -| `signer:certificates:read` | `GET /connectors/signer/certificates`<br>`GET /connectors/signer/certificates/{serial}`<br>`GET /connectors/signer/status` | -| `signer:certificates:write` | `POST /connectors/signer/certificates/{serial}/revoke` | - -The SSH-Certificate-Signer extension checks the same two keys in the privileges that core `GET /me` returns. +| Privilege | Routes it gates | +|-----------------------------|----------------------------------------------------------------------------------------------------------------------------| +| `signer:certificates:read` | `GET /connectors/signer/certificates`<br>`GET /connectors/signer/certificates/{serial}`<br>`GET /connectors/signer/status` | +| `signer:certificates:write` | `POST /connectors/signer/certificates/{serial}/revoke` | ## Other connectors @@ -116,16 +114,16 @@ no route on a key. Two roles are created by the server and marked `is_system`. -| Role | Privileges | Created | -|---|---|---| -| `super_admin` | All keys registered at startup, core and connector alike | At startup, for the user named by `CUSTOS_BOOTSTRAP_ADMIN_EMAIL` ([CONFIG.md](../CONFIG.md#environment-variables-read-directly)) | -| `admin` | All registered keys except `core:privileges:grant` and `core:roles:manage` | The first time `POST /users` onboards a portal admin. Its keys are set only then | +| Role | Privileges | Created | +|---------------|----------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------| +| `super_admin` | All keys registered at startup, core and connector alike | At startup, for the user named by `CUSTOS_BOOTSTRAP_ADMIN_EMAIL` ([CONFIG.md](../CONFIG.md#environment-variables-read-directly)) | +| `admin` | All registered keys except `core:privileges:grant` and `core:roles:manage` | The first time `POST /users` onboards a portal admin. Its keys are set only then | Two revoke paths guard against locking every administrator out: -| Revoke | Refused when | -|---|---| -| A role assignment | No user would still hold `core:privileges:grant` or `core:roles:manage` | +| Revoke | Refused when | +|-------------------------------------------|--------------------------------------------------------------------------| +| A role assignment | No user would still hold `core:privileges:grant` or `core:roles:manage` | | A direct grant of `core:privileges:grant` | It is the last direct grant of that key, or the caller revokes their own | A direct grant of `core:roles:manage` has no such guard.
