Coverage for src/governed_harness/capabilities/authorizer.py: 97%

82 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1from __future__ import annotations 

2 

3import fnmatch 

4import os 

5from collections.abc import Iterable, Sequence 

6from datetime import UTC, datetime, timedelta 

7from pathlib import Path 

8 

9from governed_harness.capabilities.denial import CapabilityDenied as CapabilityDenied 

10from governed_harness.capabilities.denial import command_in_scope as command_in_scope 

11from governed_harness.capabilities.phase import current_policy 

12from governed_harness.configuration.models import CapabilityRule 

13from governed_harness.domain.ids import new_id 

14from governed_harness.domain.models import Actor, CapabilityGrant 

15 

16 

17class CapabilityAuthorizer: 

18 def authorize( 

19 self, 

20 *, 

21 actor: Actor, 

22 capability: str, 

23 resource: str, 

24 grants: Iterable[CapabilityGrant], 

25 now: datetime | None = None, 

26 allow_approval_required: bool = False, 

27 ) -> CapabilityGrant: 

28 instant = now or datetime.now(UTC) 

29 for grant in grants: 

30 if ( 

31 grant.actor != actor 

32 or grant.capability != capability 

33 or not grant.active_at(instant) 

34 ): 

35 continue 

36 if grant.approval_required and not allow_approval_required: 

37 continue 

38 if any(self._matches(resource, scope) for scope in grant.scope): 

39 return grant 

40 raise CapabilityDenied(f"{actor.actor_id} lacks {capability} for {resource}") 

41 

42 def authorize_command( 

43 self, 

44 *, 

45 actor: Actor, 

46 argv: Sequence[str], 

47 grants: Iterable[CapabilityGrant], 

48 now: datetime | None = None, 

49 ) -> CapabilityGrant: 

50 if not argv: 50 ↛ 51line 50 didn't jump to line 51 because the condition on line 50 was never true

51 raise CapabilityDenied("empty command is not authorized") 

52 resource = " ".join(argv) 

53 instant = now or datetime.now(UTC) 

54 for grant in grants: 

55 if ( 

56 grant.actor != actor 

57 or grant.capability != "process.execute" 

58 or not grant.active_at(instant) 

59 ): 

60 continue 

61 if any(command_in_scope(argv, scope) for scope in grant.scope): 

62 return grant 

63 raise CapabilityDenied(f"{actor.actor_id} lacks process.execute for {resource}") 

64 

65 @staticmethod 

66 def _matches(resource: str, scope: str) -> bool: 

67 """Whether the workspace path ``resource`` is in the glob ``scope``. A leading ``./`` 

68 is a prefix (``lstrip`` removed characters, so ``.env`` matched ``env`` and 

69 ``../src/x.py`` matched ``src/**``, F11); a path with a ``..`` part, or an absolute 

70 one, is in no scope. The glob is ``fnmatch`` as in 0.8.0, where ``*`` also crosses 

71 ``/`` (``*.py`` matches ``pkg/mod.py``, which the profiles' grants rely on).""" 

72 resource_parts = _workspace_parts(resource) 

73 scope_parts = _workspace_parts(scope) 

74 if resource_parts is None or scope_parts is None: 

75 return False 

76 normalized_resource = "/".join(resource_parts) 

77 normalized_scope = "/".join(scope_parts) 

78 if normalized_scope == "**": 

79 return True 

80 if fnmatch.fnmatchcase(normalized_resource, normalized_scope): 

81 return True 

82 if normalized_scope.endswith("/**"): 

83 base = normalized_scope[:-3].rstrip("/") 

84 return normalized_resource == base or normalized_resource.startswith(f"{base}/") 

85 return normalized_resource == normalized_scope 

86 

87 

88def _workspace_parts(path: str) -> list[str] | None: 

89 """The parts of a workspace-relative path (``./`` prefixes and empty parts dropped), 

90 ``None`` for an absolute path or one with a ``..`` part.""" 

91 text = path.replace(os.sep, "/").replace("\\", "/") 

92 if text.startswith("/") or (len(text) > 1 and text[1] == ":"): 

93 return None 

94 while text.startswith("./"): 

95 text = text.removeprefix("./") 

96 parts = [part for part in text.split("/") if part not in {"", "."}] 

97 if ".." in parts: 

98 return None 

99 return parts 

100 

101 

102def grants_from_rules( 

103 execution_id: str, 

104 actor: Actor, 

105 rules: Iterable[CapabilityRule], 

106 *, 

107 lifetime: timedelta = timedelta(hours=8), 

108) -> list[CapabilityGrant]: 

109 policy = current_policy() 

110 if policy is not None: 

111 # governance.phaseCapabilities (#4): only what the running phase allows. 

112 rules = policy.apply(actor, rules) 

113 issued = datetime.now(UTC) 

114 return [ 

115 CapabilityGrant( 

116 grant_id=new_id("grant"), 

117 execution_id=execution_id, 

118 actor=actor, 

119 capability=rule.capability, 

120 scope=rule.scope, 

121 issued_at=issued, 

122 expires_at=issued + lifetime, 

123 conditions=rule.conditions, 

124 approval_required=rule.approval_required, 

125 ) 

126 for rule in rules 

127 ] 

128 

129 

130def contained_path(root: Path, candidate: Path, *, allow_missing: bool = True) -> Path: 

131 resolved_root = root.resolve(strict=True) 

132 unresolved = candidate if candidate.is_absolute() else resolved_root / candidate 

133 resolved_candidate = unresolved.resolve(strict=not allow_missing) 

134 if resolved_candidate != resolved_root and resolved_root not in resolved_candidate.parents: 

135 raise CapabilityDenied(f"path escapes workspace: {candidate}") 

136 # Reject any existing symlink in the path from the workspace root to the candidate. The 

137 # candidate may reach the workspace through a symlinked ancestor outside it (macOS: /var -> 

138 # /private/var), so the workspace part is taken after the first ancestor, from the top, that 

139 # resolves to the workspace root; links inside the workspace are still checked below. 

140 workspace_prefix = next( 

141 ( 

142 ancestor 

143 for ancestor in reversed((unresolved, *unresolved.parents)) 

144 if ancestor.resolve() == resolved_root 

145 ), 

146 None, 

147 ) 

148 if workspace_prefix is None: 148 ↛ 149line 148 didn't jump to line 149 because the condition on line 148 was never true

149 raise CapabilityDenied(f"path escapes workspace: {candidate}") 

150 relative = unresolved.relative_to(workspace_prefix) 

151 current = resolved_root 

152 for part in relative.parts: 

153 current = current / part 

154 if current.exists() and current.is_symlink(): 

155 raise CapabilityDenied(f"symlink path is not allowed: {current}") 

156 return resolved_candidate