protected.gno
2.42 Kb · 66 lines
1// The `protected.gno` file contains public realm functions that must only be called
2// from realms that live within the Boards2 package namespace. This allows sub realms
3// to access boards data to be able to migrate content from one version to another or
4// to implement specific features in separate sub realms.
5
6package boards2
7
8import (
9 "strings"
10
11 "gno.land/p/gnoland/boards"
12)
13
14// TODO: Authorize sub realms to be able to call protected functions (use DAOs)
15
16// boardsNS is the package-path namespace shared by all Boards2 versions.
17// Update as part of each version bump.
18const boardsNS = "gno.land/r/gnoland/boards2/"
19
20// GetRealmPermissions returns Boards2 realm permissions.
21// This is a protected function only callable by Boards2 sub realms.
22func GetRealmPermissions(cur realm) boards.Permissions {
23 assertCallerHasBoardsNS(0, cur)
24 return gPerms
25}
26
27// GetBoard returns a board.
28// This is a protected function only callable by Boards2 sub realms.
29func GetBoard(cur realm, boardID boards.ID) (_ *boards.Board, found bool) {
30 assertCallerHasBoardsNS(0, cur)
31 return gBoards.Get(boardID)
32}
33
34// MustGetBoard returns a board or panics on error.
35// This is a protected function only callable by Boards2 sub realms.
36func MustGetBoard(cur realm, boardID boards.ID) *boards.Board {
37 assertCallerHasBoardsNS(0, cur)
38 return mustGetBoard(boardID)
39}
40
41// Iterate iterates boards.
42// Iteration is done for all boards, including the ones that are not listed.
43// To reverse iterate boards use a negative count.
44// If the callback returns true, iteration is stopped.
45func Iterate(cur realm, start, count int, fn boards.BoardIterFn) bool {
46 assertCallerHasBoardsNS(0, cur)
47 return gBoards.Iterate(start, count, fn)
48}
49
50// assertCallerHasBoardsNS panics unless the caller realm's PkgPath
51// lives within the Boards2 namespace. Callers pass their own live cur;
52// the helper enforces rlm.IsCurrent() and derives the caller as
53// rlm.Previous() internally. This mirrors the Transfer/AddMember
54// pattern (see docs/resources/gno-security.md): receive the live cur,
55// extract Previous() inside, never trust a stale-or-stashed realm
56// value's PkgPath().
57//
58// _ int discriminator keeps this helper non-crossing.
59func assertCallerHasBoardsNS(_ int, rlm realm) {
60 if !rlm.IsCurrent() {
61 panic("unauthorized: rlm is not the caller's live cur")
62 }
63 if !strings.HasPrefix(rlm.Previous().PkgPath(), boardsNS) {
64 panic("forbidden, caller should live within \"" + boardsNS + "\" namespace")
65 }
66}