Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

6.5 KB
Raw Blame
// Copyright (c) 2026 Jonas Kaninda.
//
// This file is part of Posta.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package middlewares

import (
	"strconv"

	"github.com/goposta/posta/internal/models"
	"github.com/goposta/posta/internal/storage/repositories"
	"github.com/jkaninda/okapi"
)

// WorkspaceHeader names the header carrying the active workspace. Browser-direct
// requests (EventSource, download links) cannot set headers, so the
// query-tolerant middleware also accepts `?workspace_id=`.
const WorkspaceHeader = "X-Posta-Workspace-Id"

// resolveWorkspace establishes the request's workspace and the caller's role in
// it, given the raw workspace id the caller asked for ("" when unspecified).
//
// Three callers, three sources of authority:
//
//   - A workspace-bound API key IS the workspace. It gets owner-equivalent
//     access to it and cannot reach any other workspace, whatever it asks for.
//   - An account-wide API key, and any JWT session, must prove membership of the
//     workspace they name, and inherit that membership's role.
//   - When nobody names a workspace and `required` is false, we fall back to the
//     user's default workspace, with the role from that membership.
//
// Membership answers "which workspace?", never "how much of it?". An API key's
// scopes answer the latter, and are enforced here for every workspace-scoped
// route — see requireWorkspaceScope.
// DefaultWorkspaceResolver answers where a request that names no workspace
// lands, and with what role. Narrow on purpose: the role it returns is the only
// thing standing between a viewer and write access on a header-less request, so
// it is worth being able to substitute in a test.
type DefaultWorkspaceResolver interface {
	DefaultWorkspace(userID uint) (*models.Workspace, models.WorkspaceRole, error)
}

func resolveWorkspace(c *okapi.Context, workspaceRepo *repositories.WorkspaceRepository, userRepo DefaultWorkspaceResolver, raw string, required bool) error {
	userID := c.GetInt(CtxUserID)
	if userID == 0 {
		return c.AbortUnauthorized("authentication required")
	}

	// Checked before the workspace is resolved, so an under-scoped key is refused
	// without learning whether the workspace it named exists.
	if err := requireWorkspaceScope(c); err != nil {
		return err
	}

	if bound := APIKeyWorkspaceID(c); bound != nil {
		if raw != "" {
			wsID, err := strconv.Atoi(raw)
			if err != nil || wsID <= 0 {
				return c.AbortBadRequest("invalid workspace id")
			}
			if uint(wsID) != *bound {
				return c.AbortForbidden("API key is not bound to this workspace")
			}
		}
		c.Set(CtxWorkspaceID, int(*bound))
		c.Set(CtxWorkspaceRole, string(models.WorkspaceRoleOwner))
		return c.Next()
	}

	if raw != "" {
		wsID, err := strconv.Atoi(raw)
		if err != nil || wsID <= 0 {
			return c.AbortBadRequest("invalid workspace id")
		}
		member, err := workspaceRepo.FindMember(uint(wsID), uint(userID))
		if err != nil {
			return c.AbortForbidden("you are not a member of this workspace")
		}
		c.Set(CtxWorkspaceID, wsID)
		c.Set(CtxWorkspaceRole, string(member.Role))
		return c.Next()
	}

	if required {
		return c.AbortBadRequest(WorkspaceHeader + " header is required")
	}

	// Nobody named a workspace: fall back to the caller's default one.
	//
	// The role comes from the membership row, never a constant. The default
	// workspace used to be the caller's personal one, which they always owned, so
	// hard-coding owner was safe. It is now any workspace they belong to —
	// possibly as a viewer — and assuming owner here would grant write access on
	// every header-less request.
	if userRepo != nil {
		if ws, role, err := userRepo.DefaultWorkspace(uint(userID)); err == nil && ws != nil {
			c.Set(CtxWorkspaceID, int(ws.ID))
			c.Set(CtxWorkspaceRole, string(role))
		}
	}
	return c.Next()
}

// RequireWorkspaceMiddleware demands an explicit workspace, except for a
// workspace-bound API key, whose binding names it.
func RequireWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo DefaultWorkspaceResolver) okapi.Middleware {
	return func(c *okapi.Context) error {
		return resolveWorkspace(c, workspaceRepo, userRepo, c.Header(WorkspaceHeader), true)
	}
}

// OptionalWorkspaceMiddleware resolves the workspace when named, and otherwise
// falls back to the caller's personal workspace.
func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo DefaultWorkspaceResolver) okapi.Middleware {
	return func(c *okapi.Context) error {
		return resolveWorkspace(c, workspaceRepo, userRepo, c.Header(WorkspaceHeader), false)
	}
}

// WorkspaceFromQueryOrHeader is OptionalWorkspaceMiddleware for browser-direct
// requests, which can pass the workspace only as a query parameter.
func WorkspaceFromQueryOrHeader(workspaceRepo *repositories.WorkspaceRepository, userRepo DefaultWorkspaceResolver) okapi.Middleware {
	return func(c *okapi.Context) error {
		raw := c.Header(WorkspaceHeader)
		if raw == "" {
			raw = c.Query("workspace_id")
		}
		return resolveWorkspace(c, workspaceRepo, userRepo, raw, false)
	}
}

// RequireWorkspaceRole enforces a minimum workspace role. A workspace-bound API
// key resolves as owner, so it clears every tier.
func RequireWorkspaceRole(minRole models.WorkspaceRole) okapi.Middleware {
	return func(c *okapi.Context) error {
		roleStr := c.GetString(CtxWorkspaceRole)
		if roleStr == "" {
			return c.AbortForbidden("workspace context required")
		}

		role := models.WorkspaceRole(roleStr)
		allowed := false

		switch minRole {
		case models.WorkspaceRoleViewer:
			allowed = role.CanView()
		case models.WorkspaceRoleEditor:
			allowed = role.CanEdit()
		case models.WorkspaceRoleAdmin:
			allowed = role.CanManageMembers()
		case models.WorkspaceRoleOwner:
			allowed = role.IsOwner()
		}

		if !allowed {
			return c.AbortForbidden("insufficient workspace permissions")
		}

		return c.Next()
	}
}