space

package
v1.24.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MemberRoleCommon is an ordinary Space member.
	MemberRoleCommon = 0
	// MemberRoleAdmin is a Space administrator.
	MemberRoleAdmin = 1
	// MemberRoleOwner is the Space owner.
	MemberRoleOwner = 2
)

Space member roles. Mirrors modules/space's MemberRole* constants, spelled out here rather than imported: modules/space imports this package, so referencing its constants would be an import cycle. Same reason CheckMembershipForCleanup spells out its status literal.

View Source
const SpaceChannelPrefix = "s"

Variables

View Source
var ErrMembershipCacheNegativeFallback = errors.New("membership cache: negative fallback written")

ErrMembershipCacheNegativeFallback 标记「DEL 失败,但否定缓存已写入」这一种失败。

InvalidateMembershipCache 的两种非空返回,运维含义正好相反:

  • 命中这个哨兵:正向条目没删掉,但已被一条 TTL 更短的 "0" 盖住,SpaceMiddleware 当场就拒绝这个人——**边界守住了**,只是留下一条到期才消失的脏数据。
  • 不命中(DEL 与兜底写入都失败):正向条目原样活满它的 60s TTL,被移除的人在这 段时间里仍然进得来——**这才是真的隔离失效**。

分不开的后果不是少记一点信息,而是记反:兜底成功是两者中更常见的一种,把它按 「可能仍可访问」报出去,等于在边界明明守住的时候报一次越权,值班的人照着排查会 一无所获,几次之后这条日志就不再被当真。

View Source
var SystemBots = map[string]bool{
	"botfather":    true,
	"u_10000":      true,
	"fileHelper":   true,
	"notification": true,
}

SystemBots 是所有 Space 都可见的系统级 Bot UID。

关键场景 (YUJ-216 / GH#1280):

  • 会话同步(POST /v1/conversation/sync)带 X-Space-ID 时,按 Space 过滤 普通会话。系统 Bot(botfather 等)与 Space 无关,必须始终对客户端可见, 哪怕用户在当前 Space 下尚未与 Bot 产生任何消息(首次进入 Space、 本地缓存丢失等)。Web 端在前端做兜底,移动端没有,所以后端 需要在 sync 响应中保底注入 SystemBot entry。
  • 目前系统 Bot 固定为 {botfather, u_10000, fileHelper}。未来加入 BUILDER/ADMIN bot 时,只需在此 map 中追加,或改为从配置加载。 对外接口通过 SystemBotList() 暴露,便于统一遍历。

Functions

func ActiveMembers added in v1.19.0

func ActiveMembers(session dbr.SessionRunner, spaceID string, uids []string) (map[string]bool, error)

ActiveMembers is CheckMembership for a batch: it returns the subset of uids that are active members of the given active Space.

The predicate is byte-for-byte CheckMembership's (space_member.status = 1 AND space.status = 1), and it must stay that way — this exists to stop a caller with many uids from either issuing N round-trips or, worse, hand-rolling a near-copy of the predicate that then drifts from this one.

Callers get a set rather than a bool so they can name exactly which uids failed. Absent from the map means "not an active member of that Space"; the map is never nil on success.

The parameter is dbr.SessionRunner, satisfied by both *dbr.Session and *dbr.Tx, and which one a caller passes changes what the answer MEANS:

  • a *dbr.Session runs outside any caller transaction and proves nothing about state at COMMIT time. That is the long-standing shape of the Space half of every group admission check, and changing it is a behaviour change on every group join in the product — see modules/group/admission.go for why the project half does NOT copy it.
  • a *dbr.Tx joins the caller's snapshot. pkg/project.ProjectMemberships passes one deliberately: its four reads have to describe ONE instant, because an answer torn across a Space ban carries a denial beside a live epoch and the peer's cache has no bound on that combination.

So do not "simplify" a *dbr.Tx caller back to the session. It is not a stylistic choice there; it is the fix.

func ActiveMembersTx added in v1.19.0

func ActiveMembersTx(tx *dbr.Tx, spaceID string, uids []string) (map[string]bool, error)

ActiveMembersTx is the transaction-scoped form of ActiveMembers. It keeps the exact Space predicate while allowing a caller-owned transaction to use one repeatable-read snapshot with its other authorization checks.

Subsumed by ActiveMembers since that one took dbr.SessionRunner: a *dbr.Tx satisfies it, so ActiveMembers(tx, ...) is this function. Kept because it is main's exported name and this is a merge, not a rename — but do not reach for it in new code, and do not let the two predicates drift apart.

func ActiveSpacesForMember added in v1.21.0

func ActiveSpacesForMember(session dbr.SessionRunner, uid string) (map[string]bool, error)

ActiveSpacesForMember returns every active Space in which uid is an active member. Its predicates intentionally match CheckMembership so callers can authorize a multi-Space response with one query instead of checking each output key separately.

func BuildChannelID

func BuildChannelID(spaceID, peerID string) string

BuildChannelID 构建 Space 内的 channel_id 个人空间返回原始 peerID

func CheckBothMembers

func CheckBothMembers(session *dbr.Session, spaceID string, uid1, uid2 string) (bool, error)

CheckBothMembers checks if both uid1 and uid2 are active members of the given Space. The Space itself must also be active (space.status=1); a disabled Space returns false even if both users still have space_member rows, matching CheckMembership's semantics.

func CheckBotsInSpace

func CheckBotsInSpace(session *dbr.Session, spaceID string, botUIDs map[string]bool) (map[string]bool, error)

CheckBotsInSpace 查询给定 Bot UID 中哪些是指定 Space 的成员。 返回在 Space 中的 Bot UID 集合。DB 查询失败时返回 error。

func CheckMembership

func CheckMembership(session *dbr.Session, spaceID string, uid string) (bool, error)

CheckMembership checks if uid is an active member of the given Space. Also verifies the Space itself is active (space.status=1).

func CheckMembershipForCleanup added in v1.16.0

func CheckMembershipForCleanup(session *dbr.Session, spaceID string, uid string) (bool, error)

CheckMembershipForCleanup answers a different question from CheckMembership: "does uid still hold their seat in this Space, so removal cleanup must SKIP?"

It differs on exactly one axis — a **banned** Space (status=2) still counts. Membership there is real: Manager.addMembers rejects only SpaceStatusDisbanded (modules/space/api_manager.go:638), so adding people to a banned Space is allowed, and the cleanup pipeline must not tear an active member out of every group merely because their Space was banned. A **disbanded** Space (status=0) does not count: the Space is gone, so a surviving space_member row is a join-vs-disband orphan and cleanup must proceed.

Both removal-cleanup gates MUST use this rather than CheckMembership, so the two layers answer the same question:

  • the worker gate (modules/space/member_removal.go)
  • the group cascade step (modules/group/space_member_removal.go)

**Do NOT use this for authorization.** Access control is CheckMembership's job and requires space.status=1 — a banned Space must never pass an auth gate. CheckMembership has 37 non-test call sites including SpaceMiddleware; relaxing it instead of adding this second predicate would admit banned Spaces across the whole authenticated API (Mininglamp-OSS/octo-server#797).

The status literal is spelled out rather than referencing modules/space's SpaceStatusDisbanded: modules/space imports this package, so the constant is unreachable here without an import cycle.

func DMSpacePresenceAnySet added in v1.8.0

func DMSpacePresenceAnySet(session *dbr.Session, fakeChannelIDs []string) (map[string]bool, error)

DMSpacePresenceAnySet returns the subset of fakeChannelIDs that have at least one dm_space_presence row in ANY Space, as a set keyed by fake_channel_id. Combined with DMSpacePresenceSet(ids, spaceID) a caller can derive "tracked, but belongs exclusively to other Spaces" — the positive, durable evidence required before hiding a DM from the default-Space catch-all (issue #484 follow-up). Empty input returns an empty set without querying.

func DMSpacePresenceSet added in v1.8.0

func DMSpacePresenceSet(session *dbr.Session, fakeChannelIDs []string, spaceID string) (map[string]bool, error)

DMSpacePresenceSet returns the subset of fakeChannelIDs that have at least one message tagged with spaceID, as a set keyed by fake_channel_id. Empty input (or empty spaceID) returns an empty set without querying.

func GetBotUIDs

func GetBotUIDs(session *dbr.Session, uids []string) (map[string]bool, error)

GetBotUIDs 从给定 UID 列表中查询哪些是 Bot(robot=1),排除系统 Bot。 返回 Bot UID 集合。DB 查询失败时返回 error。

func GetGroupSpaceMap

func GetGroupSpaceMap(groupNos []string, getGroups func([]string) ([]GroupSpaceInfo, error)) (map[string]string, error)

GetGroupSpaceMap 批量查询群的 space_id,返回 groupNo -> spaceID 映射。 需要传入一个能执行 GetGroups 的回调。

func GetSpaceID

func GetSpaceID(c *wkhttp.Context) string

GetSpaceID 从 gin context 读取 space_id。

func GetSpaceName

func GetSpaceName(session *dbr.Session, spaceID string) (string, error)

GetSpaceName returns the name of an active Space by ID. Returns an empty string (without error) when the Space does not exist, has status=0, or spaceID is empty — callers can treat "no space info" uniformly.

Used by H5 invite / join landing pages (YUJ-168 / GH #1243) to show "来自 {space_name}" below the group name so that external-group invitees have a trust anchor before they tap "加入群聊".

func HaveCommonSpace

func HaveCommonSpace(session *dbr.Session, uid1, uid2 string) (bool, error)

HaveCommonSpace reports whether uid1 and uid2 share at least one active Space membership. It is used to prevent cross-Space existence probing in user search.

func InvalidateMembershipCache

func InvalidateMembershipCache(redisConn *redis.Conn, spaceID, uid string) error

InvalidateMembershipCache 删除指定用户在指定 Space 的成员缓存。

返回 error 而不是吞掉:这条缓存是隔离边界的一部分,删除失败必须让调用方有机会 记日志。原先的 `_ = redisConn.Del(...)` 让失败完全无声。

func IsActiveSpace added in v1.19.0

func IsActiveSpace(session dbr.SessionRunner, spaceID string) (bool, error)

IsActiveSpace reports whether the Space itself is active, with no reference to any user.

The `status = 1` here is byte-for-byte CheckMembership's Space half, and must stay that way: a caller that answered "is this Space usable" differently from the gate every authenticated route runs would be authorizing against a different definition of the same word. A banned Space (status 2) and a disbanded one (status 0) both answer false — see CheckMembershipForCleanup for the ONE place where banned must count, and why it is a separate predicate rather than a relaxation of this one.

It exists for callers that hold no uid: a peer-facing predicate answering about a project or a container, where the parent Space's state is part of the answer but there is nobody whose membership to check.

func IsSpaceActive added in v1.18.0

func IsSpaceActive(session *dbr.Session, spaceID string) (bool, error)

IsSpaceActive reports whether a Space exists and is in the normal (status=1) state. An empty spaceID is not active. A missing row is (false, nil); only a real query failure returns an error, so callers can fail closed on it.

Distinct from GetSpaceName, which answers the same question by proxy through a non-empty name. That proxy is fine for a display string but wrong for an existence gate: `space`.`name` carries no NOT-NULL-and-non-empty guarantee at the storage layer, so a Space whose name is blank would read as absent and an admin could never point a setting at it. This asks the question directly.

Both `modules/common` (admin write-path validation) and any consumer that must refuse to write into a disbanded Space need this, and neither can import `modules/space` — it imports `modules/common`, so the dependency only runs one way. This leaf package is the shared floor.

func IsSystemBot

func IsSystemBot(uid string) bool

IsSystemBot 判断 UID 是否为系统 Bot。语义等价于 SystemBots[uid], 提供函数版本是为将来切换到配置/DB 后不破坏调用方签名。

func MemberRole added in v1.18.0

func MemberRole(session *dbr.Session, spaceID string, uid string) (int, bool, error)

MemberRole returns uid's role in spaceID. ok=false means uid is NOT an active member of an active Space, and callers MUST treat that as "no role at all" rather than falling back to MemberRoleCommon — the zero value of an int is a valid role, so a caller that ignores ok silently grants ordinary-member rights to a non-member.

The predicate is CheckMembership's (space_member.status=1 AND space.status=1), deliberately NOT CheckMembershipForCleanup's relaxed variant: this answers an authorization question, and a banned Space must never pass an auth gate (Mininglamp-OSS/octo-server#797).

func ParseChannelID

func ParseChannelID(channelID string) (spaceID, peerID string)

ParseChannelID 从 channel_id 解析 space_id 和 peer_id 优先用已知 spaceId 列表做快速匹配,回退用正则 s[0-9a-f]{32}_ 精确匹配

func RegisterSpaceIDs

func RegisterSpaceIDs(ids []string)

RegisterSpaceIDs 注册已知的 spaceId 列表(启动时从 DB 加载)

func ResolveActiveMemberSpaceName added in v1.17.0

func ResolveActiveMemberSpaceName(session *dbr.Session, spaceID string, uid string) (string, bool, error)

ResolveActiveMemberSpaceName verifies uid is an active member of the given active Space (space.status=1 AND space_member.status=1) and, when so, returns that Space's name. ok=false means uid is NOT an active member of that Space (or the Space is inactive) — callers MUST treat that as "no authoritative operator Space" and never fall back to a default/card/document Space. A DB error is returned as-is with ok=false. name may be empty for a valid Space with no name set; ok=true still distinguishes that from a non-member.

func ResolveSpaceID added in v1.19.0

func ResolveSpaceID(session dbr.SessionRunner, spaceID string) (string, bool, error)

ResolveSpaceID returns the value stored in the Space table for a selector accepted by that table's collation. The bool distinguishes "no such Space" from a database failure; callers handling recovery must not manufacture a canonical value when it is false. A caller-owned transaction keeps resolution in its authorization snapshot.

func SetSpaceID added in v1.14.0

func SetSpaceID(c *wkhttp.Context, spaceID string)

SetSpaceID marks spaceID as the request's verified Space, so handlers reading GetSpaceID apply their Space isolation. The caller owns the verification: SpaceMiddleware checks membership itself, and a non-session authentication tree publishes the tenant its credential was issued against.

func SpaceMiddleware

func SpaceMiddleware(ctx *config.Context) wkhttp.HandlerFunc

SpaceMiddleware 是 opt-in 中间件,route group 级别注入。 从请求提取 space_id(query param 优先,header X-Space-ID 其次), 无 space_id 则跳过,有则校验用户是否属于该 Space。

func SystemBotList

func SystemBotList() []string

SystemBotList 以稳定顺序返回所有系统 Bot UID。

稳定顺序有两个价值:

  1. sync 响应里保底注入 SystemBot entry 时,保证跨请求顺序一致, 方便客户端/测试做幂等比对。
  2. 未来系统 Bot 列表改为配置驱动时,调用方无需感知底层容器类型。

func UpsertDMSpacePresence added in v1.8.0

func UpsertDMSpacePresence(session *dbr.Session, fakeChannelID, spaceID string, ts int64) error

UpsertDMSpacePresence records that fakeChannelID has a message in spaceID. Idempotent; last_timestamp only moves forward. Best-effort by contract — callers (webhook ingest) log and continue on error and must NOT let a failure here roll back message persistence.

Types

type GroupSpaceInfo

type GroupSpaceInfo struct {
	GroupNo string
	SpaceID string
}

GroupSpaceInfo 用于 GetGroupSpaceMap 回调的最小接口。

type InMemoryMembershipCache

type InMemoryMembershipCache struct {
	// contains filtered or unexported fields
}

InMemoryMembershipCache 基于内存的 MembershipCache 实现,用于测试。

func NewInMemoryMembershipCache

func NewInMemoryMembershipCache() *InMemoryMembershipCache

func (*InMemoryMembershipCache) Clear

func (c *InMemoryMembershipCache) Clear()

Clear 清除所有缓存条目(测试用)。

func (*InMemoryMembershipCache) Get

func (c *InMemoryMembershipCache) Get(spaceID, uid string) (bool, bool)

func (*InMemoryMembershipCache) Set

func (c *InMemoryMembershipCache) Set(spaceID, uid string, isMember bool, ttl time.Duration)

type MembershipCache

type MembershipCache interface {
	// Get 返回缓存的成员身份。found=false 表示缓存未命中。
	Get(spaceID, uid string) (isMember bool, found bool)
	// Set 写入缓存,ttl 为过期时间。
	Set(spaceID, uid string, isMember bool, ttl time.Duration)
}

MembershipCache 缓存成员身份校验结果的接口。

type MembershipChecker

type MembershipChecker func(spaceID string, uid string) (bool, error)

MembershipChecker 校验用户是否属于 Space 的函数签名。

type RedisMembershipCache

type RedisMembershipCache struct {
	// contains filtered or unexported fields
}

RedisMembershipCache 基于 Redis 的 MembershipCache 实现。

func NewRedisMembershipCache

func NewRedisMembershipCache(redisConn *redis.Conn) *RedisMembershipCache

NewRedisMembershipCache 创建基于 Redis 的缓存。

func (*RedisMembershipCache) Get

func (c *RedisMembershipCache) Get(spaceID, uid string) (bool, bool)

func (*RedisMembershipCache) Set

func (c *RedisMembershipCache) Set(spaceID, uid string, isMember bool, ttl time.Duration)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址