import uuid
from typing import Set, Dict, List, Optional
# Allowed rights for simplicity
READ = "r"
WRITE = "w"
EXECUTE = "x"
class CapabilityToken:
def __init__(self, resource: str, rights: Set[str]):
self.id = str(uuid.uuid4())
self.resource = resource # e.g. file path
self.rights = set(rights)
self.revoked = False
def revoke(self):
self.revoked = True
def __repr__(self):
return f"<Token {self.id[:8]} res={self.resource} rights={self.rights} revoked={self.revoked}>"
class TokenManager:
def __init__(self):
self._tokens: Dict[str, CapabilityToken] = {}
def issue(self, resource: str, rights: Set[str]) -> CapabilityToken:
tok = CapabilityToken(resource, rights)
self._tokens[tok.id] = tok
return tok
def revoke(self, token_id: str) -> None:
tok = self._tokens.get(token_id)
if tok:
tok.revoke()
def get(self, token_id: str) -> Optional[CapabilityToken]:
return self._tokens.get(token_id)
class File:
def __init__(self, path: str, content: str = ""):
self.path = path
self.content = content
class FileSystem:
def __init__(self):
self._files: Dict[str, File] = {}
def create_file(self, path: str, content: str = "") -> File:
if path in self._files:
raise ValueError(f"File {path} already exists")
f = File(path, content)
self._files[path] = f
return f
def get_file(self, path: str) -> File:
if path not in self._files:
raise FileNotFoundError(path)
return self._files[path]
class Process:
_next_pid = 1
def __init__(self, fs: FileSystem, tm: TokenManager, tokens: Optional[List[CapabilityToken]] = None, parent=None):
self.fs = fs
self.tm = tm
self.pid = Process._next_pid
Process._next_pid += 1
self.parent = parent
# store references to the tokens; revocation is checked at use time
self.tokens: List[CapabilityToken] = list(tokens) if tokens else []
def spawn_child(self) -> 'Process':
"""Spawn a child process inheriting this process's tokens."""
child = Process(self.fs, self.tm, tokens=self.tokens, parent=self)
print(f"Spawned child PID {child.pid} from PID {self.pid}")
return child
def add_token(self, token: CapabilityToken) -> None:
self.tokens.append(token)
def has_access(self, path: str, op: str) -> bool:
for tok in self.tokens:
if tok.resource == path and op in tok.rights and not tok.revoked:
return True
return False
def read(self, path: str) -> str:
if not self.has_access(path, READ):
raise PermissionError(f"PID {self.pid} lacks read capability for {path}")
file = self.fs.get_file(path)
print(f"PID {self.pid} read {path}")
return file.content
def write(self, path: str, data: str) -> None:
if not self.has_access(path, WRITE):
raise PermissionError(f"PID {self.pid} lacks write capability for {path}")
file = self.fs.get_file(path)
file.content = data
print(f"PID {self.pid} wrote to {path}")
def exec(self, path: str) -> None:
if not self.has_access(path, EXECUTE):
raise PermissionError(f"PID {self.pid} lacks execute capability for {path}")
print(f"PID {self.pid} executed {path}")
# Example usage
if __name__ == "__main__":
fs = FileSystem()
tm = TokenManager()
fs.create_file("/bin/hello", "#!/bin/sh\necho Hello")
fs.create_file("/tmp/data.txt", "secret")
# Create an initial "root" process and issue capabilities
root = Process(fs, tm)
hello_exec = tm.issue("/bin/hello", {READ, EXECUTE})
data_rw = tm.issue("/tmp/data.txt", {READ, WRITE})
root.add_token(hello_exec)
root.add_token(data_rw)
# Spawn a child; it inherits root's tokens
child = root.spawn_child()
print(child.read("/tmp/data.txt"))
child.write("/tmp/data.txt", "new content")
child.exec("/bin/hello")
# Revoke a token
tm.revoke(data_rw.id)
try:
child.read("/tmp/data.txt")
except PermissionError as e:
print("Access denied after revocation:", e)
# Issue a new token and give only to the parent
new_read = tm.issue("/tmp/data.txt", {READ})
root.add_token(new_read)
print("Root can still read:", root.read("/tmp/data.txt"))
try:
child.read("/tmp/data.txt")
except PermissionError as e:
print("Child still denied:", e)