Add api keys

Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
Sacha Al Himdani
2025-11-03 09:15:14 +01:00
parent 845652c382
commit 5212d0c18f
47 changed files with 6009 additions and 3648 deletions

View File

@@ -18,11 +18,11 @@ import (
"net/http"
"time"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/log"
authsvc "go.probo.inc/probo/pkg/auth"
"go.probo.inc/probo/pkg/authz"
"go.probo.inc/probo/pkg/filemanager"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/log"
)
type Config struct {
@@ -56,6 +56,12 @@ func NewServer(cfg Config) (*Server, error) {
router.Get("/invitations", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, ListInvitationsHandler(cfg.Authz)))
router.Post("/invitations/accept", AcceptInvitationHandler(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret))
router.Get("/api-keys", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, ListUserAPIKeysHandler(cfg.Auth, cfg.Authz)))
router.Post("/api-keys", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, CreateUserAPIKeyHandler(cfg.Auth)))
router.Get("/api-keys/{id}", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, GetUserAPIKeyHandler(cfg.Auth)))
router.Put("/api-keys", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, UpdateUserAPIKeyHandler(cfg.Auth)))
router.Delete("/api-keys", RequireAuth(cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, DeleteUserAPIKeyHandler(cfg.Auth)))
router.Get("/saml/login/{samlConfigID}", SAMLLoginHandler(cfg.SAML, cfg.Auth, cfg.Logger))
router.Post("/saml/consume", SAMLACSHandler(cfg.SAML, cfg.Auth, cfg.Authz, cfg.CookieName, cfg.CookieSecret, cfg.SessionDuration, cfg.Logger))
router.Get("/saml/metadata", SAMLMetadataHandler(cfg.SAML))

View File

@@ -0,0 +1,126 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"fmt"
"net/http"
"time"
"go.gearno.de/kit/httpserver"
authsvc "go.probo.inc/probo/pkg/auth"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
)
type (
CreateUserAPIKeyRequest struct {
Name string `json:"name"`
ExpiresAt time.Time `json:"expiresAt"`
Organizations []UserAPIKeyOrganizationMembershipRequest `json:"organizations"`
}
UserAPIKeyOrganizationMembershipRequest struct {
OrganizationID string `json:"organizationId"`
Role string `json:"role"`
}
CreateUserAPIKeyResponse struct {
UserAPIKey UserAPIKeyResponse `json:"apiKey"`
Key string `json:"key"`
}
)
func CreateUserAPIKeyHandler(authSvc *authsvc.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := UserFromContext(ctx)
var req CreateUserAPIKeyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid request body",
})
return
}
if req.ExpiresAt.IsZero() {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "expiresAt is required",
})
return
}
if req.ExpiresAt.Before(time.Now()) {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "expiration date must be in the future",
})
return
}
if len(req.Organizations) == 0 {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "at least one organization is required",
})
return
}
name := req.Name
if name == "" {
name = time.Now().Format("2006-01-02")
}
orgInputs := make([]authsvc.UserAPIKeyOrganizationRequest, len(req.Organizations))
for i, org := range req.Organizations {
orgID, err := gid.ParseGID(org.OrganizationID)
if err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid organization id",
})
return
}
orgInputs[i] = authsvc.UserAPIKeyOrganizationRequest{
OrganizationID: orgID,
Role: coredata.APIRole(org.Role),
}
}
memberships, err := authSvc.ValidateAndBuildUserAPIKeyMemberships(ctx, user.ID, orgInputs)
if err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid organizations",
})
return
}
userAPIKey, key, err := authSvc.CreateUserAPIKey(ctx, user.ID, name, req.ExpiresAt, memberships)
if err != nil {
panic(fmt.Errorf("cannot create user api key: %w", err))
}
response := CreateUserAPIKeyResponse{
UserAPIKey: UserAPIKeyResponse{
ID: userAPIKey.ID,
Name: userAPIKey.Name,
ExpiresAt: userAPIKey.ExpiresAt,
CreatedAt: userAPIKey.CreatedAt,
},
Key: key,
}
httpserver.RenderJSON(w, http.StatusCreated, response)
}
}

View File

@@ -0,0 +1,84 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"errors"
"net/http"
"go.gearno.de/kit/httpserver"
authsvc "go.probo.inc/probo/pkg/auth"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
)
type DeleteUserAPIKeyRequest struct {
ID string `json:"id"`
}
type DeleteUserAPIKeyResponse struct {
ID string `json:"id"`
}
func DeleteUserAPIKeyHandler(authSvc *authsvc.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := UserFromContext(ctx)
var req DeleteUserAPIKeyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid request body",
})
return
}
if req.ID == "" {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "user api key id is required",
})
return
}
userAPIKeyID, err := gid.ParseGID(req.ID)
if err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid user api key id",
})
return
}
if err := authSvc.DeleteUserAPIKey(ctx, userAPIKeyID, user.ID); err != nil {
var errNotFound *coredata.ErrUserAPIKeyNotFound
if errors.As(err, &errNotFound) {
httpserver.RenderJSON(w, http.StatusNotFound, map[string]string{
"error": "user api key not found",
})
return
}
httpserver.RenderJSON(w, http.StatusInternalServerError, map[string]string{
"error": "failed to delete user api key",
})
return
}
response := DeleteUserAPIKeyResponse{
ID: req.ID,
}
httpserver.RenderJSON(w, http.StatusOK, response)
}
}

View File

@@ -0,0 +1,65 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"net/http"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/httpserver"
authsvc "go.probo.inc/probo/pkg/auth"
"go.probo.inc/probo/pkg/gid"
)
type GetUserAPIKeyResponse struct {
Key string `json:"key"`
}
func GetUserAPIKeyHandler(authSvc *authsvc.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := UserFromContext(ctx)
userAPIKeyIDStr := chi.URLParam(r, "id")
if userAPIKeyIDStr == "" {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "user api key id is required",
})
return
}
userAPIKeyID, err := gid.ParseGID(userAPIKeyIDStr)
if err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid user api key id",
})
return
}
key, err := authSvc.GetUserAPIKey(ctx, userAPIKeyID, user.ID)
if err != nil {
httpserver.RenderJSON(w, http.StatusNotFound, map[string]string{
"error": "user api key not found",
})
return
}
response := GetUserAPIKeyResponse{
Key: key,
}
httpserver.RenderJSON(w, http.StatusOK, response)
}
}

View File

@@ -0,0 +1,93 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"fmt"
"net/http"
"time"
"go.gearno.de/kit/httpserver"
authsvc "go.probo.inc/probo/pkg/auth"
"go.probo.inc/probo/pkg/authz"
"go.probo.inc/probo/pkg/gid"
)
type (
ListUserAPIKeysResponse struct {
UserAPIKeys []UserAPIKeyResponse `json:"apiKeys"`
}
UserAPIKeyResponse struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
ExpiresAt time.Time `json:"expiresAt"`
CreatedAt time.Time `json:"createdAt"`
Organizations []UserAPIKeyOrganizationMembership `json:"organizations"`
}
UserAPIKeyOrganizationMembership struct {
OrganizationID gid.GID `json:"organizationId"`
OrganizationName string `json:"organizationName"`
Role string `json:"role"`
}
)
func ListUserAPIKeysHandler(authSvc *authsvc.Service, authzSvc *authz.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := UserFromContext(ctx)
organizations, err := authzSvc.GetAllUserOrganizations(ctx, user.ID)
if err != nil {
panic(fmt.Errorf("cannot list organizations for user: %w", err))
}
tenantIDs := make([]gid.TenantID, 0, len(organizations))
for _, org := range organizations {
tenantIDs = append(tenantIDs, org.ID.TenantID())
}
userAPIKeysWithMemberships, err := authSvc.ListUserAPIKeysWithMemberships(ctx, user.ID, tenantIDs)
if err != nil {
panic(fmt.Errorf("cannot list user api keys: %w", err))
}
response := ListUserAPIKeysResponse{
UserAPIKeys: make([]UserAPIKeyResponse, 0, len(userAPIKeysWithMemberships)),
}
for _, keyWithMemberships := range userAPIKeysWithMemberships {
organizations := make([]UserAPIKeyOrganizationMembership, 0, len(keyWithMemberships.Memberships))
for _, membership := range keyWithMemberships.Memberships {
organizations = append(organizations, UserAPIKeyOrganizationMembership{
OrganizationID: membership.OrganizationID,
OrganizationName: membership.OrganizationName,
Role: membership.Role.String(),
})
}
response.UserAPIKeys = append(response.UserAPIKeys, UserAPIKeyResponse{
ID: keyWithMemberships.UserAPIKey.ID,
Name: keyWithMemberships.UserAPIKey.Name,
ExpiresAt: keyWithMemberships.UserAPIKey.ExpiresAt,
CreatedAt: keyWithMemberships.UserAPIKey.CreatedAt,
Organizations: organizations,
})
}
httpserver.RenderJSON(w, http.StatusOK, response)
}
}

View File

@@ -0,0 +1,142 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"errors"
"net/http"
"strings"
"go.gearno.de/kit/httpserver"
authsvc "go.probo.inc/probo/pkg/auth"
"go.probo.inc/probo/pkg/coredata"
"go.probo.inc/probo/pkg/gid"
)
type UpdateUserAPIKeyRequest struct {
ID string `json:"id"`
Name *string `json:"name,omitempty"`
Organizations []UserAPIKeyOrganizationMembershipRequest `json:"organizations"`
}
func UpdateUserAPIKeyHandler(authSvc *authsvc.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := UserFromContext(ctx)
var req UpdateUserAPIKeyRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid request body",
})
return
}
if req.ID == "" {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "user api key id is required",
})
return
}
userAPIKeyID, err := gid.ParseGID(req.ID)
if err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid user api key id",
})
return
}
if req.Name == nil && len(req.Organizations) == 0 {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "at least one field must be provided for update",
})
return
}
if req.Name != nil && *req.Name != "" {
if err := authSvc.UpdateUserAPIKeyName(ctx, userAPIKeyID, user.ID, *req.Name); err != nil {
var errNotFound *coredata.ErrUserAPIKeyNotFound
if errors.As(err, &errNotFound) {
httpserver.RenderJSON(w, http.StatusNotFound, map[string]string{
"error": "user api key not found",
})
return
}
if strings.Contains(err.Error(), "does not belong to user") {
httpserver.RenderJSON(w, http.StatusForbidden, map[string]string{
"error": "access denied",
})
return
}
httpserver.RenderJSON(w, http.StatusInternalServerError, map[string]string{
"error": "failed to update user api key name",
})
return
}
}
if len(req.Organizations) > 0 {
orgInputs := make([]authsvc.UserAPIKeyOrganizationRequest, len(req.Organizations))
for i, org := range req.Organizations {
orgID, err := gid.ParseGID(org.OrganizationID)
if err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid organization id",
})
return
}
orgInputs[i] = authsvc.UserAPIKeyOrganizationRequest{
OrganizationID: orgID,
Role: coredata.APIRole(org.Role),
}
}
memberships, err := authSvc.ValidateAndBuildUserAPIKeyMemberships(ctx, user.ID, orgInputs)
if err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, map[string]string{
"error": "invalid organizations",
})
return
}
if err := authSvc.UpdateUserAPIKeyMemberships(ctx, userAPIKeyID, user.ID, memberships); err != nil {
var errNotFound *coredata.ErrUserAPIKeyNotFound
if errors.As(err, &errNotFound) {
httpserver.RenderJSON(w, http.StatusNotFound, map[string]string{
"error": "user api key not found",
})
return
}
if strings.Contains(err.Error(), "does not belong to user") {
httpserver.RenderJSON(w, http.StatusForbidden, map[string]string{
"error": "access denied",
})
return
}
httpserver.RenderJSON(w, http.StatusInternalServerError, map[string]string{
"error": "failed to update user api key",
})
return
}
}
httpserver.RenderJSON(w, http.StatusOK, map[string]string{
"message": "User API key updated successfully",
})
}
}