JFLib

plat/policy.rs#

Source: lib/plat/policy.rs

policy -- the app's permissions (apps/NAME/PERMISSIONS, docs/PERMISSIONS.md): parsed once at
start-up, then checked by the public file, process, shell, plugin and print functions

  install(text) -> Result<Key, String>   parse and activate a manifest (once per process);
                                         before that, and in apps without one, all is allowed
  active() -> bool
  fs_allowed(path, FS_READ | FS_WRITE) / process_allowed(program) / url_allowed(url) /
  plugin_allowed(path) / print_allowed() / secrets_allowed(service) / autostart_allowed() /
  audio_allowed()                        -> bool
  input_global_allowed() / screen_capture_allowed() / location_allowed() / sensors_allowed() /
  gamepad_allowed()                      -> bool
                                         a refusal is recorded (denials) and printed once
                                         per target to stderr: "PERMDENY kind target"
  audio_granted() -> bool                sound is allowed now, without asking or recording a
                                         refusal (ui's dialog sounds stay silent without it)
  gamepad_granted() -> bool              game pads are allowed now, the same way (ui.gamepads
                                         starts watching once an ask line was answered yes)
  net_connect_allowed(addr) / net_listen_allowed(addr) / net_name_allowed(host) -> bool
  net_listen_granted(addr) -> bool       net.listen without asking or recording (a UDP socket on
                                         port 0: may it answer its peers)
  net_host_allowed(host, port) -> bool   (G7d) a connection to a host as written, name or
                                         address (the browser's WebSocket resolves itself)
  net_resolved(host, addrs)              (resolvers) the addresses of a permitted name:
                                         connections to them follow that name's rules
  Key::grant(path, FS_*) / Key::grant_dir(dir, FS_*)   a file / folder the user handed over
                                         (file dialog, drop, command line); needs fs.user
  Key::trusted(f)                        f runs on this thread without the file checks (the
                                         library's own file dialog and test scripts)
  denials() -> Vec<Denial>               the last DENIALS_MAX refusals (audit)
  normalize(path) -> Option<String>      absolute, '/' separators, no "." / ".." / empty
                                         segments; Windows: upper-case drive letter, no
                                         device, stream or reserved names; Linux: no ".."
                                         at all (the kernel applies it after symbolic
                                         links); None = refused
  normalize_for(path, windows, cwd)      the same rules for either OS (tests, tools)
  font_dirs() -> [folder]                the system font folders in scan order (fontdb)
  cap_mask() -> CAP_* bits               what the policy leaves of capabilities()

Questions to the user ("ask" lines; one decision per line):
  questions() -> Vec<Question>           what waits for the user's answer (the UI shows it)
  Key::ask_here(on)                      this thread (the UI's) asks: an access on it is
                                         refused while its question is open (Verdict::
                                         Pending; the UI tells the app when it was answered),
                                         other threads wait up to Key::set_wait ms (env
                                         jfgui_PERM_TIMEOUT, WAIT_MS) and are refused then.
                                         Nobody asks (headless runs, console programs): refused
  Key::answer(id, Answer)                Once / Deny: until the program ends; Always / Never:
                                         also stored (Key::set_store, env jfgui_PERM_STORE,
                                         STORE in config://; the app cannot write that file,
                                         by no other name either -- 8.3, case, link -- and
                                         STORE also not while another store is chosen)
  Key::set_answer(Some(a))               every question answered with a, without asking
                                         (scripts; env jfgui_PERM_ANSWER=once|always|deny|never)
  decisions() -> Vec<Decision>           every ask line and agent action with its answer
  forget(rule) / forget_all()            revoke: asked again on the next access
  reload()                               read the stored answers again
Plugins (their own <stem>.permissions beside the library, same syntax without ask and agent
lines, $PLUGIN = the plugin's folder; read access to that folder is implied):
  plugin_rights(lib_path) -> Result<Arc<PluginRights>, String>
  on_behalf(&rights, f)                  f on this thread for the plugin: every check must
                                         pass the plugin's rules AND the app's (nested scopes:
                                         all of them); jobs it starts on the pool keep it
  plugin_scope() -> Option<Arc<PluginRights>>   the innermost scope of this thread
Agent control (agent.confirm / agent.deny lines):
  agent_rule(action) -> AgentRule        agent_ask(action, description) -> Verdict

Manifest: one rule per line, '#' starts a comment, a key may repeat:
  fs.read PATTERN..     read files below PATTERN
  fs.write PATTERN..    write (and read) files below PATTERN
  fs.user               files the user chooses (dialog, drop, command line): read + write;
                        also every document the system hands over one at a time (Android's
                        content://, a Flatpak's documents portal mount, the browser's
                        /handles/), so they work after a restart too
  process PATTERN|NAME..   programs Command::spawn / run_elevated may start (NAME: no '/')
  url SCHEME..|*        open_url schemes (https, mailto, ...)
  plugins PATTERN..     native libraries for lib_open
  print                 plat::print
  secrets               plat::secret (the system's store for passwords, tokens and keys)
  autostart             plat::autostart_set (start the app at login; reading is free)
  audio.output          plat::audio: streams, play / play_file, the system's sounds (sound)
  input.global          plat::hotkey_register (global shortcuts: chords pressed while
                        another program has the keyboard)
  screen.capture        plat::screen::capture_start (pictures of the screen; picking one
                        pixel's colour needs nothing: the user chooses it)
  location              plat::sensors::location_watch (where the device is)
  sensors               plat::sensors::watch (accelerometer, gyroscope, magnetometer, rotation)
  gamepad               plat::pad_watch (game pads: XInput, evdev, GameController, the
                        browser's Gamepad API; a Flatpak gets --device=input for it, which
                        shows the nodes of every input device, keyboards too: tools/pkg_linux.py)
  net.connect HOST:PORT..   TCP connections and UDP datagrams to HOST (a name, *.name for
                        every name below it, an IPv4 / [IPv6] address, a block 10.0.0.0/8
                        or [fd00::]/8, localhost = the loopback addresses, * = any) on PORT
                        (a number, a range 8000-8099 or *); names are checked when they are
                        resolved, their addresses then count for the name; with any name
                        rule, port 53 (DNS) is open too
  net.listen ADDR:PORT..    TCP listeners and UDP sockets with a fixed port on ADDR (an
                        address, a block, localhost or *; 0.0.0.0 / [::] = every interface)
                        and PORT (port 0 = any free one: the rule needs 0 or *).  A UDP socket
                        whose address it covers may answer: send to an address it received a
                        datagram from in the last 60 s without a net.connect rule (net.rs
                        AnswerSet: at most 1024 addresses per socket, so forged source
                        addresses cannot grow it; inside a plugin's scope the plugin's
                        net.listen must cover the socket too).  Every other datagram needs
                        net.connect
  ask KEY ARGS.. ["reason"]   (every key but fs.user) the first access asks the user; a
                        plain rule that covers the access wins over an ask line
  agent.confirm NAME..  agent actions (glob: '*' any run) the user confirms first
  agent.deny NAME..     agent actions an agent may not run
  sandbox [strict]      ask the OS to enforce the manifest as well (Landlock + seccomp on
                        Linux, process mitigation policies on Windows; sandbox.rs); `strict`
                        refuses to start when the OS cannot enforce it
  recent                the host's list of recent files for a Flatpak (tools/pkg_linux.py:
                        --filesystem=xdg-data/recently-used.xbel, the list of every program);
                        at run time nothing changes: the system's list is always allowed
                        for files the app may read (recent.rs)
A PATTERN is an absolute path (X:/.. and //server/share/.. count on Windows only, /.. on
Linux only), or starts with $CONFIG $TEMP $HOME $EXE $FONTS, $APPIMAGE (the folder of the
running AppImage file: lib/update replaces it there; no value elsewhere), the app's own folders
$APPCONFIG $APPDATA $APPCACHE $APPLOG (vfs::app_dir) or the user's folders $DESKTOP
$DOCUMENTS $DOWNLOADS $PICTURES $MUSIC $VIDEOS (user_dir; a variable without a value
drops the pattern); '*' / '?' match inside one segment, a '**' segment any number of
segments ("dir/**" also matches dir itself); "**" alone matches every path.  Windows
compares without case.  Always readable: the font folders, the Hunspell dictionary folders
(spell::hunspell_dirs), the exe folder and on Linux /etc/resolv.conf and /etc/hosts
(netio's resolver); always writable: the app's own folders (config://, data://, cache://,
logs://; vfs::set_app_id comes first) except the file of the stored answers.  trash counts
as writing the path.

The checks are lexical: a symbolic link inside an allowed folder can point outside it.  On
Linux a path with a ".." segment is refused: "allowed/link/../x" would leave the folder.
/// read access ([`fs_allowed`], [`Key::grant`])
FS_READ: u32 = 1
/// write access; implies [`FS_READ`]
FS_WRITE: u32 = 2
/// refusals kept for [`denials`]
DENIALS_MAX: usize = 64
/// how long a thread other than the asking one waits for the user's answer by default (ms)
WAIT_MS: u32 = 60_000
/// where Always / Never answers are kept by default ([`Key::set_store`])
STORE: &str = "config://permission-decisions.txt"
  • struct Denial one refused access

    • kind: &'static str -- "fs.read", "fs.write", "process", "url", "plugins", "print", "secrets", "autostart", "audio.output", "net.connect", "net.listen", "agent", "input.global", "screen.capture", "location", "sensors" or "gamepad"
    • target: String -- the path, program, URL, address, the service of a secret, the agent's action, the chord of a shortcut or "" (print, autostart, audio.output, screen.capture, location, sensors, gamepad)
    • plugin: String -- the plugin the call was made for ("" = the app itself)
  • enum Answer the user's answer to a question

    • Once -- allowed until the program ends
    • Always -- allowed, also in later runs (stored)
    • Deny -- refused until the program ends
    • Never -- refused, also in later runs (stored)

impl Answer

  • fn allows(self) -> bool Once or Always

  • fn stored(self) -> bool Always or Never: kept for later runs

  • fn word(self) -> &'static str "once", "always", "deny", "never" (scripts, env, the store)

  • fn parse(w: &str) -> Option<Answer> the answer of word

  • enum Verdict the outcome of a check that may ask the user

    • Allow -- go ahead
    • Deny -- refused (the rules, the user's answer, nobody to ask, a timeout)
    • Pending -- refused for now: the question waits for the user on this (the asking) thread
  • struct Question a question waiting for the user's answer

    • id: u32 -- for [Key::answer]
    • kind: &'static str -- the kind of access ("fs.read", "net.connect", ..., "agent")
    • target: String -- what is accessed: the path, host, program, URL or the agent's action
    • rule: String -- the ask line the answer decides ("fs.read $DOCUMENTS/**", "agent document.delete")
    • reason: String -- the manifest's reason ("" without one); an agent action: its description
    • plugin: String -- the plugin the call is made for ("" = the app)
  • struct Decision an ask line or an agent action with its answer ([decisions])

    • rule: String -- the ask line ("url mailto") or "agent ACTION"
    • kind: &'static str -- its kind ("url", ..., "agent")
    • reason: String -- the manifest's reason or the action's description ("" when unknown)
    • answer: Option<Answer> -- None: not answered (asked on the next access)
  • enum AgentRule what the manifest says about an agent action ([agent_rule])

    • Free -- no rule: the agent may run it
    • Confirm -- agent.confirm: the user confirms it first
    • Deny -- agent.deny: never for an agent
  • struct Key(()) The right to widen the installed policy for the user's own files, to run trusted library code and to answer questions; only [install] creates one (the UI runtime keeps it to itself).

  • fn install(text: &str) -> Result<Key, String> parse and activate a manifest; Err names the first bad line. Only the first call of a process can succeed.

  • fn take_key() -> Option<Key> the key of a process without a manifest (it answers the questions of agent actions); only the first call (and none after install) gets it

  • fn active() -> bool whether a policy restricts this process

  • fn fs_allowed(path: &str, mode: u32) -> bool whether path may be read (FS_READ) or written (FS_WRITE); never a path with a NUL character (the system would end the name there and reach another file), with or without a policy

  • fn user_doc_allowed(uri: &str) -> bool whether the app may reach a document the user chose by its URI (Android's content:// names; the system grants each one): with fs.user in the manifest, or without a manifest; inside on_behalf every plugin scope needs fs.user as well

  • fn process_allowed(program: &str) -> bool whether Command::spawn / run_elevated may start program (a path, or a name found in PATH)

  • fn url_allowed(url: &str) -> bool whether open_url may open url (its scheme); false for anything but an absolute URL (a path, a drive letter), with or without a manifest

  • fn plugin_allowed(path: &str) -> bool whether lib_open may load the native library at path

  • fn print_allowed() -> bool whether plat::print may print

  • fn secrets_allowed(service: &str) -> bool whether plat::secret may use the system's secret store (secrets); a refusal names the service ("" for secret_available)

  • fn autostart_allowed() -> bool whether plat::autostart_set may change the app's autostart entry (autostart)

  • fn audio_allowed() -> bool whether plat::audio may play sound (audio.output): streams, play, play_file, the system's sounds

  • fn audio_granted() -> bool whether sound is allowed now without a question or a recorded refusal: no manifest, a plain audio.output line or an ask line already answered with yes (ui's dialog sounds)

  • fn input_global_allowed() -> bool whether plat::hotkey_register may register global shortcuts (input.global)

  • fn screen_capture_allowed() -> bool whether plat::screen::capture_start may take pictures of the screen (screen.capture)

  • fn location_allowed() -> bool whether plat::sensors::location_watch may ask where the device is (location)

  • fn sensors_allowed() -> bool whether plat::sensors::watch may read the motion sensors (sensors)

  • fn gamepad_allowed() -> bool whether plat::pad_watch may read game pads (gamepad)

  • fn gamepad_granted() -> bool whether game pads are allowed now without a question or a recorded refusal: no manifest, a plain gamepad line or an ask line already answered with yes (ui.gamepads tries pad_watch again once it is)

  • fn denials() -> Vec<Denial> the last refusals, oldest first

  • fn sandbox_level() -> u8 the OS sandbox the manifest asks for: 0 none, 1 sandbox, 2 sandbox strict (sandbox.rs)

  • struct LinuxPlan (Linux) what the Linux OS sandbox grants, derived from the active policy ([sandbox_plan_linux])

    • level: u8 -- 0 none, 1 sandbox, 2 sandbox strict
    • fs: Vec<(String, bool)> -- literal folders / files the manifest reaches, with whether they may be written
    • make_dirs: Vec<String> -- writable folders to create when missing (the app's own folders, the folders of fs.write rules): the kernel can only grant paths that exist
    • exec_allowed: bool -- the manifest names at least one program (execve is denied otherwise)
    • connect_restrict: bool -- restrict TCP connect to connect_ports (false: leave it unrestricted -- a * rule)
    • connect_ports: Vec<u16> -- the ports of net.connect (and 53 with a name rule); empty: no TCP connection at all
    • listen_restrict: bool -- restrict TCP bind to listen_ports
    • listen_ports: Vec<u16> -- the ports of net.listen; empty: no TCP listener at all
  • fn sandbox_plan_linux() -> LinuxPlan (Linux) what the Linux OS sandbox should enforce for the active policy (no policy: nothing)

  • struct WinPlan (Windows) what the Windows OS sandbox needs to know from the active policy ([sandbox_plan_win])

    • level: u8 -- 0 none, 1 sandbox, 2 sandbox strict
    • plugins_allowed: bool -- the manifest allows native plugins (dynamic code must stay allowed for the loader)
    • exec_allowed: bool -- child processes may be created: the manifest names a program, or has a url / print rule (open_url's ShellExecute and the print dialog can start another program)
  • fn sandbox_plan_win() -> WinPlan (Windows) what the Windows OS sandbox should enforce for the active policy (no policy: nothing)

  • fn cap_mask() -> u64 the CAP_* bits the policy leaves (all without a policy)

impl Key

  • fn grant(&self, path: &str, mode: u32) -> bool let the app read (FS_READ) or read and write (FS_WRITE) the file at path, which the user chose; false without fs.user or for a path normalize refuses

  • fn grant_dir(&self, dir: &str, mode: u32) -> bool the same for a folder and everything below it

  • fn trusted<R>(&self, f: impl FnOnce() -> R) -> R run f on this thread without the file checks

  • fn ask_here(&self, on: bool) this thread (the UI's) shows the questions (on) or nobody does (off: the open questions are withdrawn, waiting threads are refused)

  • fn answer(&self, id: u32, a: Answer) -> bool the user's answer to question id -> false when it is no longer open. The answer decides the question's ask line; waiting threads continue.

  • fn set_answer(&self, a: Option<Answer>) answer every question with a, without asking (None: ask; jfgui_PERM_ANSWER)

  • fn set_wait(&self, ms: u32) how long a thread other than the asking one waits for an answer (ms)

  • fn set_store(&self, path: Option<&str>) where Always / Never answers are kept (None: in memory only); the answers of the new place are read, the ones of this run stay

  • fn questions() -> Vec<Question> the questions waiting for the user, oldest first

  • fn decisions() -> Vec<Decision> every ask line of the manifest and every answered rule (agent actions, stored answers of lines the manifest no longer has) with its answer, in that order

  • fn forget(rule: &str) -> bool revoke the answer for rule (this run's and the stored one): the next access asks again -> false when there was none

  • fn forget_all() revoke every answer (this run's and the stored ones)

  • fn reload() read the stored answers again (another program of the app changed them)

  • fn agent_rule(action: &str) -> AgentRule agent.deny / agent.confirm of the manifest for action (Free without a manifest)

  • fn agent_ask(action: &str, description: &str) -> Verdict ask the user whether an agent may run action (one decision per action, "agent ACTION"); description is shown as the reason

  • fn agent_refused(action: &str) record that an agent was refused action (agent.deny, an action the app keeps to itself)

  • struct PluginRights the rights of a native plugin: its own manifest (None: unrestricted, the app has none and neither has the plugin)

impl PluginRights

  • fn parse(name: &str, text: &str, dir: &str) -> Result<Arc<PluginRights>, String> a plugin's manifest text (the syntax of PERMISSIONS without ask and agent lines; $PLUGIN = dir); Err names the bad line

  • fn none(name: &str) -> Arc<PluginRights> no rights at all (a plugin without a manifest in an app with one)

  • fn unrestricted(name: &str) -> Arc<PluginRights> no restriction of its own (the app's rules still apply)

  • fn name(&self) -> &str the plugin's name (its file name without extension)

  • fn restricted(&self) -> bool whether the plugin has rules of its own

  • fn plugin_rights(lib_path: &str) -> Result<Arc<PluginRights>, String> the rights of the native library at lib_path: its manifest "<stem>.permissions" beside it; without one: no rights when the app has a manifest, else unrestricted. Err: a manifest that does not parse (do not load the plugin).

  • fn on_behalf<R>(rights: &Arc<PluginRights>, f: impl FnOnce() -> R) -> R f on this thread on behalf of the plugin: every check must also pass its rules

  • fn plugin_scope() -> Option<Arc<PluginRights>> the innermost plugin scope of this thread

  • fn font_dirs() -> Vec<String> the system font folders in the order fontdb scans them: jfgui_FONTDIRS (';' separated, on Linux also ':'), else the Windows / XDG folders (macOS and iOS: /System/Library/Fonts, /Library/Fonts, ~/Library/Fonts; Android: /system/fonts, /product/fonts, real paths as android_files.rs keeps the system's folders); on Linux then fontconfig's own folders (fontconfig_dirs: NixOS, TeX fonts, a <dir> of the user) and in Flatpak the host's fonts

  • fn net_connect_allowed(addr: &crate::net::SocketAddr) -> bool whether a TCP connection or a UDP datagram to addr is allowed: a net.connect rule with that address, an address a permitted name resolved to, or port 53 (DNS) with name rules

  • fn net_listen_allowed(addr: &crate::net::SocketAddr) -> bool whether a TCP listener (or a UDP socket with a fixed port) may bind addr

  • fn net_listen_granted(addr: &crate::net::SocketAddr) -> bool whether net.listen allows a socket on addr now, quietly (nothing recorded, nobody asked; an ask line only by its answer): a UDP socket on port 0, which needs no rule, may answer its peers when one covers it (net.rs)

  • fn net_host_allowed(host: &str, port: u16) -> bool (G7d) whether a connection to host as written (a name, an IPv4 address, an IPv6 address with or without brackets, localhost) on port is allowed: a net.connect rule for that name, block or address and port. The browser's WebSocket asks this (the browser resolves names itself, so there is no lookup to check first)

  • fn net_name_allowed(host: &str) -> bool whether host may be resolved: a net.connect rule names it (or allows every host)

  • fn net_resolved(host: &str, addrs: &[crate::net::SocketAddr]) (resolvers) host resolved to addrs: connections to them get the ports of host's rules

  • fn normalize(path: &str) -> Option<String> path as an absolute, normalised path of this OS (relative paths against cwd()), or None for a path the policy refuses. The normalisation is lexical: junctions, symbolic links and 8.3 names are not resolved, so rules match the path as written, not its final target.

  • fn normalize_for(path: &str, windows: bool, cwd: &str) -> Option<String> normalize with the rules of Windows (windows = true) or Linux against the folder cwd

  • fn pattern_matches(pattern: &str, path: &str) -> bool whether pattern (manifest syntax after variables) matches path; both normalised with the rules of this OS (tests)

  • fn check(text: &str) -> Result<(), String> (build checks, tests) whether text is a valid manifest: Err names the first bad line

Source: docs/API.md in the JFLib repository.