awscope 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- awscope/__init__.py +47 -0
- awscope/_doctor.py +198 -0
- awscope/_selftest.py +7 -0
- awscope/cli.py +328 -0
- awscope/graph.py +570 -0
- awscope/model.py +194 -0
- awscope-0.1.0.dist-info/METADATA +201 -0
- awscope-0.1.0.dist-info/RECORD +12 -0
- awscope-0.1.0.dist-info/WHEEL +5 -0
- awscope-0.1.0.dist-info/entry_points.txt +2 -0
- awscope-0.1.0.dist-info/licenses/LICENSE +202 -0
- awscope-0.1.0.dist-info/top_level.txt +1 -0
awscope/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""awscope -- the scope graph a company, a household and a friend group can share.
|
|
2
|
+
|
|
3
|
+
from awscope import ScopeGraph
|
|
4
|
+
|
|
5
|
+
g = ScopeGraph("scopes.json") # or ScopeGraph() in memory
|
|
6
|
+
g.create_scope("acme", "org", actor="dana") # dana becomes owner
|
|
7
|
+
g.create_scope("sam", "person", actor="sam")
|
|
8
|
+
g.create_scope("sam-home", "household", actor="sam")
|
|
9
|
+
g.add_member("sam", "acme", "member", actor="dana")
|
|
10
|
+
g.add_member("alex", "sam-home", "member", actor="sam")
|
|
11
|
+
|
|
12
|
+
g.grant_link("sam", "sam-home", ["calendar.read"], granted_by="sam")
|
|
13
|
+
d = g.check("alex", "sam-home", "calendar.read", "sam")
|
|
14
|
+
d.allowed, d.reason, d.via
|
|
15
|
+
|
|
16
|
+
g.offboard("sam", "acme", actor="dana") # personal scopes are untouched
|
|
17
|
+
|
|
18
|
+
Membership answers "is this mine"; a consent link, granted by the owner of the
|
|
19
|
+
data, is the only way across a scope boundary. Every check fails closed.
|
|
20
|
+
Every `actor` is host-asserted: authenticate the caller before passing it.
|
|
21
|
+
"""
|
|
22
|
+
from .graph import SCHEMA, ScopeGraph, validate
|
|
23
|
+
from .model import (
|
|
24
|
+
ADMIN_ROLES,
|
|
25
|
+
KINDS,
|
|
26
|
+
PERSONAL_KINDS,
|
|
27
|
+
REALMS,
|
|
28
|
+
ROLES,
|
|
29
|
+
ConsentLink,
|
|
30
|
+
Decision,
|
|
31
|
+
Membership,
|
|
32
|
+
RefusedError,
|
|
33
|
+
Scope,
|
|
34
|
+
ScopeError,
|
|
35
|
+
StoreError,
|
|
36
|
+
capability_covers,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
__version__ = "0.1.0"
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"ScopeGraph", "SCHEMA", "validate",
|
|
43
|
+
"Scope", "Membership", "ConsentLink", "Decision",
|
|
44
|
+
"ScopeError", "RefusedError", "StoreError",
|
|
45
|
+
"KINDS", "PERSONAL_KINDS", "REALMS", "ROLES", "ADMIN_ROLES", "capability_covers",
|
|
46
|
+
"__version__",
|
|
47
|
+
]
|
awscope/_doctor.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Stack-aware `doctor` for awscope.
|
|
2
|
+
|
|
3
|
+
GENERATED BY gen_aw_doctor.py -- DO NOT EDIT.
|
|
4
|
+
Regenerate it with the generator named above; a hand-edit here is reverted by
|
|
5
|
+
the next run and fails the parity gate.
|
|
6
|
+
|
|
7
|
+
Why a doctor exists at all: the aw* bricks are designed to COMPOSE, so the
|
|
8
|
+
interesting failures live BETWEEN them. "awscope is installed" is not the useful
|
|
9
|
+
fact -- "awscope is installed and the thing it pairs with is not" is. This reports
|
|
10
|
+
the whole stack, not just itself.
|
|
11
|
+
|
|
12
|
+
stdlib only, on purpose: a diagnostic that cannot run because a dependency is
|
|
13
|
+
missing is worthless precisely when you need it.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import importlib.util
|
|
18
|
+
import os
|
|
19
|
+
import shutil
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
#: Frozen from the Aither World registry at generation time. A shipped
|
|
23
|
+
#: package cannot read the registry, and a doctor that guessed at the family
|
|
24
|
+
#: would go stale in silence. Regenerate to update.
|
|
25
|
+
SELF = 'awscope'
|
|
26
|
+
FAMILY = [
|
|
27
|
+
'awask', 'awavatar', 'awbac', 'awbrain', 'awbrowse', 'awcams', 'awclassify', 'awdecide',
|
|
28
|
+
'awdeck', 'awdelphi', 'awdit', 'awembed', 'awevolve', 'awfind', 'awflow', 'awfocus', 'awgit',
|
|
29
|
+
'awgraph', 'awgym', 'awiam', 'awkno', 'awm', 'awmail', 'awmine', 'awnboard', 'awnest', 'awnet',
|
|
30
|
+
'awplay', 'awpool', 'awpredict', 'awprism', 'awprove', 'awreason', 'awrecover', 'awrecurse',
|
|
31
|
+
'awrelay', 'awrena', 'awrepl', 'awreport', 'awresearch', 'awrise', 'awrouter', 'awrtifact',
|
|
32
|
+
'awrun', 'awscreen', 'awseal', 'awsettings', 'awshare', 'awsprite', 'awstorage', 'awsuite',
|
|
33
|
+
'awswarm', 'awtax', 'awtoll', 'awtunnel', 'awvision', 'awvoice', 'awwall', 'gawbbonet',
|
|
34
|
+
]
|
|
35
|
+
PAIRS_WITH = ['awbac', 'awdit', 'awnboard', 'awseal', 'awshare']
|
|
36
|
+
|
|
37
|
+
#: This brick's OWN config, read out of its source at generation time.
|
|
38
|
+
#: ENV_REQUIRED is `os.environ["X"]` -- absent, that is a KeyError the moment
|
|
39
|
+
#: the line runs. ENV_OPTIONAL is `os.getenv("X")`, which returns None and lets
|
|
40
|
+
#: the caller cope. Only this brick's namespace is listed: reporting the
|
|
41
|
+
#: platform-wide vars it also touches would be noise, and a doctor that floods
|
|
42
|
+
#: gets ignored.
|
|
43
|
+
ENV_REQUIRED = []
|
|
44
|
+
ENV_OPTIONAL = []
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _installed(mod: str) -> "str | None":
|
|
48
|
+
"""Version if importable, else None. Never raises -- a broken sibling must
|
|
49
|
+
not take the diagnostic down with it."""
|
|
50
|
+
try:
|
|
51
|
+
if importlib.util.find_spec(mod) is None:
|
|
52
|
+
return None
|
|
53
|
+
except (ImportError, ValueError):
|
|
54
|
+
return None
|
|
55
|
+
try:
|
|
56
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
57
|
+
try:
|
|
58
|
+
return version(mod)
|
|
59
|
+
except PackageNotFoundError:
|
|
60
|
+
return "installed"
|
|
61
|
+
except Exception:
|
|
62
|
+
return "installed"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def report(out=None) -> int:
|
|
66
|
+
"""Print the stack picture. 0 = this brick and its pairs are present."""
|
|
67
|
+
out = out or sys.stdout
|
|
68
|
+
print(f"{SELF} doctor", file=out)
|
|
69
|
+
|
|
70
|
+
mine = _installed(SELF)
|
|
71
|
+
print(f" self {SELF} {mine or 'NOT IMPORTABLE'}", file=out)
|
|
72
|
+
shim = shutil.which(SELF)
|
|
73
|
+
print(f" command {shim or 'not on PATH'}", file=out)
|
|
74
|
+
|
|
75
|
+
# The stack. Siblings this brick pairs with are called out separately,
|
|
76
|
+
# because a missing pair is a REASON, while a missing unrelated brick is
|
|
77
|
+
# just a fact about your machine.
|
|
78
|
+
missing_pairs, present = [], []
|
|
79
|
+
for name in FAMILY:
|
|
80
|
+
v = _installed(name)
|
|
81
|
+
if v:
|
|
82
|
+
present.append(name)
|
|
83
|
+
elif name in PAIRS_WITH:
|
|
84
|
+
missing_pairs.append(name)
|
|
85
|
+
print(f" stack {len(present)}/{len(FAMILY)} aw* packages installed",
|
|
86
|
+
file=out)
|
|
87
|
+
if present:
|
|
88
|
+
print(f" {' '.join(sorted(present))}", file=out)
|
|
89
|
+
|
|
90
|
+
missing_req = [v for v in ENV_REQUIRED if not os.environ.get(v)]
|
|
91
|
+
if ENV_REQUIRED or ENV_OPTIONAL:
|
|
92
|
+
have = sum(1 for v in ENV_REQUIRED + ENV_OPTIONAL if os.environ.get(v))
|
|
93
|
+
total = len(ENV_REQUIRED) + len(ENV_OPTIONAL)
|
|
94
|
+
print(f" config {have}/{total} of this brick's own vars set", file=out)
|
|
95
|
+
if missing_req:
|
|
96
|
+
# Not a preference. os.environ[...] raises the moment it runs.
|
|
97
|
+
print(f" MISSING REQUIRED: {' '.join(missing_req)}", file=out)
|
|
98
|
+
|
|
99
|
+
local = _local_checks()
|
|
100
|
+
for line in local:
|
|
101
|
+
print(f" {line}", file=out)
|
|
102
|
+
problems, unjudged = _local_verdict()
|
|
103
|
+
|
|
104
|
+
if mine is None:
|
|
105
|
+
print(f"\nverdict: {SELF} itself is not importable. Reinstall it before "
|
|
106
|
+
f"anything else here means much.", file=out)
|
|
107
|
+
return 1
|
|
108
|
+
if missing_req:
|
|
109
|
+
print(f"\nverdict: {SELF} is missing required config "
|
|
110
|
+
f"({', '.join(missing_req)}). Those are read with os.environ[...], "
|
|
111
|
+
f"so the code path that needs them raises rather than degrades.",
|
|
112
|
+
file=out)
|
|
113
|
+
return 1
|
|
114
|
+
# A measured NO outranks a missing optional pair: awrise printed
|
|
115
|
+
# "nothing wakes run-due" and still exited 0 because the missing-pairs
|
|
116
|
+
# branch returned first (measured 2026-09-20).
|
|
117
|
+
if problems:
|
|
118
|
+
for p in problems:
|
|
119
|
+
print(f"\nverdict: {p}", file=out)
|
|
120
|
+
return 1
|
|
121
|
+
if unjudged:
|
|
122
|
+
for u in unjudged:
|
|
123
|
+
print(f"\nverdict: UNJUDGED -- could not judge: {u}", file=out)
|
|
124
|
+
return 2
|
|
125
|
+
if missing_pairs:
|
|
126
|
+
print(f"\nverdict: {SELF} works, but pairs with "
|
|
127
|
+
f"{', '.join(sorted(missing_pairs))} which "
|
|
128
|
+
f"{'is' if len(missing_pairs) == 1 else 'are'} not installed. "
|
|
129
|
+
f"That is a capability you are missing, not an error.", file=out)
|
|
130
|
+
return 0
|
|
131
|
+
print(f"\nverdict: {SELF} and everything it pairs with are present.", file=out)
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _local_verdict() -> tuple:
|
|
136
|
+
"""The brick's OWN verdict, folded into the exit code.
|
|
137
|
+
|
|
138
|
+
Without this the local lines are DECORATION. Measured 2026-09-20: awrise
|
|
139
|
+
printed "hostclock NOT INSTALLED -- nothing wakes run-due" and "last tick
|
|
140
|
+
never", then exited 0 -- teaching an operator that a doctor exit code
|
|
141
|
+
carries no information. A brick opts in with `_doctor_local_verdict()`
|
|
142
|
+
returning (problems, unjudged); a brick without one is unaffected.
|
|
143
|
+
"""
|
|
144
|
+
try:
|
|
145
|
+
mod = importlib.import_module(f"{SELF}.doctor_local")
|
|
146
|
+
problems, unjudged = mod._doctor_local_verdict()
|
|
147
|
+
except Exception: # noqa: BLE001
|
|
148
|
+
return [], []
|
|
149
|
+
return list(problems or []), list(unjudged or [])
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _local_checks() -> "list[str]":
|
|
153
|
+
"""Per-brick checks, if this package defines them.
|
|
154
|
+
|
|
155
|
+
Kept as a HOOK rather than generated guesses: the generator knows the family
|
|
156
|
+
from the registry, but it does not know what awscope needs at runtime, and a
|
|
157
|
+
doctor that invented config requirements would be confidently wrong. A
|
|
158
|
+
package supplies `_doctor_local()` returning display lines; absent, the
|
|
159
|
+
stack picture above still stands on its own.
|
|
160
|
+
"""
|
|
161
|
+
try:
|
|
162
|
+
mod = importlib.import_module(f"{SELF}.doctor_local")
|
|
163
|
+
except Exception:
|
|
164
|
+
return []
|
|
165
|
+
try:
|
|
166
|
+
return list(mod._doctor_local())
|
|
167
|
+
except Exception as exc: # noqa: BLE001
|
|
168
|
+
return [f"local checks raised {type(exc).__name__}: {exc}"]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def main(argv: "list[str] | None" = None) -> int:
|
|
172
|
+
# --self-test delegates to a SIBLING module when one exists.
|
|
173
|
+
#
|
|
174
|
+
# This file is generated and a fresh run replaces it, so a self-test
|
|
175
|
+
# written HERE is deleted by the next regeneration. awdelphi learned that
|
|
176
|
+
# the expensive way: 125 lines exercising four real failure paths --
|
|
177
|
+
# convergence, roster anonymization, resume, gateway-down -- lived in this
|
|
178
|
+
# file and were destroyed by a routine regeneration, silently, leaving a
|
|
179
|
+
# --self-test flag that reported PASS while asserting nothing.
|
|
180
|
+
#
|
|
181
|
+
# So the seam is a separate module the generator never writes. A package
|
|
182
|
+
# with real machinery to prove puts it in _selftest.py; everything else
|
|
183
|
+
# keeps the honest answer below rather than a self-test that only ever
|
|
184
|
+
# passes.
|
|
185
|
+
argv = list(argv if argv is not None else __import__("sys").argv[1:])
|
|
186
|
+
if "--self-test" in argv:
|
|
187
|
+
try:
|
|
188
|
+
from . import _selftest as _st
|
|
189
|
+
except Exception:
|
|
190
|
+
print("no _selftest module: this doctor reports the stack, and has",
|
|
191
|
+
"no machinery of its own to prove")
|
|
192
|
+
return 0
|
|
193
|
+
return int(_st.run())
|
|
194
|
+
return report()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
if __name__ == "__main__":
|
|
198
|
+
raise SystemExit(main())
|
awscope/_selftest.py
ADDED
awscope/cli.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""awscope CLI.
|
|
2
|
+
|
|
3
|
+
awscope --store scopes.json create org acme --name "Acme" --by dana --init
|
|
4
|
+
awscope --store scopes.json create team eng --parent acme --by dana
|
|
5
|
+
awscope --store scopes.json member add sam acme --role member --by dana
|
|
6
|
+
awscope --store scopes.json member rm sam acme --by dana
|
|
7
|
+
awscope --store scopes.json move notes --parent sam --by sam
|
|
8
|
+
awscope --store scopes.json link grant sam sam-home --grant calendar.read --by sam [--ttl 86400]
|
|
9
|
+
awscope --store scopes.json link revoke LINK_ID --by sam [--reason "..."]
|
|
10
|
+
awscope --store scopes.json link list [--scope sam] [--all]
|
|
11
|
+
awscope --store scopes.json check alex sam-home calendar.read sam
|
|
12
|
+
awscope --store scopes.json tree
|
|
13
|
+
awscope --self-test
|
|
14
|
+
|
|
15
|
+
The store comes from --store or AWSCOPE_STORE and is never guessed: a check
|
|
16
|
+
against a default file nobody chose answers questions about the wrong world.
|
|
17
|
+
A store path that does not exist is exit 2 for every command except
|
|
18
|
+
`create --init`, so a typo never reads as an empty world or starts a new one.
|
|
19
|
+
|
|
20
|
+
`--by` is the ACTOR and this CLI believes it. It is a local admin tool; a
|
|
21
|
+
service that exposes awscope must authenticate the caller and pass that
|
|
22
|
+
identity, never one taken from the request.
|
|
23
|
+
|
|
24
|
+
Exit codes: 0 ok / allowed 1 denied / refused 2 error (bad store, bad usage)
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import argparse
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import sys
|
|
32
|
+
from typing import List, Optional
|
|
33
|
+
|
|
34
|
+
from .graph import ScopeGraph
|
|
35
|
+
from .model import KINDS, ROLES, RefusedError, StoreError
|
|
36
|
+
|
|
37
|
+
_STORE_ENV = "AWSCOPE_STORE"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _self_test() -> int:
|
|
41
|
+
"""Proves `check` can DENY. A check that only ever allows passes every
|
|
42
|
+
happy-path test, so each arm here is a denial that must happen."""
|
|
43
|
+
now = [1_700_000_000.0]
|
|
44
|
+
g = ScopeGraph(clock=lambda: now[0])
|
|
45
|
+
f: List[str] = []
|
|
46
|
+
g.create_scope("acme", "org", actor="dana")
|
|
47
|
+
g.create_scope("eng", "team", parent_id="acme", actor="dana")
|
|
48
|
+
g.create_scope("sam", "person", actor="sam")
|
|
49
|
+
g.create_scope("sam-home", "household", actor="sam")
|
|
50
|
+
g.create_scope("notes", "workspace", parent_id="sam", actor="sam")
|
|
51
|
+
g.add_member("sam", "acme", "member", actor="dana")
|
|
52
|
+
g.add_member("sam", "eng", "member", actor="dana")
|
|
53
|
+
g.add_member("alex", "sam-home", "member", actor="sam")
|
|
54
|
+
|
|
55
|
+
if g.check("alex", "sam-home", "calendar.read", "sam"):
|
|
56
|
+
f.append("allowed across a scope boundary with NO consent link")
|
|
57
|
+
lk = g.grant_link("sam", "sam-home", ["calendar.read"], granted_by="sam", ttl_s=60)
|
|
58
|
+
if not g.check("alex", "sam-home", "calendar.read", "sam"):
|
|
59
|
+
f.append("a granted link did not allow its own capability")
|
|
60
|
+
if g.check("alex", "sam-home", "calendar.readwrite", "sam"):
|
|
61
|
+
f.append("calendar.read covered calendar.readwrite (prefix match)")
|
|
62
|
+
if g.check("alex", "sam-home", "inbox.read", "sam"):
|
|
63
|
+
f.append("a link allowed a capability it never granted")
|
|
64
|
+
if g.check("alex", "acme", "calendar.read", "sam"):
|
|
65
|
+
f.append("a link to sam-home was usable from a scope alex is not in")
|
|
66
|
+
if g.check("alex", "sam-home", "calendar.read", "no-such-scope"):
|
|
67
|
+
f.append("an unknown target scope was allowed")
|
|
68
|
+
if g.check("", "sam-home", "calendar.read", "sam"):
|
|
69
|
+
f.append("an anonymous subject was allowed")
|
|
70
|
+
try:
|
|
71
|
+
g.grant_link("sam", "sam-home", ["inbox.read"], granted_by="alex")
|
|
72
|
+
f.append("a non-admin of the source granted a link")
|
|
73
|
+
except RefusedError as exc:
|
|
74
|
+
if "only the source scope can consent" not in str(exc):
|
|
75
|
+
f.append(f"a non-admin grant was refused for the wrong reason: {exc}")
|
|
76
|
+
try:
|
|
77
|
+
g.add_member("mallory", "sam", "owner", actor="mallory")
|
|
78
|
+
f.append("a stranger made themselves owner of someone else's scope")
|
|
79
|
+
except RefusedError:
|
|
80
|
+
pass
|
|
81
|
+
try:
|
|
82
|
+
g.move_scope("notes", "acme", actor="dana")
|
|
83
|
+
f.append("a personal workspace was moved under an org")
|
|
84
|
+
except RefusedError:
|
|
85
|
+
pass
|
|
86
|
+
if g.check("dana", "acme", "notes.read", "notes"):
|
|
87
|
+
f.append("an org owner can read a personal workspace")
|
|
88
|
+
try:
|
|
89
|
+
g.grant_link("sam", "sam-home", ["inbox.read"], granted_by="sam", ttl_s=float("nan"))
|
|
90
|
+
f.append("a NaN ttl was accepted (a link that never expires)")
|
|
91
|
+
except RefusedError:
|
|
92
|
+
pass
|
|
93
|
+
now[0] += 61
|
|
94
|
+
if g.check("alex", "sam-home", "calendar.read", "sam"):
|
|
95
|
+
f.append("an EXPIRED link still allowed")
|
|
96
|
+
now[0] -= 61
|
|
97
|
+
g.revoke_link(lk.id, by="sam")
|
|
98
|
+
if g.check("alex", "sam-home", "calendar.read", "sam"):
|
|
99
|
+
f.append("a REVOKED link still allowed")
|
|
100
|
+
g.offboard("sam", "acme", actor="dana")
|
|
101
|
+
if g.roles_of("sam", "eng") or g.roles_of("sam", "acme"):
|
|
102
|
+
f.append("offboarding left company memberships behind")
|
|
103
|
+
if not g.roles_of("sam", "sam") or not g.roles_of("sam", "sam-home"):
|
|
104
|
+
f.append("offboarding touched a PERSONAL scope")
|
|
105
|
+
|
|
106
|
+
for line in f:
|
|
107
|
+
print(f"FAIL {line}")
|
|
108
|
+
verdict = "PASS (every denial denied)" if not f else f"{len(f)} FAILURE(S)"
|
|
109
|
+
print(f"awscope self-test: {verdict}")
|
|
110
|
+
return 0 if not f else 1
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _print(obj, as_json: bool) -> None:
|
|
114
|
+
if as_json:
|
|
115
|
+
print(json.dumps(obj, indent=2, sort_keys=True))
|
|
116
|
+
elif isinstance(obj, dict):
|
|
117
|
+
for k, v in obj.items():
|
|
118
|
+
print(f"{k}: {v}")
|
|
119
|
+
else:
|
|
120
|
+
print(obj)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _tree(g: ScopeGraph) -> List[str]:
|
|
124
|
+
lines: List[str] = []
|
|
125
|
+
roots = sorted(s.id for s in g.scopes.values() if s.parent_id is None)
|
|
126
|
+
|
|
127
|
+
def walk(sid: str, depth: int) -> None:
|
|
128
|
+
s = g.scopes[sid]
|
|
129
|
+
who = ", ".join(f"{m.subject}({m.role})" for m in sorted(
|
|
130
|
+
(m for m in g.members if m.scope_id == sid), key=lambda m: m.subject))
|
|
131
|
+
lines.append(f"{' ' * depth}{s.kind}:{sid}" + (f" [{who}]" if who else ""))
|
|
132
|
+
for c in sorted(x.id for x in g.scopes.values() if x.parent_id == sid):
|
|
133
|
+
walk(c, depth + 1)
|
|
134
|
+
|
|
135
|
+
for r in roots:
|
|
136
|
+
walk(r, 0)
|
|
137
|
+
for lk in sorted(g.links.values(), key=lambda x: x.id):
|
|
138
|
+
lines.append(f"link {lk.id}: {lk.source_scope} -> {lk.target_scope} "
|
|
139
|
+
f"{','.join(lk.grants)} [{lk.state(g.clock())}]")
|
|
140
|
+
return lines
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _parser() -> argparse.ArgumentParser:
|
|
144
|
+
ap = argparse.ArgumentParser(prog="awscope", description=__doc__,
|
|
145
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
146
|
+
ap.add_argument("--store", help=f"JSON store path (or ${_STORE_ENV})")
|
|
147
|
+
ap.add_argument("--json", action="store_true", help="machine-readable output")
|
|
148
|
+
ap.add_argument("--self-test", action="store_true", help="prove check can deny")
|
|
149
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
150
|
+
|
|
151
|
+
c = sub.add_parser("create", help="create a scope")
|
|
152
|
+
c.add_argument("kind", choices=KINDS)
|
|
153
|
+
c.add_argument("id")
|
|
154
|
+
c.add_argument("--name")
|
|
155
|
+
c.add_argument("--parent")
|
|
156
|
+
c.add_argument("--attr", action="append", default=[], metavar="K=V")
|
|
157
|
+
c.add_argument("--by", required=True, help="actor: owner of a new top-level scope, "
|
|
158
|
+
"or an owner/admin of --parent")
|
|
159
|
+
c.add_argument("--init", action="store_true",
|
|
160
|
+
help="allow creating the store file if it does not exist")
|
|
161
|
+
|
|
162
|
+
mv = sub.add_parser("move", help="re-parent a scope (never across personal/company)")
|
|
163
|
+
mv.add_argument("scope")
|
|
164
|
+
mv.add_argument("--parent", help="new parent; omit for top-level")
|
|
165
|
+
mv.add_argument("--by", required=True, help="owner/admin of the old and new parent")
|
|
166
|
+
|
|
167
|
+
m = sub.add_parser("member", help="add or remove a member")
|
|
168
|
+
msub = m.add_subparsers(dest="action", required=True)
|
|
169
|
+
ma = msub.add_parser("add")
|
|
170
|
+
ma.add_argument("subject")
|
|
171
|
+
ma.add_argument("scope")
|
|
172
|
+
ma.add_argument("--role", choices=ROLES, default="member")
|
|
173
|
+
ma.add_argument("--by", required=True, help="owner/admin of SCOPE")
|
|
174
|
+
mr = msub.add_parser("rm", help="remove (org/team: cascades down, never into personal scopes)")
|
|
175
|
+
mr.add_argument("subject")
|
|
176
|
+
mr.add_argument("scope")
|
|
177
|
+
mr.add_argument("--by", required=True, help="SUBJECT themselves, or an owner/admin of SCOPE")
|
|
178
|
+
|
|
179
|
+
lk = sub.add_parser("link", help="consent links")
|
|
180
|
+
lsub = lk.add_subparsers(dest="action", required=True)
|
|
181
|
+
lg = lsub.add_parser("grant")
|
|
182
|
+
lg.add_argument("source")
|
|
183
|
+
lg.add_argument("target")
|
|
184
|
+
lg.add_argument("--grant", action="append", required=True, metavar="CAPABILITY")
|
|
185
|
+
lg.add_argument("--by", required=True, help="owner/admin of SOURCE granting consent")
|
|
186
|
+
lg.add_argument("--ttl", type=float, help="seconds until it expires")
|
|
187
|
+
lg.add_argument("--id")
|
|
188
|
+
lr = lsub.add_parser("revoke")
|
|
189
|
+
lr.add_argument("link_id")
|
|
190
|
+
lr.add_argument("--by", required=True)
|
|
191
|
+
lr.add_argument("--reason", default="")
|
|
192
|
+
ll = lsub.add_parser("list")
|
|
193
|
+
ll.add_argument("--scope")
|
|
194
|
+
ll.add_argument("--all", action="store_true", help="include revoked and expired")
|
|
195
|
+
|
|
196
|
+
ck = sub.add_parser("check", help="may SUBJECT acting from ACTING use CAPABILITY on TARGET")
|
|
197
|
+
ck.add_argument("subject")
|
|
198
|
+
ck.add_argument("acting")
|
|
199
|
+
ck.add_argument("capability")
|
|
200
|
+
ck.add_argument("target")
|
|
201
|
+
|
|
202
|
+
tp = sub.add_parser("path", help="print a scope's path (awbac permission prefix)")
|
|
203
|
+
tp.add_argument("scope")
|
|
204
|
+
|
|
205
|
+
sub.add_parser("tree", help="print the scope tree, members and links")
|
|
206
|
+
return ap
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
210
|
+
# GENERATED doctor intercept (gen_aw_doctor.py) -- do not edit
|
|
211
|
+
_dv = locals().get("argv")
|
|
212
|
+
if (_dv if _dv is not None else __import__("sys").argv[1:])[:1] == ["doctor"]:
|
|
213
|
+
from ._doctor import report
|
|
214
|
+
return report()
|
|
215
|
+
# GENERATED repo-state intercept (gen_aw_doctor.py) -- do not edit
|
|
216
|
+
try:
|
|
217
|
+
from awgit import state as _aw_state
|
|
218
|
+
except Exception:
|
|
219
|
+
_aw_state = None
|
|
220
|
+
if _aw_state is not None:
|
|
221
|
+
_sv = locals().get("argv")
|
|
222
|
+
if _aw_state.cli_banner(_sv if _sv is not None else __import__("sys").argv[1:]):
|
|
223
|
+
return 0
|
|
224
|
+
ap = _parser()
|
|
225
|
+
args = ap.parse_args(argv)
|
|
226
|
+
if args.self_test:
|
|
227
|
+
return _self_test()
|
|
228
|
+
if not args.cmd:
|
|
229
|
+
ap.print_usage(sys.stderr)
|
|
230
|
+
return 2
|
|
231
|
+
store = args.store or os.environ.get(_STORE_ENV)
|
|
232
|
+
if not store:
|
|
233
|
+
print(f"awscope: no store -- pass --store PATH or set {_STORE_ENV}", file=sys.stderr)
|
|
234
|
+
return 2
|
|
235
|
+
if not os.path.exists(store) and not (args.cmd == "create" and args.init):
|
|
236
|
+
# A typo'd path is not an empty world. A read against it would answer
|
|
237
|
+
# DENY (exit 1, routine) and a write would quietly start a new store.
|
|
238
|
+
hint = " (pass `create ... --init` to start a new store)" if args.cmd == "create" else ""
|
|
239
|
+
print(f"DEAD: store {store} does not exist{hint}", file=sys.stderr)
|
|
240
|
+
return 2
|
|
241
|
+
try:
|
|
242
|
+
return _run(args, ScopeGraph(store))
|
|
243
|
+
except RefusedError as exc:
|
|
244
|
+
print(f"REFUSED: {exc}", file=sys.stderr)
|
|
245
|
+
return 1
|
|
246
|
+
except (StoreError, OSError) as exc:
|
|
247
|
+
print(f"DEAD: {exc}", file=sys.stderr)
|
|
248
|
+
return 2
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _run(args, g: ScopeGraph) -> int:
|
|
252
|
+
if args.cmd == "create":
|
|
253
|
+
attrs = {}
|
|
254
|
+
for kv in args.attr:
|
|
255
|
+
if "=" not in kv:
|
|
256
|
+
print(f"awscope: --attr wants K=V, got {kv!r}", file=sys.stderr)
|
|
257
|
+
return 2
|
|
258
|
+
k, v = kv.split("=", 1)
|
|
259
|
+
attrs[k] = v
|
|
260
|
+
s = g.create_scope(args.id, args.kind, args.name, args.parent, attrs, actor=args.by)
|
|
261
|
+
_print(s.to_dict() if args.json else f"created {g.scope_path(s.id)}", args.json)
|
|
262
|
+
return 0
|
|
263
|
+
if args.cmd == "move":
|
|
264
|
+
s = g.move_scope(args.scope, args.parent, actor=args.by)
|
|
265
|
+
_print(s.to_dict() if args.json else f"moved to {g.scope_path(s.id)}", args.json)
|
|
266
|
+
return 0
|
|
267
|
+
if args.cmd == "member":
|
|
268
|
+
if args.action == "add":
|
|
269
|
+
mm = g.add_member(args.subject, args.scope, args.role, actor=args.by)
|
|
270
|
+
_print(mm.to_dict() if args.json else f"{mm.subject} is {mm.role} of {mm.scope_id}",
|
|
271
|
+
args.json)
|
|
272
|
+
return 0
|
|
273
|
+
report = g.remove_member(args.subject, args.scope, actor=args.by)
|
|
274
|
+
if args.json:
|
|
275
|
+
_print(report, True)
|
|
276
|
+
else:
|
|
277
|
+
for r in report["removed"]:
|
|
278
|
+
print(f"removed {r['subject']} from {r['scope_id']} ({r['role']})")
|
|
279
|
+
for lid in report["revoked"]:
|
|
280
|
+
lk = g.links[lid]
|
|
281
|
+
print(f"revoked link {lid} ({lk.source_scope} -> {lk.target_scope}): "
|
|
282
|
+
f"{lk.revoke_reason}")
|
|
283
|
+
return 0
|
|
284
|
+
if args.cmd == "link":
|
|
285
|
+
if args.action == "grant":
|
|
286
|
+
lk = g.grant_link(args.source, args.target, args.grant, args.by,
|
|
287
|
+
ttl_s=args.ttl, link_id=args.id)
|
|
288
|
+
_print(lk.to_dict() if args.json else lk.id, args.json)
|
|
289
|
+
return 0
|
|
290
|
+
if args.action == "revoke":
|
|
291
|
+
lk = g.revoke_link(args.link_id, args.by, args.reason)
|
|
292
|
+
_print(lk.to_dict() if args.json else f"revoked {lk.id}", args.json)
|
|
293
|
+
return 0
|
|
294
|
+
if args.scope:
|
|
295
|
+
links = g.links_for(args.scope, include_inactive=args.all)
|
|
296
|
+
else:
|
|
297
|
+
now = g.clock()
|
|
298
|
+
links = sorted((lk for lk in g.links.values()
|
|
299
|
+
if args.all or lk.state(now) == "active"),
|
|
300
|
+
key=lambda x: (x.created_at, x.id))
|
|
301
|
+
if args.json:
|
|
302
|
+
_print([lk.to_dict() for lk in links], True)
|
|
303
|
+
else:
|
|
304
|
+
for lk in links:
|
|
305
|
+
print(f"{lk.id} {lk.source_scope} -> {lk.target_scope} "
|
|
306
|
+
f"{','.join(lk.grants)} by {lk.granted_by} [{lk.state(g.clock())}]")
|
|
307
|
+
return 0
|
|
308
|
+
if args.cmd == "check":
|
|
309
|
+
d = g.check(args.subject, args.acting, args.capability, args.target)
|
|
310
|
+
if args.json:
|
|
311
|
+
_print(d.to_dict(), True)
|
|
312
|
+
else:
|
|
313
|
+
verdict = "ALLOW" if d.allowed else "DENY"
|
|
314
|
+
print(f"{verdict}: {d.reason.removeprefix('denied: ')}"
|
|
315
|
+
+ (f" (via {d.via})" if d.via else ""))
|
|
316
|
+
return 0 if d.allowed else 1
|
|
317
|
+
if args.cmd == "path":
|
|
318
|
+
print(g.scope_path(args.scope))
|
|
319
|
+
return 0
|
|
320
|
+
if args.cmd == "tree":
|
|
321
|
+
for line in _tree(g):
|
|
322
|
+
print(line)
|
|
323
|
+
return 0
|
|
324
|
+
return 2
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
if __name__ == "__main__":
|
|
328
|
+
raise SystemExit(main())
|