Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 26 additions & 18 deletions packages/syft-enclave/src/syft_enclaves/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -732,26 +732,26 @@ def _forward_job_to_dos(self, job_dir: Path, do_emails: list[str]):
)

def _forward_review_files_to_dos(self, review_dir: Path, do_emails: list[str]):
"""Forward each DO its approval state file, with the job's state.
"""Forward each DO the approval state file of every DO, with the job's state.

The state holds the submitter's request, which a DO approves within.
The state holds the submitter's request, which a DO approves within. The
approval files of the other DOs show a DO who approved the job, and which
files.
"""
datasite_dir = self._rds.syftbox_folder / self._rds.email
syncer = self._rds.sync_engine.datasite_owner_syncer
state_file = review_dir / "state.yaml"
for do_email in do_emails:
approval_file = review_dir / enclave_approval_file_name(do_email)
files_by_datasite_path = {
f.relative_to(datasite_dir): f.read_bytes()
for f in (approval_file, state_file)
}
events_message = syncer.event_cache.create_events_for_files(
files_by_datasite_path
)
syncer.process_events_for_own_state_and_peers(
recipients=[do_email],
file_change_events_message=events_message,
)
approval_files = [review_dir / enclave_approval_file_name(e) for e in do_emails]
files_by_datasite_path = {
f.relative_to(datasite_dir): f.read_bytes()
for f in (*approval_files, review_dir / "state.yaml")
}
events_message = syncer.event_cache.create_events_for_files(
files_by_datasite_path
)
syncer.process_events_for_own_state_and_peers(
recipients=do_emails,
file_change_events_message=events_message,
)

def _get_files_in_dir(self, directory: Path) -> dict[Path, bytes]:
"""Read all files under directory, keyed by path relative to the datasite root."""
Expand Down Expand Up @@ -788,8 +788,9 @@ def _set_job_permissions(
approval_dos: list[str],
):
"""Grant inbox read to everyone who needs to see the job (referenced +
approving DOs), state read to them and the submitter, and write to each
approving DO on its own approval and log request files."""
approving DOs), state read to them and the submitter, write to each
approving DO on its own approval and log request files, and read to every
approving DO on every approval file."""
job_manager = self._rds.job_client.manager
datasite = self._rds.syftbox_folder / self._rds.email
ctx = SyftPermContext(datasite=datasite)
Expand All @@ -811,6 +812,13 @@ def _set_job_permissions(
):
ctx.open(review_rel / name).grant_write_access(do_email)

# Each DO shows who approved the job, and which files. The submitter
# does not read the approval files.
for party in approval_dos:
approval_file = ctx.open(review_rel / enclave_approval_file_name(party))
for do_email in approval_dos:
approval_file.grant_read_access(do_email)

@classmethod
def from_config(
cls,
Expand Down
67 changes: 39 additions & 28 deletions packages/syft-enclave/src/syft_enclaves/enclave_job_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@
)


# How a data owner's decision on a job shows. Any other status shows as pending.
APPROVAL_MARKS = {JobStatus.APPROVED: "✓", JobStatus.REJECTED: "✗"}
PENDING_MARK = "pending"


class PartyApprovalStatus(BaseModel):
"""Tracks approval from a single party in a multi-party (enclave) job."""

Expand Down Expand Up @@ -185,14 +190,10 @@ def status(self) -> str:
return self._state.status.value
if self._required_approvers is not None:
return self._status_from_required_approvers(self._required_approvers)
approvals = load_enclave_approval_files(self.job_review_path)
if not approvals:
if not self._approval_file.exists():
return self._state.status.value
if any(a.status == JobStatus.REJECTED for a in approvals):
return JobStatus.REJECTED.value
if all(a.status == JobStatus.APPROVED for a in approvals):
return JobStatus.APPROVED.value
return JobStatus.PENDING.value
# A data owner holds every party's approval file, and shows its own.
return self._load_own_approval().status.value

@property
def can_approve(self) -> bool:
Expand Down Expand Up @@ -222,24 +223,25 @@ def _status_from_required_approvers(self, required: list[str]) -> str:
def read_permission_rows(self) -> list[tuple[str, str]]:
"""The read permission state as (label, value) rows, for display.

The enclave shows the approval of every party and what all approved.
A data owner shows its own approval.
The enclave and each data owner also show, with a line per data owner,
whether it approved the job and which output files it approved.
"""
rows = [("Requested", format_read_permissions(self.requested_read_permissions))]
if self.current_user_email == self.datasite_owner_email:
return rows + self._party_rows()
if self._approval_file.exists():
own = format_read_permissions(self.approved_read_permissions)
rows.append(("Approved by you", own))
rows.append(("Approved by all", "needs the approval of every party"))
return rows

def _party_rows(self) -> list[tuple[str, str]]:
"""Each party's approval, then what every party approved."""
if not self._holds_approval_files:
return rows
approvals = _party_approvals(self.job_review_path, self._required_approvers)
rows = [(f"Approved by {p}", _approval_summary(a)) for p, a in approvals]
shared = format_read_permissions(self.read_permissions_to_share)
return [*rows, ("Approved by all", shared)]
job_lines = [_job_approval_line(party, a) for party, a in approvals]
file_lines = [f"{party}: {_approved_output_files(a)}" for party, a in approvals]
return rows + [
("Job approved", "\n".join(job_lines)),
("Output files approved", "\n".join(file_lines)),
]

@property
def _holds_approval_files(self) -> bool:
"""Whether this client holds the approval files: the enclave or a data owner."""
is_enclave = self.current_user_email == self.datasite_owner_email
return is_enclave or self._approval_file.exists()

def _restrict_to_request(
self, read_permissions: Optional[ReadPermissions]
Expand Down Expand Up @@ -403,12 +405,21 @@ def reject(self, reason: Optional[str] = None) -> None:
print(f"Job '{self.name}' rejected by {self.current_user_email}.")


def _approval_summary(approval: Optional[PartyApprovalStatus]) -> str:
"""One party's approval for display, or why it has none."""
if approval is None:
return "(no approval file)"
if approval.status != JobStatus.APPROVED:
return f"({approval.status.value})"
def _job_approval_line(party: str, approval: Optional[PartyApprovalStatus]) -> str:
"""The party, then ✓ when it approved the job, ✗ and its reason when it
rejected it, and pending otherwise."""
status = approval.status if approval is not None else JobStatus.PENDING
line = f"{party} {APPROVAL_MARKS.get(status, PENDING_MARK)}"
if status == JobStatus.REJECTED and approval.reason:
# On one line, so that each party keeps one line.
line += f" ({' '.join(approval.reason.split())})"
return line


def _approved_output_files(approval: Optional[PartyApprovalStatus]) -> str:
"""The output files the party approved, for display; "none" until it approved."""
if approval is None or approval.status != JobStatus.APPROVED:
return format_read_permissions({})
return format_read_permissions(approval.approved_read_permissions)


Expand Down
84 changes: 67 additions & 17 deletions packages/syft-enclave/tests/test_read_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,15 +257,26 @@ def has_file(client, name):
return (Path(client.jobs["j"].job_review_path) / name).exists()


def readers_of(enclave, name, parties):
"""The parties that may read ``name`` in the enclave's review folder."""
def review_file_path(enclave, name):
"""The path of ``name`` in the enclave's review folder, relative to its datasite."""
datasite = enclave._rds.syftbox_folder / enclave.email
review = Path(enclave._rds.job_client.jobs["j"].job_review_path)
path = str((review / name).relative_to(datasite))
ctx = SyftPermContext(datasite=datasite)
return str((review / name).relative_to(datasite))


def readers_of(enclave, name, parties):
"""The parties that may read ``name`` in the enclave's review folder."""
ctx = SyftPermContext(datasite=enclave._rds.syftbox_folder / enclave.email)
path = review_file_path(enclave, name)
return [p for p in parties if ctx.can_read(path, p.email)]


def enclave_accepts_write(enclave, party, name):
"""Whether the enclave accepts a change from ``party`` to ``name`` in its review folder."""
syncer = enclave._rds.sync_engine.datasite_owner_syncer
return syncer.check_write_permission(party.email, review_file_path(enclave, name))


def test_submitter_gets_no_logs_without_approval():
enclave, do1, do2, ds = build_quad()
submit(ds, enclave, do1, do2, OK_CODE, readable(LOGS, ds.email))
Expand Down Expand Up @@ -652,6 +663,11 @@ def test_owner_logs_approval_warns():
do1.jobs["j"].approve(share_files=logs)


def lines(value):
"""The lines of a row value, in any order."""
return set(value.splitlines())


def test_display_on_enclave_shows_every_party():
enclave, do1, do2, ds = build_quad()
submit(
Expand All @@ -666,25 +682,57 @@ def test_display_on_enclave_shows_every_party():
assert rows["Requested"] == (
f"returncode.txt ({ds.email}), stdout.txt ({ds.email})"
)
assert rows[f"Approved by {do1.email}"] == f"returncode.txt ({ds.email})"
assert rows[f"Approved by {do2.email}"] == "(pending)"
assert rows["Approved by all"] == "none"
assert lines(rows["Job approved"]) == {f"{do1.email} ✓", f"{do2.email} pending"}
assert lines(rows["Output files approved"]) == {
f"{do1.email}: returncode.txt ({ds.email})",
f"{do2.email}: none",
}


def test_display_on_data_owner_shows_own_approval():
def test_data_owner_sees_every_owner_approval():
enclave, do1, do2, ds = build_quad()
return_code = readable(RETURN_CODE, ds.email)
submit(ds, enclave, do1, do2, OK_CODE, return_code)
distribute(enclave, do1)
distribute(enclave, do1, do2)
do1.jobs["j"].approve(share_files=return_code)
enclave.sync()
do2.sync()

rows = dict(do2.jobs["j"].read_permission_rows())
assert lines(rows["Job approved"]) == {f"{do1.email} ✓", f"{do2.email} pending"}
assert lines(rows["Output files approved"]) == {
f"{do1.email}: returncode.txt ({ds.email})",
f"{do2.email}: none",
}

do2.jobs["j"].reject("too much\ndata")
enclave.sync()
do1.sync()

job = do1.jobs["j"]
assert job.read_permission_rows() == [
("Requested", f"returncode.txt ({ds.email})"),
("Approved by you", f"returncode.txt ({ds.email})"),
("Approved by all", "needs the approval of every party"),
]
assert "Approved by you:" in job._repr_html_()
rows = dict(job.read_permission_rows())
# The reason stays on the line of the data owner that rejected.
assert lines(rows["Job approved"]) == {
f"{do1.email} ✓",
f"{do2.email} ✗ (too much data)",
}
assert lines(rows["Output files approved"]) == {
f"{do1.email}: returncode.txt ({ds.email})",
f"{do2.email}: none",
}
# A data owner's status stays its own decision.
assert job.status == "approved"
assert rows["Job approved"].replace("\n", "<br>") in job._repr_html_()
job_approved = " / ".join(rows["Job approved"].splitlines())
assert f"Job approved: {job_approved};" in str(job)
# Each data owner reads every approval file, and writes only its own.
do2_file = enclave_approval_file_name(do2.email)
assert readers_of(enclave, do2_file, [do1, do2, ds]) == [do1, do2]
assert enclave_accepts_write(enclave, do2, do2_file)
assert not enclave_accepts_write(enclave, do1, do2_file)
# The submitter does not get the approval files.
assert not has_file(ds, enclave_approval_file_name(do1.email))
assert dict(ds.jobs["j"].read_permission_rows()).keys() == {"Requested"}


# -- the request is DS-writable after the approval ------------------------------
Expand Down Expand Up @@ -759,8 +807,10 @@ def test_display_lists_party_without_file():
(review / enclave_approval_file_name(do2.email)).unlink()

rows = dict(enclave.jobs["j"].read_permission_rows())
assert rows[f"Approved by {do1.email}"] == "(pending)"
assert rows[f"Approved by {do2.email}"] == "(no approval file)"
assert lines(rows["Job approved"]) == {
f"{do1.email} pending",
f"{do2.email} pending",
}


def test_job_reject_reaches_enclave():
Expand Down
5 changes: 4 additions & 1 deletion packages/syft-job/src/syft_job/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,8 +641,11 @@ def __str__(self) -> str:
base = f"{emoji} {self.name} ({self.status}{approval_info}) -> {self.datasite_owner_email}"
if self.review_reason:
base += f" | Review reason: {self.review_reason}"
# A value with a line per data owner goes on one line here. The lines
# are joined with " / ", because a line can list files with commas.
rows = "; ".join(
f"{label}: {value}" for label, value in self.read_permission_rows()
f"{label}: {' / '.join(value.splitlines())}"
for label, value in self.read_permission_rows()
)
return f"{base} | Read permissions: {rows}"

Expand Down
12 changes: 5 additions & 7 deletions packages/syft-job/src/syft_job/job_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,12 +469,7 @@ def job_info_repr_html(job: "JobInfo") -> str:
policy_details, policy_section = _policy_html(job)

read_permission_details = "".join(
f"""
<div class="syftjob-single-detail">
<div class="syftjob-single-detail-label">{escape(label)}:</div>
<div class="syftjob-single-detail-value">{escape(value)}</div>
</div>"""
for label, value in job.read_permission_rows()
_detail_html(label, value) for label, value in job.read_permission_rows()
)

return f"""
Expand Down Expand Up @@ -753,10 +748,13 @@ def job_info_repr_html(job: "JobInfo") -> str:


def _detail_html(label: str, value: str) -> str:
"""One detail row. Each line of ``value``, such as one per data owner, shows
on its own line."""
value_html = "<br>".join(escape(line) for line in value.splitlines())
return f"""
<div class="syftjob-single-detail">
<div class="syftjob-single-detail-label">{escape(label)}:</div>
<div class="syftjob-single-detail-value">{escape(value)}</div>
<div class="syftjob-single-detail-value">{value_html}</div>
</div>"""


Expand Down
Loading